blob: 09410d76160d38965149b3193fd048d071286bda [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;
440 };
441
442 // We can't check the value of a dependent argument.
443 if (TheCall->getArg(i)->isTypeDependent() ||
444 TheCall->getArg(i)->isValueDependent())
445 return false;
446
447 // Check that the immediate argument is actually a constant.
448 llvm::APSInt Result;
449 if (SemaBuiltinConstantArg(TheCall, i, Result))
450 return true;
451
452 // Range check against the upper/lower values for this instruction.
453 unsigned Val = Result.getZExtValue();
454 if (Val < l || Val > u)
455 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
456 << l << u << TheCall->getArg(i)->getSourceRange();
457
458 return false;
459}
460
Richard Smith831421f2012-06-25 20:30:08 +0000461/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
462/// parameter with the FormatAttr's correct format_idx and firstDataArg.
463/// Returns true when the format fits the function and the FormatStringInfo has
464/// been populated.
465bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
466 FormatStringInfo *FSI) {
467 FSI->HasVAListArg = Format->getFirstArg() == 0;
468 FSI->FormatIdx = Format->getFormatIdx() - 1;
469 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssond406bf02009-08-16 01:56:34 +0000470
Richard Smith831421f2012-06-25 20:30:08 +0000471 // The way the format attribute works in GCC, the implicit this argument
472 // of member functions is counted. However, it doesn't appear in our own
473 // lists, so decrement format_idx in that case.
474 if (IsCXXMember) {
475 if(FSI->FormatIdx == 0)
476 return false;
477 --FSI->FormatIdx;
478 if (FSI->FirstDataArg != 0)
479 --FSI->FirstDataArg;
480 }
481 return true;
482}
Mike Stump1eb44332009-09-09 15:08:12 +0000483
Richard Smith831421f2012-06-25 20:30:08 +0000484/// Handles the checks for format strings, non-POD arguments to vararg
485/// functions, and NULL arguments passed to non-NULL parameters.
486void Sema::checkCall(NamedDecl *FDecl, Expr **Args,
487 unsigned NumArgs,
488 unsigned NumProtoArgs,
489 bool IsMemberFunction,
490 SourceLocation Loc,
491 SourceRange Range,
492 VariadicCallType CallType) {
Daniel Dunbarde454282008-10-02 18:44:07 +0000493 // FIXME: This mechanism should be abstracted to be less fragile and
494 // more efficient. For example, just map function ids to custom
495 // handlers.
496
Ted Kremenekc82faca2010-09-09 04:33:05 +0000497 // Printf and scanf checking.
Richard Smith831421f2012-06-25 20:30:08 +0000498 bool HandledFormatString = false;
Ted Kremenekc82faca2010-09-09 04:33:05 +0000499 for (specific_attr_iterator<FormatAttr>
Richard Smith831421f2012-06-25 20:30:08 +0000500 I = FDecl->specific_attr_begin<FormatAttr>(),
501 E = FDecl->specific_attr_end<FormatAttr>(); I != E ; ++I)
Jordan Roseddcfbc92012-07-19 18:10:23 +0000502 if (CheckFormatArguments(*I, Args, NumArgs, IsMemberFunction, CallType,
503 Loc, Range))
Richard Smith831421f2012-06-25 20:30:08 +0000504 HandledFormatString = true;
505
506 // Refuse POD arguments that weren't caught by the format string
507 // checks above.
508 if (!HandledFormatString && CallType != VariadicDoesNotApply)
509 for (unsigned ArgIdx = NumProtoArgs; ArgIdx < NumArgs; ++ArgIdx)
510 variadicArgumentPODCheck(Args[ArgIdx], CallType);
Mike Stump1eb44332009-09-09 15:08:12 +0000511
Ted Kremenekc82faca2010-09-09 04:33:05 +0000512 for (specific_attr_iterator<NonNullAttr>
Richard Smith831421f2012-06-25 20:30:08 +0000513 I = FDecl->specific_attr_begin<NonNullAttr>(),
514 E = FDecl->specific_attr_end<NonNullAttr>(); I != E; ++I)
515 CheckNonNullArguments(*I, Args, Loc);
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +0000516
517 // Type safety checking.
518 for (specific_attr_iterator<ArgumentWithTypeTagAttr>
519 i = FDecl->specific_attr_begin<ArgumentWithTypeTagAttr>(),
520 e = FDecl->specific_attr_end<ArgumentWithTypeTagAttr>(); i != e; ++i) {
521 CheckArgumentWithTypeTag(*i, Args);
522 }
Richard Smith831421f2012-06-25 20:30:08 +0000523}
524
525/// CheckConstructorCall - Check a constructor call for correctness and safety
526/// properties not enforced by the C type system.
527void Sema::CheckConstructorCall(FunctionDecl *FDecl, Expr **Args,
528 unsigned NumArgs,
529 const FunctionProtoType *Proto,
530 SourceLocation Loc) {
531 VariadicCallType CallType =
532 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
533 checkCall(FDecl, Args, NumArgs, Proto->getNumArgs(),
534 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
535}
536
537/// CheckFunctionCall - Check a direct function call for various correctness
538/// and safety properties not strictly enforced by the C type system.
539bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
540 const FunctionProtoType *Proto) {
541 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall);
542 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
543 TheCall->getCallee());
544 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
545 checkCall(FDecl, TheCall->getArgs(), TheCall->getNumArgs(), NumProtoArgs,
546 IsMemberFunction, TheCall->getRParenLoc(),
547 TheCall->getCallee()->getSourceRange(), CallType);
548
549 IdentifierInfo *FnInfo = FDecl->getIdentifier();
550 // None of the checks below are needed for functions that don't have
551 // simple names (e.g., C++ conversion functions).
552 if (!FnInfo)
553 return false;
Sebastian Redl0eb23302009-01-19 00:08:26 +0000554
Anna Zaks0a151a12012-01-17 00:37:07 +0000555 unsigned CMId = FDecl->getMemoryFunctionKind();
556 if (CMId == 0)
Anna Zaksd9b859a2012-01-13 21:52:01 +0000557 return false;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000558
Anna Zaksd9b859a2012-01-13 21:52:01 +0000559 // Handle memory setting and copying functions.
Anna Zaks0a151a12012-01-17 00:37:07 +0000560 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000561 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaksc36bedc2012-02-01 19:08:57 +0000562 else if (CMId == Builtin::BIstrncat)
563 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaksd9b859a2012-01-13 21:52:01 +0000564 else
Anna Zaks0a151a12012-01-17 00:37:07 +0000565 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth7ccc95b2011-04-27 07:05:31 +0000566
Anders Carlssond406bf02009-08-16 01:56:34 +0000567 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000568}
569
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000570bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
571 Expr **Args, unsigned NumArgs) {
Richard Smith831421f2012-06-25 20:30:08 +0000572 VariadicCallType CallType =
573 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000574
Richard Smith831421f2012-06-25 20:30:08 +0000575 checkCall(Method, Args, NumArgs, Method->param_size(),
576 /*IsMemberFunction=*/false,
577 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000578
579 return false;
580}
581
Richard Smith831421f2012-06-25 20:30:08 +0000582bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall,
583 const FunctionProtoType *Proto) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000584 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
585 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000586 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000587
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000588 QualType Ty = V->getType();
589 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000590 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000591
Richard Smith831421f2012-06-25 20:30:08 +0000592 VariadicCallType CallType =
593 Proto && Proto->isVariadic() ? VariadicBlock : VariadicDoesNotApply ;
594 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
Anders Carlssond406bf02009-08-16 01:56:34 +0000595
Richard Smith831421f2012-06-25 20:30:08 +0000596 checkCall(NDecl, TheCall->getArgs(), TheCall->getNumArgs(),
597 NumProtoArgs, /*IsMemberFunction=*/false,
598 TheCall->getRParenLoc(),
599 TheCall->getCallee()->getSourceRange(), CallType);
600
Anders Carlssond406bf02009-08-16 01:56:34 +0000601 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000602}
603
Richard Smithff34d402012-04-12 05:08:17 +0000604ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
605 AtomicExpr::AtomicOp Op) {
Eli Friedman276b0612011-10-11 02:20:01 +0000606 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
607 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedman276b0612011-10-11 02:20:01 +0000608
Richard Smithff34d402012-04-12 05:08:17 +0000609 // All these operations take one of the following forms:
610 enum {
611 // C __c11_atomic_init(A *, C)
612 Init,
613 // C __c11_atomic_load(A *, int)
614 Load,
615 // void __atomic_load(A *, CP, int)
616 Copy,
617 // C __c11_atomic_add(A *, M, int)
618 Arithmetic,
619 // C __atomic_exchange_n(A *, CP, int)
620 Xchg,
621 // void __atomic_exchange(A *, C *, CP, int)
622 GNUXchg,
623 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
624 C11CmpXchg,
625 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
626 GNUCmpXchg
627 } Form = Init;
628 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
629 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
630 // where:
631 // C is an appropriate type,
632 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
633 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
634 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
635 // the int parameters are for orderings.
Eli Friedman276b0612011-10-11 02:20:01 +0000636
Richard Smithff34d402012-04-12 05:08:17 +0000637 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
638 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
639 && "need to update code for modified C11 atomics");
640 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
641 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
642 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
643 Op == AtomicExpr::AO__atomic_store_n ||
644 Op == AtomicExpr::AO__atomic_exchange_n ||
645 Op == AtomicExpr::AO__atomic_compare_exchange_n;
646 bool IsAddSub = false;
647
648 switch (Op) {
649 case AtomicExpr::AO__c11_atomic_init:
650 Form = Init;
651 break;
652
653 case AtomicExpr::AO__c11_atomic_load:
654 case AtomicExpr::AO__atomic_load_n:
655 Form = Load;
656 break;
657
658 case AtomicExpr::AO__c11_atomic_store:
659 case AtomicExpr::AO__atomic_load:
660 case AtomicExpr::AO__atomic_store:
661 case AtomicExpr::AO__atomic_store_n:
662 Form = Copy;
663 break;
664
665 case AtomicExpr::AO__c11_atomic_fetch_add:
666 case AtomicExpr::AO__c11_atomic_fetch_sub:
667 case AtomicExpr::AO__atomic_fetch_add:
668 case AtomicExpr::AO__atomic_fetch_sub:
669 case AtomicExpr::AO__atomic_add_fetch:
670 case AtomicExpr::AO__atomic_sub_fetch:
671 IsAddSub = true;
672 // Fall through.
673 case AtomicExpr::AO__c11_atomic_fetch_and:
674 case AtomicExpr::AO__c11_atomic_fetch_or:
675 case AtomicExpr::AO__c11_atomic_fetch_xor:
676 case AtomicExpr::AO__atomic_fetch_and:
677 case AtomicExpr::AO__atomic_fetch_or:
678 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smith51b92402012-04-13 06:31:38 +0000679 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithff34d402012-04-12 05:08:17 +0000680 case AtomicExpr::AO__atomic_and_fetch:
681 case AtomicExpr::AO__atomic_or_fetch:
682 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smith51b92402012-04-13 06:31:38 +0000683 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithff34d402012-04-12 05:08:17 +0000684 Form = Arithmetic;
685 break;
686
687 case AtomicExpr::AO__c11_atomic_exchange:
688 case AtomicExpr::AO__atomic_exchange_n:
689 Form = Xchg;
690 break;
691
692 case AtomicExpr::AO__atomic_exchange:
693 Form = GNUXchg;
694 break;
695
696 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
697 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
698 Form = C11CmpXchg;
699 break;
700
701 case AtomicExpr::AO__atomic_compare_exchange:
702 case AtomicExpr::AO__atomic_compare_exchange_n:
703 Form = GNUCmpXchg;
704 break;
705 }
706
707 // Check we have the right number of arguments.
708 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedman276b0612011-10-11 02:20:01 +0000709 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithff34d402012-04-12 05:08:17 +0000710 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +0000711 << TheCall->getCallee()->getSourceRange();
712 return ExprError();
Richard Smithff34d402012-04-12 05:08:17 +0000713 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
714 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedman276b0612011-10-11 02:20:01 +0000715 diag::err_typecheck_call_too_many_args)
Richard Smithff34d402012-04-12 05:08:17 +0000716 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +0000717 << TheCall->getCallee()->getSourceRange();
718 return ExprError();
719 }
720
Richard Smithff34d402012-04-12 05:08:17 +0000721 // Inspect the first argument of the atomic operation.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000722 Expr *Ptr = TheCall->getArg(0);
Eli Friedman276b0612011-10-11 02:20:01 +0000723 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
724 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
725 if (!pointerType) {
Richard Smithff34d402012-04-12 05:08:17 +0000726 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedman276b0612011-10-11 02:20:01 +0000727 << Ptr->getType() << Ptr->getSourceRange();
728 return ExprError();
729 }
730
Richard Smithff34d402012-04-12 05:08:17 +0000731 // For a __c11 builtin, this should be a pointer to an _Atomic type.
732 QualType AtomTy = pointerType->getPointeeType(); // 'A'
733 QualType ValType = AtomTy; // 'C'
734 if (IsC11) {
735 if (!AtomTy->isAtomicType()) {
736 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
737 << Ptr->getType() << Ptr->getSourceRange();
738 return ExprError();
739 }
740 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedman276b0612011-10-11 02:20:01 +0000741 }
Eli Friedman276b0612011-10-11 02:20:01 +0000742
Richard Smithff34d402012-04-12 05:08:17 +0000743 // For an arithmetic operation, the implied arithmetic must be well-formed.
744 if (Form == Arithmetic) {
745 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
746 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
747 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
748 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
749 return ExprError();
750 }
751 if (!IsAddSub && !ValType->isIntegerType()) {
752 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
753 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
754 return ExprError();
755 }
756 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
757 // For __atomic_*_n operations, the value type must be a scalar integral or
758 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedman276b0612011-10-11 02:20:01 +0000759 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithff34d402012-04-12 05:08:17 +0000760 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
761 return ExprError();
762 }
763
764 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context)) {
765 // For GNU atomics, require a trivially-copyable type. This is not part of
766 // the GNU atomics specification, but we enforce it for sanity.
767 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedman276b0612011-10-11 02:20:01 +0000768 << Ptr->getType() << Ptr->getSourceRange();
769 return ExprError();
770 }
771
Richard Smithff34d402012-04-12 05:08:17 +0000772 // FIXME: For any builtin other than a load, the ValType must not be
773 // const-qualified.
Eli Friedman276b0612011-10-11 02:20:01 +0000774
775 switch (ValType.getObjCLifetime()) {
776 case Qualifiers::OCL_None:
777 case Qualifiers::OCL_ExplicitNone:
778 // okay
779 break;
780
781 case Qualifiers::OCL_Weak:
782 case Qualifiers::OCL_Strong:
783 case Qualifiers::OCL_Autoreleasing:
Richard Smithff34d402012-04-12 05:08:17 +0000784 // FIXME: Can this happen? By this point, ValType should be known
785 // to be trivially copyable.
Eli Friedman276b0612011-10-11 02:20:01 +0000786 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
787 << ValType << Ptr->getSourceRange();
788 return ExprError();
789 }
790
791 QualType ResultType = ValType;
Richard Smithff34d402012-04-12 05:08:17 +0000792 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedman276b0612011-10-11 02:20:01 +0000793 ResultType = Context.VoidTy;
Richard Smithff34d402012-04-12 05:08:17 +0000794 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedman276b0612011-10-11 02:20:01 +0000795 ResultType = Context.BoolTy;
796
Richard Smithff34d402012-04-12 05:08:17 +0000797 // The type of a parameter passed 'by value'. In the GNU atomics, such
798 // arguments are actually passed as pointers.
799 QualType ByValType = ValType; // 'CP'
800 if (!IsC11 && !IsN)
801 ByValType = Ptr->getType();
802
Eli Friedman276b0612011-10-11 02:20:01 +0000803 // The first argument --- the pointer --- has a fixed type; we
804 // deduce the types of the rest of the arguments accordingly. Walk
805 // the remaining arguments, converting them to the deduced value type.
Richard Smithff34d402012-04-12 05:08:17 +0000806 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedman276b0612011-10-11 02:20:01 +0000807 QualType Ty;
Richard Smithff34d402012-04-12 05:08:17 +0000808 if (i < NumVals[Form] + 1) {
809 switch (i) {
810 case 1:
811 // The second argument is the non-atomic operand. For arithmetic, this
812 // is always passed by value, and for a compare_exchange it is always
813 // passed by address. For the rest, GNU uses by-address and C11 uses
814 // by-value.
815 assert(Form != Load);
816 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
817 Ty = ValType;
818 else if (Form == Copy || Form == Xchg)
819 Ty = ByValType;
820 else if (Form == Arithmetic)
821 Ty = Context.getPointerDiffType();
822 else
823 Ty = Context.getPointerType(ValType.getUnqualifiedType());
824 break;
825 case 2:
826 // The third argument to compare_exchange / GNU exchange is a
827 // (pointer to a) desired value.
828 Ty = ByValType;
829 break;
830 case 3:
831 // The fourth argument to GNU compare_exchange is a 'weak' flag.
832 Ty = Context.BoolTy;
833 break;
834 }
Eli Friedman276b0612011-10-11 02:20:01 +0000835 } else {
836 // The order(s) are always converted to int.
837 Ty = Context.IntTy;
838 }
Richard Smithff34d402012-04-12 05:08:17 +0000839
Eli Friedman276b0612011-10-11 02:20:01 +0000840 InitializedEntity Entity =
841 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithff34d402012-04-12 05:08:17 +0000842 ExprResult Arg = TheCall->getArg(i);
Eli Friedman276b0612011-10-11 02:20:01 +0000843 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
844 if (Arg.isInvalid())
845 return true;
846 TheCall->setArg(i, Arg.get());
847 }
848
Richard Smithff34d402012-04-12 05:08:17 +0000849 // Permute the arguments into a 'consistent' order.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000850 SmallVector<Expr*, 5> SubExprs;
851 SubExprs.push_back(Ptr);
Richard Smithff34d402012-04-12 05:08:17 +0000852 switch (Form) {
853 case Init:
854 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnall7a7ee302012-01-16 17:27:18 +0000855 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +0000856 break;
857 case Load:
858 SubExprs.push_back(TheCall->getArg(1)); // Order
859 break;
860 case Copy:
861 case Arithmetic:
862 case Xchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000863 SubExprs.push_back(TheCall->getArg(2)); // Order
864 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +0000865 break;
866 case GNUXchg:
867 // Note, AtomicExpr::getVal2() has a special case for this atomic.
868 SubExprs.push_back(TheCall->getArg(3)); // Order
869 SubExprs.push_back(TheCall->getArg(1)); // Val1
870 SubExprs.push_back(TheCall->getArg(2)); // Val2
871 break;
872 case C11CmpXchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000873 SubExprs.push_back(TheCall->getArg(3)); // Order
874 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000875 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall2ebb98a2012-03-29 17:58:59 +0000876 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithff34d402012-04-12 05:08:17 +0000877 break;
878 case GNUCmpXchg:
879 SubExprs.push_back(TheCall->getArg(4)); // Order
880 SubExprs.push_back(TheCall->getArg(1)); // Val1
881 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
882 SubExprs.push_back(TheCall->getArg(2)); // Val2
883 SubExprs.push_back(TheCall->getArg(3)); // Weak
884 break;
Eli Friedman276b0612011-10-11 02:20:01 +0000885 }
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000886
887 return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +0000888 SubExprs, ResultType, Op,
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000889 TheCall->getRParenLoc()));
Eli Friedman276b0612011-10-11 02:20:01 +0000890}
891
892
John McCall5f8d6042011-08-27 01:09:30 +0000893/// checkBuiltinArgument - Given a call to a builtin function, perform
894/// normal type-checking on the given argument, updating the call in
895/// place. This is useful when a builtin function requires custom
896/// type-checking for some of its arguments but not necessarily all of
897/// them.
898///
899/// Returns true on error.
900static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
901 FunctionDecl *Fn = E->getDirectCallee();
902 assert(Fn && "builtin call without direct callee!");
903
904 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
905 InitializedEntity Entity =
906 InitializedEntity::InitializeParameter(S.Context, Param);
907
908 ExprResult Arg = E->getArg(0);
909 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
910 if (Arg.isInvalid())
911 return true;
912
913 E->setArg(ArgIndex, Arg.take());
914 return false;
915}
916
Chris Lattner5caa3702009-05-08 06:58:22 +0000917/// SemaBuiltinAtomicOverloaded - We have a call to a function like
918/// __sync_fetch_and_add, which is an overloaded function based on the pointer
919/// type of its first argument. The main ActOnCallExpr routines have already
920/// promoted the types of arguments because all of these calls are prototyped as
921/// void(...).
922///
923/// This function goes through and does final semantic checking for these
924/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +0000925ExprResult
926Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000927 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +0000928 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
929 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
930
931 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +0000932 if (TheCall->getNumArgs() < 1) {
933 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
934 << 0 << 1 << TheCall->getNumArgs()
935 << TheCall->getCallee()->getSourceRange();
936 return ExprError();
937 }
Mike Stump1eb44332009-09-09 15:08:12 +0000938
Chris Lattner5caa3702009-05-08 06:58:22 +0000939 // Inspect the first argument of the atomic builtin. This should always be
940 // a pointer type, whose element is an integral scalar or pointer type.
941 // Because it is a pointer type, we don't have to worry about any implicit
942 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +0000943 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +0000944 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman8c382062012-01-23 02:35:22 +0000945 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
946 if (FirstArgResult.isInvalid())
947 return ExprError();
948 FirstArg = FirstArgResult.take();
949 TheCall->setArg(0, FirstArg);
950
John McCallf85e1932011-06-15 23:02:42 +0000951 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
952 if (!pointerType) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000953 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
954 << FirstArg->getType() << FirstArg->getSourceRange();
955 return ExprError();
956 }
Mike Stump1eb44332009-09-09 15:08:12 +0000957
John McCallf85e1932011-06-15 23:02:42 +0000958 QualType ValType = pointerType->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +0000959 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +0000960 !ValType->isBlockPointerType()) {
961 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
962 << FirstArg->getType() << FirstArg->getSourceRange();
963 return ExprError();
964 }
Chris Lattner5caa3702009-05-08 06:58:22 +0000965
John McCallf85e1932011-06-15 23:02:42 +0000966 switch (ValType.getObjCLifetime()) {
967 case Qualifiers::OCL_None:
968 case Qualifiers::OCL_ExplicitNone:
969 // okay
970 break;
971
972 case Qualifiers::OCL_Weak:
973 case Qualifiers::OCL_Strong:
974 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +0000975 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCallf85e1932011-06-15 23:02:42 +0000976 << ValType << FirstArg->getSourceRange();
977 return ExprError();
978 }
979
John McCallb45ae252011-10-05 07:41:44 +0000980 // Strip any qualifiers off ValType.
981 ValType = ValType.getUnqualifiedType();
982
Chandler Carruth8d13d222010-07-18 20:54:12 +0000983 // The majority of builtins return a value, but a few have special return
984 // types, so allow them to override appropriately below.
985 QualType ResultType = ValType;
986
Chris Lattner5caa3702009-05-08 06:58:22 +0000987 // We need to figure out which concrete builtin this maps onto. For example,
988 // __sync_fetch_and_add with a 2 byte object turns into
989 // __sync_fetch_and_add_2.
990#define BUILTIN_ROW(x) \
991 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
992 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +0000993
Chris Lattner5caa3702009-05-08 06:58:22 +0000994 static const unsigned BuiltinIndices[][5] = {
995 BUILTIN_ROW(__sync_fetch_and_add),
996 BUILTIN_ROW(__sync_fetch_and_sub),
997 BUILTIN_ROW(__sync_fetch_and_or),
998 BUILTIN_ROW(__sync_fetch_and_and),
999 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +00001000
Chris Lattner5caa3702009-05-08 06:58:22 +00001001 BUILTIN_ROW(__sync_add_and_fetch),
1002 BUILTIN_ROW(__sync_sub_and_fetch),
1003 BUILTIN_ROW(__sync_and_and_fetch),
1004 BUILTIN_ROW(__sync_or_and_fetch),
1005 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +00001006
Chris Lattner5caa3702009-05-08 06:58:22 +00001007 BUILTIN_ROW(__sync_val_compare_and_swap),
1008 BUILTIN_ROW(__sync_bool_compare_and_swap),
1009 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +00001010 BUILTIN_ROW(__sync_lock_release),
1011 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +00001012 };
Mike Stump1eb44332009-09-09 15:08:12 +00001013#undef BUILTIN_ROW
1014
Chris Lattner5caa3702009-05-08 06:58:22 +00001015 // Determine the index of the size.
1016 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +00001017 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +00001018 case 1: SizeIndex = 0; break;
1019 case 2: SizeIndex = 1; break;
1020 case 4: SizeIndex = 2; break;
1021 case 8: SizeIndex = 3; break;
1022 case 16: SizeIndex = 4; break;
1023 default:
Chandler Carruthd2014572010-07-09 18:59:35 +00001024 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1025 << FirstArg->getType() << FirstArg->getSourceRange();
1026 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +00001027 }
Mike Stump1eb44332009-09-09 15:08:12 +00001028
Chris Lattner5caa3702009-05-08 06:58:22 +00001029 // Each of these builtins has one pointer argument, followed by some number of
1030 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1031 // that we ignore. Find out which row of BuiltinIndices to read from as well
1032 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00001033 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +00001034 unsigned BuiltinIndex, NumFixed = 1;
1035 switch (BuiltinID) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001036 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregora9766412011-11-28 16:30:08 +00001037 case Builtin::BI__sync_fetch_and_add:
1038 case Builtin::BI__sync_fetch_and_add_1:
1039 case Builtin::BI__sync_fetch_and_add_2:
1040 case Builtin::BI__sync_fetch_and_add_4:
1041 case Builtin::BI__sync_fetch_and_add_8:
1042 case Builtin::BI__sync_fetch_and_add_16:
1043 BuiltinIndex = 0;
1044 break;
1045
1046 case Builtin::BI__sync_fetch_and_sub:
1047 case Builtin::BI__sync_fetch_and_sub_1:
1048 case Builtin::BI__sync_fetch_and_sub_2:
1049 case Builtin::BI__sync_fetch_and_sub_4:
1050 case Builtin::BI__sync_fetch_and_sub_8:
1051 case Builtin::BI__sync_fetch_and_sub_16:
1052 BuiltinIndex = 1;
1053 break;
1054
1055 case Builtin::BI__sync_fetch_and_or:
1056 case Builtin::BI__sync_fetch_and_or_1:
1057 case Builtin::BI__sync_fetch_and_or_2:
1058 case Builtin::BI__sync_fetch_and_or_4:
1059 case Builtin::BI__sync_fetch_and_or_8:
1060 case Builtin::BI__sync_fetch_and_or_16:
1061 BuiltinIndex = 2;
1062 break;
1063
1064 case Builtin::BI__sync_fetch_and_and:
1065 case Builtin::BI__sync_fetch_and_and_1:
1066 case Builtin::BI__sync_fetch_and_and_2:
1067 case Builtin::BI__sync_fetch_and_and_4:
1068 case Builtin::BI__sync_fetch_and_and_8:
1069 case Builtin::BI__sync_fetch_and_and_16:
1070 BuiltinIndex = 3;
1071 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001072
Douglas Gregora9766412011-11-28 16:30:08 +00001073 case Builtin::BI__sync_fetch_and_xor:
1074 case Builtin::BI__sync_fetch_and_xor_1:
1075 case Builtin::BI__sync_fetch_and_xor_2:
1076 case Builtin::BI__sync_fetch_and_xor_4:
1077 case Builtin::BI__sync_fetch_and_xor_8:
1078 case Builtin::BI__sync_fetch_and_xor_16:
1079 BuiltinIndex = 4;
1080 break;
1081
1082 case Builtin::BI__sync_add_and_fetch:
1083 case Builtin::BI__sync_add_and_fetch_1:
1084 case Builtin::BI__sync_add_and_fetch_2:
1085 case Builtin::BI__sync_add_and_fetch_4:
1086 case Builtin::BI__sync_add_and_fetch_8:
1087 case Builtin::BI__sync_add_and_fetch_16:
1088 BuiltinIndex = 5;
1089 break;
1090
1091 case Builtin::BI__sync_sub_and_fetch:
1092 case Builtin::BI__sync_sub_and_fetch_1:
1093 case Builtin::BI__sync_sub_and_fetch_2:
1094 case Builtin::BI__sync_sub_and_fetch_4:
1095 case Builtin::BI__sync_sub_and_fetch_8:
1096 case Builtin::BI__sync_sub_and_fetch_16:
1097 BuiltinIndex = 6;
1098 break;
1099
1100 case Builtin::BI__sync_and_and_fetch:
1101 case Builtin::BI__sync_and_and_fetch_1:
1102 case Builtin::BI__sync_and_and_fetch_2:
1103 case Builtin::BI__sync_and_and_fetch_4:
1104 case Builtin::BI__sync_and_and_fetch_8:
1105 case Builtin::BI__sync_and_and_fetch_16:
1106 BuiltinIndex = 7;
1107 break;
1108
1109 case Builtin::BI__sync_or_and_fetch:
1110 case Builtin::BI__sync_or_and_fetch_1:
1111 case Builtin::BI__sync_or_and_fetch_2:
1112 case Builtin::BI__sync_or_and_fetch_4:
1113 case Builtin::BI__sync_or_and_fetch_8:
1114 case Builtin::BI__sync_or_and_fetch_16:
1115 BuiltinIndex = 8;
1116 break;
1117
1118 case Builtin::BI__sync_xor_and_fetch:
1119 case Builtin::BI__sync_xor_and_fetch_1:
1120 case Builtin::BI__sync_xor_and_fetch_2:
1121 case Builtin::BI__sync_xor_and_fetch_4:
1122 case Builtin::BI__sync_xor_and_fetch_8:
1123 case Builtin::BI__sync_xor_and_fetch_16:
1124 BuiltinIndex = 9;
1125 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001126
Chris Lattner5caa3702009-05-08 06:58:22 +00001127 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001128 case Builtin::BI__sync_val_compare_and_swap_1:
1129 case Builtin::BI__sync_val_compare_and_swap_2:
1130 case Builtin::BI__sync_val_compare_and_swap_4:
1131 case Builtin::BI__sync_val_compare_and_swap_8:
1132 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001133 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +00001134 NumFixed = 2;
1135 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001136
Chris Lattner5caa3702009-05-08 06:58:22 +00001137 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001138 case Builtin::BI__sync_bool_compare_and_swap_1:
1139 case Builtin::BI__sync_bool_compare_and_swap_2:
1140 case Builtin::BI__sync_bool_compare_and_swap_4:
1141 case Builtin::BI__sync_bool_compare_and_swap_8:
1142 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001143 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +00001144 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001145 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001146 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001147
1148 case Builtin::BI__sync_lock_test_and_set:
1149 case Builtin::BI__sync_lock_test_and_set_1:
1150 case Builtin::BI__sync_lock_test_and_set_2:
1151 case Builtin::BI__sync_lock_test_and_set_4:
1152 case Builtin::BI__sync_lock_test_and_set_8:
1153 case Builtin::BI__sync_lock_test_and_set_16:
1154 BuiltinIndex = 12;
1155 break;
1156
Chris Lattner5caa3702009-05-08 06:58:22 +00001157 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +00001158 case Builtin::BI__sync_lock_release_1:
1159 case Builtin::BI__sync_lock_release_2:
1160 case Builtin::BI__sync_lock_release_4:
1161 case Builtin::BI__sync_lock_release_8:
1162 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001163 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +00001164 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001165 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001166 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001167
1168 case Builtin::BI__sync_swap:
1169 case Builtin::BI__sync_swap_1:
1170 case Builtin::BI__sync_swap_2:
1171 case Builtin::BI__sync_swap_4:
1172 case Builtin::BI__sync_swap_8:
1173 case Builtin::BI__sync_swap_16:
1174 BuiltinIndex = 14;
1175 break;
Chris Lattner5caa3702009-05-08 06:58:22 +00001176 }
Mike Stump1eb44332009-09-09 15:08:12 +00001177
Chris Lattner5caa3702009-05-08 06:58:22 +00001178 // Now that we know how many fixed arguments we expect, first check that we
1179 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +00001180 if (TheCall->getNumArgs() < 1+NumFixed) {
1181 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1182 << 0 << 1+NumFixed << TheCall->getNumArgs()
1183 << TheCall->getCallee()->getSourceRange();
1184 return ExprError();
1185 }
Mike Stump1eb44332009-09-09 15:08:12 +00001186
Chris Lattnere7ac0a92009-05-08 15:36:58 +00001187 // Get the decl for the concrete builtin from this, we can tell what the
1188 // concrete integer type we should convert to is.
1189 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1190 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
1191 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump1eb44332009-09-09 15:08:12 +00001192 FunctionDecl *NewBuiltinDecl =
Chris Lattnere7ac0a92009-05-08 15:36:58 +00001193 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
1194 TUScope, false, DRE->getLocStart()));
Chandler Carruthd2014572010-07-09 18:59:35 +00001195
John McCallf871d0c2010-08-07 06:22:56 +00001196 // The first argument --- the pointer --- has a fixed type; we
1197 // deduce the types of the rest of the arguments accordingly. Walk
1198 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +00001199 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +00001200 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +00001201
Chris Lattner5caa3702009-05-08 06:58:22 +00001202 // GCC does an implicit conversion to the pointer or integer ValType. This
1203 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb45ae252011-10-05 07:41:44 +00001204 // Initialize the argument.
1205 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1206 ValType, /*consume*/ false);
1207 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley429bb272011-04-08 18:41:53 +00001208 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +00001209 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001210
Chris Lattner5caa3702009-05-08 06:58:22 +00001211 // Okay, we have something that *can* be converted to the right type. Check
1212 // to see if there is a potentially weird extension going on here. This can
1213 // happen when you do an atomic operation on something like an char* and
1214 // pass in 42. The 42 gets converted to char. This is even more strange
1215 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +00001216 // FIXME: Do this check.
John McCallb45ae252011-10-05 07:41:44 +00001217 TheCall->setArg(i+1, Arg.take());
Chris Lattner5caa3702009-05-08 06:58:22 +00001218 }
Mike Stump1eb44332009-09-09 15:08:12 +00001219
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001220 ASTContext& Context = this->getASTContext();
1221
1222 // Create a new DeclRefExpr to refer to the new decl.
1223 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1224 Context,
1225 DRE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001226 SourceLocation(),
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001227 NewBuiltinDecl,
John McCallf4b88a42012-03-10 09:33:50 +00001228 /*enclosing*/ false,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001229 DRE->getLocation(),
1230 NewBuiltinDecl->getType(),
1231 DRE->getValueKind());
Mike Stump1eb44332009-09-09 15:08:12 +00001232
Chris Lattner5caa3702009-05-08 06:58:22 +00001233 // Set the callee in the CallExpr.
1234 // FIXME: This leaks the original parens and implicit casts.
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001235 ExprResult PromotedCall = UsualUnaryConversions(NewDRE);
John Wiegley429bb272011-04-08 18:41:53 +00001236 if (PromotedCall.isInvalid())
1237 return ExprError();
1238 TheCall->setCallee(PromotedCall.take());
Mike Stump1eb44332009-09-09 15:08:12 +00001239
Chandler Carruthdb4325b2010-07-18 07:23:17 +00001240 // Change the result type of the call to match the original value type. This
1241 // is arbitrary, but the codegen for these builtins ins design to handle it
1242 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +00001243 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +00001244
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001245 return TheCallResult;
Chris Lattner5caa3702009-05-08 06:58:22 +00001246}
1247
Chris Lattner69039812009-02-18 06:01:06 +00001248/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +00001249/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +00001250/// Note: It might also make sense to do the UTF-16 conversion here (would
1251/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +00001252bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +00001253 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +00001254 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1255
Douglas Gregor5cee1192011-07-27 05:40:30 +00001256 if (!Literal || !Literal->isAscii()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001257 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1258 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001259 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +00001260 }
Mike Stump1eb44332009-09-09 15:08:12 +00001261
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001262 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001263 StringRef String = Literal->getString();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001264 unsigned NumBytes = String.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001265 SmallVector<UTF16, 128> ToBuf(NumBytes);
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001266 const UTF8 *FromPtr = (UTF8 *)String.data();
1267 UTF16 *ToPtr = &ToBuf[0];
1268
1269 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1270 &ToPtr, ToPtr + NumBytes,
1271 strictConversion);
1272 // Check for conversion failure.
1273 if (Result != conversionOK)
1274 Diag(Arg->getLocStart(),
1275 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1276 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001277 return false;
Chris Lattner59907c42007-08-10 20:18:51 +00001278}
1279
Chris Lattnerc27c6652007-12-20 00:05:45 +00001280/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1281/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +00001282bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1283 Expr *Fn = TheCall->getCallee();
1284 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +00001285 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001286 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001287 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1288 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +00001289 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001290 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +00001291 return true;
1292 }
Eli Friedman56f20ae2008-12-15 22:05:35 +00001293
1294 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +00001295 return Diag(TheCall->getLocEnd(),
1296 diag::err_typecheck_call_too_few_args_at_least)
1297 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +00001298 }
1299
John McCall5f8d6042011-08-27 01:09:30 +00001300 // Type-check the first argument normally.
1301 if (checkBuiltinArgument(*this, TheCall, 0))
1302 return true;
1303
Chris Lattnerc27c6652007-12-20 00:05:45 +00001304 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001305 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +00001306 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001307 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +00001308 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +00001309 else if (FunctionDecl *FD = getCurFunctionDecl())
1310 isVariadic = FD->isVariadic();
1311 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001312 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +00001313
Chris Lattnerc27c6652007-12-20 00:05:45 +00001314 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001315 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1316 return true;
1317 }
Mike Stump1eb44332009-09-09 15:08:12 +00001318
Chris Lattner30ce3442007-12-19 23:59:04 +00001319 // Verify that the second argument to the builtin is the last argument of the
1320 // current function or method.
1321 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +00001322 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001323
Anders Carlsson88cf2262008-02-11 04:20:54 +00001324 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1325 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001326 // FIXME: This isn't correct for methods (results in bogus warning).
1327 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +00001328 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001329 if (CurBlock)
1330 LastArg = *(CurBlock->TheDecl->param_end()-1);
1331 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +00001332 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001333 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001334 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001335 SecondArgIsLastNamedArgument = PV == LastArg;
1336 }
1337 }
Mike Stump1eb44332009-09-09 15:08:12 +00001338
Chris Lattner30ce3442007-12-19 23:59:04 +00001339 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001340 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +00001341 diag::warn_second_parameter_of_va_start_not_last_named_argument);
1342 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +00001343}
Chris Lattner30ce3442007-12-19 23:59:04 +00001344
Chris Lattner1b9a0792007-12-20 00:26:33 +00001345/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1346/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +00001347bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1348 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +00001349 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001350 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +00001351 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +00001352 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001353 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001354 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001355 << SourceRange(TheCall->getArg(2)->getLocStart(),
1356 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001357
John Wiegley429bb272011-04-08 18:41:53 +00001358 ExprResult OrigArg0 = TheCall->getArg(0);
1359 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +00001360
Chris Lattner1b9a0792007-12-20 00:26:33 +00001361 // Do standard promotions between the two arguments, returning their common
1362 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +00001363 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +00001364 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1365 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +00001366
1367 // Make sure any conversions are pushed back into the call; this is
1368 // type safe since unordered compare builtins are declared as "_Bool
1369 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +00001370 TheCall->setArg(0, OrigArg0.get());
1371 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001372
John Wiegley429bb272011-04-08 18:41:53 +00001373 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +00001374 return false;
1375
Chris Lattner1b9a0792007-12-20 00:26:33 +00001376 // If the common type isn't a real floating type, then the arguments were
1377 // invalid for this operation.
Eli Friedman860a3192012-06-16 02:19:17 +00001378 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +00001379 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001380 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +00001381 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1382 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001383
Chris Lattner1b9a0792007-12-20 00:26:33 +00001384 return false;
1385}
1386
Benjamin Kramere771a7a2010-02-15 22:42:31 +00001387/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1388/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001389/// to check everything. We expect the last argument to be a floating point
1390/// value.
1391bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1392 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +00001393 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001394 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001395 if (TheCall->getNumArgs() > NumArgs)
1396 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001397 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001398 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001399 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001400 (*(TheCall->arg_end()-1))->getLocEnd());
1401
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001402 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001403
Eli Friedman9ac6f622009-08-31 20:06:00 +00001404 if (OrigArg->isTypeDependent())
1405 return false;
1406
Chris Lattner81368fb2010-05-06 05:50:07 +00001407 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +00001408 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +00001409 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001410 diag::err_typecheck_call_invalid_unary_fp)
1411 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001412
Chris Lattner81368fb2010-05-06 05:50:07 +00001413 // If this is an implicit conversion from float -> double, remove it.
1414 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1415 Expr *CastArg = Cast->getSubExpr();
1416 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1417 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1418 "promotion from float to double is the only expected cast here");
1419 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +00001420 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner81368fb2010-05-06 05:50:07 +00001421 }
1422 }
1423
Eli Friedman9ac6f622009-08-31 20:06:00 +00001424 return false;
1425}
1426
Eli Friedmand38617c2008-05-14 19:38:39 +00001427/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1428// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +00001429ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001430 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001431 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +00001432 diag::err_typecheck_call_too_few_args_at_least)
Nate Begeman37b6a572010-06-08 00:16:34 +00001433 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherd77b9a22010-04-16 04:48:22 +00001434 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001435
Nate Begeman37b6a572010-06-08 00:16:34 +00001436 // Determine which of the following types of shufflevector we're checking:
1437 // 1) unary, vector mask: (lhs, mask)
1438 // 2) binary, vector mask: (lhs, rhs, mask)
1439 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1440 QualType resType = TheCall->getArg(0)->getType();
1441 unsigned numElements = 0;
1442
Douglas Gregorcde01732009-05-19 22:10:17 +00001443 if (!TheCall->getArg(0)->isTypeDependent() &&
1444 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001445 QualType LHSType = TheCall->getArg(0)->getType();
1446 QualType RHSType = TheCall->getArg(1)->getType();
1447
1448 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001449 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001450 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001451 TheCall->getArg(1)->getLocEnd());
1452 return ExprError();
1453 }
Nate Begeman37b6a572010-06-08 00:16:34 +00001454
1455 numElements = LHSType->getAs<VectorType>()->getNumElements();
1456 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +00001457
Nate Begeman37b6a572010-06-08 00:16:34 +00001458 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1459 // with mask. If so, verify that RHS is an integer vector type with the
1460 // same number of elts as lhs.
1461 if (TheCall->getNumArgs() == 2) {
Douglas Gregorf6094622010-07-23 15:58:24 +00001462 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +00001463 RHSType->getAs<VectorType>()->getNumElements() != numElements)
1464 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1465 << SourceRange(TheCall->getArg(1)->getLocStart(),
1466 TheCall->getArg(1)->getLocEnd());
1467 numResElements = numElements;
1468 }
1469 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001470 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001471 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001472 TheCall->getArg(1)->getLocEnd());
1473 return ExprError();
Nate Begeman37b6a572010-06-08 00:16:34 +00001474 } else if (numElements != numResElements) {
1475 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +00001476 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001477 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +00001478 }
Eli Friedmand38617c2008-05-14 19:38:39 +00001479 }
1480
1481 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001482 if (TheCall->getArg(i)->isTypeDependent() ||
1483 TheCall->getArg(i)->isValueDependent())
1484 continue;
1485
Nate Begeman37b6a572010-06-08 00:16:34 +00001486 llvm::APSInt Result(32);
1487 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1488 return ExprError(Diag(TheCall->getLocStart(),
1489 diag::err_shufflevector_nonconstant_argument)
1490 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001491
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001492 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001493 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001494 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001495 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001496 }
1497
Chris Lattner5f9e2722011-07-23 10:55:15 +00001498 SmallVector<Expr*, 32> exprs;
Eli Friedmand38617c2008-05-14 19:38:39 +00001499
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001500 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +00001501 exprs.push_back(TheCall->getArg(i));
1502 TheCall->setArg(i, 0);
1503 }
1504
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001505 return Owned(new (Context) ShuffleVectorExpr(Context, exprs, resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001506 TheCall->getCallee()->getLocStart(),
1507 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +00001508}
Chris Lattner30ce3442007-12-19 23:59:04 +00001509
Daniel Dunbar4493f792008-07-21 22:59:13 +00001510/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1511// This is declared to take (const void*, ...) and can take two
1512// optional constant int args.
1513bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001514 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001515
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001516 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +00001517 return Diag(TheCall->getLocEnd(),
1518 diag::err_typecheck_call_too_many_args_at_most)
1519 << 0 /*function call*/ << 3 << NumArgs
1520 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001521
1522 // Argument 0 is checked for us and the remaining arguments must be
1523 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001524 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +00001525 Expr *Arg = TheCall->getArg(i);
Douglas Gregor592a4232012-06-29 01:05:22 +00001526
1527 // We can't check the value of a dependent argument.
1528 if (Arg->isTypeDependent() || Arg->isValueDependent())
1529 continue;
1530
Eli Friedman9aef7262009-12-04 00:30:06 +00001531 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +00001532 if (SemaBuiltinConstantArg(TheCall, i, Result))
1533 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001534
Daniel Dunbar4493f792008-07-21 22:59:13 +00001535 // FIXME: gcc issues a warning and rewrites these to 0. These
1536 // seems especially odd for the third argument since the default
1537 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001538 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +00001539 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001540 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001541 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001542 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +00001543 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001544 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001545 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001546 }
1547 }
1548
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001549 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +00001550}
1551
Eric Christopher691ebc32010-04-17 02:26:23 +00001552/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1553/// TheCall is a constant expression.
1554bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1555 llvm::APSInt &Result) {
1556 Expr *Arg = TheCall->getArg(ArgNum);
1557 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1558 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1559
1560 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1561
1562 if (!Arg->isIntegerConstantExpr(Result, Context))
1563 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +00001564 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +00001565
Chris Lattner21fb98e2009-09-23 06:06:36 +00001566 return false;
1567}
1568
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001569/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1570/// int type). This simply type checks that type is one of the defined
1571/// constants (0-3).
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001572// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001573bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +00001574 llvm::APSInt Result;
Douglas Gregor592a4232012-06-29 01:05:22 +00001575
1576 // We can't check the value of a dependent argument.
1577 if (TheCall->getArg(1)->isTypeDependent() ||
1578 TheCall->getArg(1)->isValueDependent())
1579 return false;
1580
Eric Christopher691ebc32010-04-17 02:26:23 +00001581 // Check constant-ness first.
1582 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1583 return true;
1584
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001585 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001586 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001587 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1588 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001589 }
1590
1591 return false;
1592}
1593
Eli Friedman586d6a82009-05-03 06:04:26 +00001594/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +00001595/// This checks that val is a constant 1.
1596bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1597 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +00001598 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +00001599
Eric Christopher691ebc32010-04-17 02:26:23 +00001600 // TODO: This is less than ideal. Overload this to take a value.
1601 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1602 return true;
1603
1604 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +00001605 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1606 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1607
1608 return false;
1609}
1610
Richard Smith831421f2012-06-25 20:30:08 +00001611// Determine if an expression is a string literal or constant string.
1612// If this function returns false on the arguments to a function expecting a
1613// format string, we will usually need to emit a warning.
1614// True string literals are then checked by CheckFormatString.
1615Sema::StringLiteralCheckType
1616Sema::checkFormatStringExpr(const Expr *E, Expr **Args,
1617 unsigned NumArgs, bool HasVAListArg,
1618 unsigned format_idx, unsigned firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001619 FormatStringType Type, VariadicCallType CallType,
1620 bool inFunctionCall) {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001621 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +00001622 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith831421f2012-06-25 20:30:08 +00001623 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001624
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001625 E = E->IgnoreParenCasts();
Peter Collingbournef111d932011-04-15 00:35:48 +00001626
David Blaikiea73cdcb2012-02-10 21:07:25 +00001627 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
1628 // Technically -Wformat-nonliteral does not warn about this case.
1629 // The behavior of printf and friends in this case is implementation
1630 // dependent. Ideally if the format string cannot be null then
1631 // it should have a 'nonnull' attribute in the function prototype.
Richard Smith831421f2012-06-25 20:30:08 +00001632 return SLCT_CheckedLiteral;
David Blaikiea73cdcb2012-02-10 21:07:25 +00001633
Ted Kremenekd30ef872009-01-12 23:09:09 +00001634 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +00001635 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +00001636 case Stmt::ConditionalOperatorClass: {
Richard Smith831421f2012-06-25 20:30:08 +00001637 // The expression is a literal if both sub-expressions were, and it was
1638 // completely checked only if both sub-expressions were checked.
1639 const AbstractConditionalOperator *C =
1640 cast<AbstractConditionalOperator>(E);
1641 StringLiteralCheckType Left =
1642 checkFormatStringExpr(C->getTrueExpr(), Args, NumArgs,
1643 HasVAListArg, format_idx, firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001644 Type, CallType, inFunctionCall);
Richard Smith831421f2012-06-25 20:30:08 +00001645 if (Left == SLCT_NotALiteral)
1646 return SLCT_NotALiteral;
1647 StringLiteralCheckType Right =
1648 checkFormatStringExpr(C->getFalseExpr(), Args, NumArgs,
1649 HasVAListArg, format_idx, firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001650 Type, CallType, inFunctionCall);
Richard Smith831421f2012-06-25 20:30:08 +00001651 return Left < Right ? Left : Right;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001652 }
1653
1654 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001655 E = cast<ImplicitCastExpr>(E)->getSubExpr();
1656 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001657 }
1658
John McCall56ca35d2011-02-17 10:25:35 +00001659 case Stmt::OpaqueValueExprClass:
1660 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
1661 E = src;
1662 goto tryAgain;
1663 }
Richard Smith831421f2012-06-25 20:30:08 +00001664 return SLCT_NotALiteral;
John McCall56ca35d2011-02-17 10:25:35 +00001665
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001666 case Stmt::PredefinedExprClass:
1667 // While __func__, etc., are technically not string literals, they
1668 // cannot contain format specifiers and thus are not a security
1669 // liability.
Richard Smith831421f2012-06-25 20:30:08 +00001670 return SLCT_UncheckedLiteral;
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001671
Ted Kremenek082d9362009-03-20 21:35:28 +00001672 case Stmt::DeclRefExprClass: {
1673 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001674
Ted Kremenek082d9362009-03-20 21:35:28 +00001675 // As an exception, do not flag errors for variables binding to
1676 // const string literals.
1677 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1678 bool isConstant = false;
1679 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001680
Ted Kremenek082d9362009-03-20 21:35:28 +00001681 if (const ArrayType *AT = Context.getAsArrayType(T)) {
1682 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001683 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001684 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +00001685 PT->getPointeeType().isConstant(Context);
Jean-Daniel Dupase98e5b52012-01-25 10:35:33 +00001686 } else if (T->isObjCObjectPointerType()) {
1687 // In ObjC, there is usually no "const ObjectPointer" type,
1688 // so don't check if the pointee type is constant.
1689 isConstant = T.isConstant(Context);
Ted Kremenek082d9362009-03-20 21:35:28 +00001690 }
Mike Stump1eb44332009-09-09 15:08:12 +00001691
Ted Kremenek082d9362009-03-20 21:35:28 +00001692 if (isConstant) {
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00001693 if (const Expr *Init = VD->getAnyInitializer()) {
1694 // Look through initializers like const char c[] = { "foo" }
1695 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
1696 if (InitList->isStringLiteralInit())
1697 Init = InitList->getInit(0)->IgnoreParenImpCasts();
1698 }
Richard Smith831421f2012-06-25 20:30:08 +00001699 return checkFormatStringExpr(Init, Args, NumArgs,
1700 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001701 firstDataArg, Type, CallType,
Richard Smith831421f2012-06-25 20:30:08 +00001702 /*inFunctionCall*/false);
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00001703 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001704 }
Mike Stump1eb44332009-09-09 15:08:12 +00001705
Anders Carlssond966a552009-06-28 19:55:58 +00001706 // For vprintf* functions (i.e., HasVAListArg==true), we add a
1707 // special check to see if the format string is a function parameter
1708 // of the function calling the printf function. If the function
1709 // has an attribute indicating it is a printf-like function, then we
1710 // should suppress warnings concerning non-literals being used in a call
1711 // to a vprintf function. For example:
1712 //
1713 // void
1714 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1715 // va_list ap;
1716 // va_start(ap, fmt);
1717 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
1718 // ...
1719 //
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00001720 if (HasVAListArg) {
1721 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
1722 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
1723 int PVIndex = PV->getFunctionScopeIndex() + 1;
1724 for (specific_attr_iterator<FormatAttr>
1725 i = ND->specific_attr_begin<FormatAttr>(),
1726 e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) {
1727 FormatAttr *PVFormat = *i;
1728 // adjust for implicit parameter
1729 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1730 if (MD->isInstance())
1731 ++PVIndex;
1732 // We also check if the formats are compatible.
1733 // We can't pass a 'scanf' string to a 'printf' function.
1734 if (PVIndex == PVFormat->getFormatIdx() &&
1735 Type == GetFormatStringType(PVFormat))
Richard Smith831421f2012-06-25 20:30:08 +00001736 return SLCT_UncheckedLiteral;
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00001737 }
1738 }
1739 }
1740 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001741 }
Mike Stump1eb44332009-09-09 15:08:12 +00001742
Richard Smith831421f2012-06-25 20:30:08 +00001743 return SLCT_NotALiteral;
Ted Kremenek082d9362009-03-20 21:35:28 +00001744 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00001745
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001746 case Stmt::CallExprClass:
1747 case Stmt::CXXMemberCallExprClass: {
Anders Carlsson8f031b32009-06-27 04:05:33 +00001748 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001749 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
1750 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
1751 unsigned ArgIndex = FA->getFormatIdx();
1752 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1753 if (MD->isInstance())
1754 --ArgIndex;
1755 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001756
Richard Smith831421f2012-06-25 20:30:08 +00001757 return checkFormatStringExpr(Arg, Args, NumArgs,
1758 HasVAListArg, format_idx, firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001759 Type, CallType, inFunctionCall);
Jordan Rose50687312012-06-04 23:52:23 +00001760 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
1761 unsigned BuiltinID = FD->getBuiltinID();
1762 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
1763 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
1764 const Expr *Arg = CE->getArg(0);
Richard Smith831421f2012-06-25 20:30:08 +00001765 return checkFormatStringExpr(Arg, Args, NumArgs,
1766 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001767 firstDataArg, Type, CallType,
1768 inFunctionCall);
Jordan Rose50687312012-06-04 23:52:23 +00001769 }
Anders Carlsson8f031b32009-06-27 04:05:33 +00001770 }
1771 }
Mike Stump1eb44332009-09-09 15:08:12 +00001772
Richard Smith831421f2012-06-25 20:30:08 +00001773 return SLCT_NotALiteral;
Anders Carlsson8f031b32009-06-27 04:05:33 +00001774 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001775 case Stmt::ObjCStringLiteralClass:
1776 case Stmt::StringLiteralClass: {
1777 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001778
Ted Kremenek082d9362009-03-20 21:35:28 +00001779 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00001780 StrE = ObjCFExpr->getString();
1781 else
Ted Kremenek082d9362009-03-20 21:35:28 +00001782 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001783
Ted Kremenekd30ef872009-01-12 23:09:09 +00001784 if (StrE) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001785 CheckFormatString(StrE, E, Args, NumArgs, HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001786 firstDataArg, Type, inFunctionCall, CallType);
Richard Smith831421f2012-06-25 20:30:08 +00001787 return SLCT_CheckedLiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001788 }
Mike Stump1eb44332009-09-09 15:08:12 +00001789
Richard Smith831421f2012-06-25 20:30:08 +00001790 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001791 }
Mike Stump1eb44332009-09-09 15:08:12 +00001792
Ted Kremenek082d9362009-03-20 21:35:28 +00001793 default:
Richard Smith831421f2012-06-25 20:30:08 +00001794 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001795 }
1796}
1797
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001798void
Mike Stump1eb44332009-09-09 15:08:12 +00001799Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewycky909a70d2011-03-25 01:44:32 +00001800 const Expr * const *ExprArgs,
1801 SourceLocation CallSiteLoc) {
Sean Huntcf807c42010-08-18 23:23:40 +00001802 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1803 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001804 i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +00001805 const Expr *ArgExpr = ExprArgs[*i];
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001806 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00001807 Expr::NPC_ValueDependentIsNotNull))
Nick Lewycky909a70d2011-03-25 01:44:32 +00001808 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001809 }
1810}
Ted Kremenekd30ef872009-01-12 23:09:09 +00001811
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001812Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
1813 return llvm::StringSwitch<FormatStringType>(Format->getType())
1814 .Case("scanf", FST_Scanf)
1815 .Cases("printf", "printf0", FST_Printf)
1816 .Cases("NSString", "CFString", FST_NSString)
1817 .Case("strftime", FST_Strftime)
1818 .Case("strfmon", FST_Strfmon)
1819 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
1820 .Default(FST_Unknown);
1821}
1822
Jordan Roseddcfbc92012-07-19 18:10:23 +00001823/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek826a3452010-07-16 02:11:22 +00001824/// functions) for correct use of format strings.
Richard Smith831421f2012-06-25 20:30:08 +00001825/// Returns true if a format string has been fully checked.
Richard Smith831421f2012-06-25 20:30:08 +00001826bool Sema::CheckFormatArguments(const FormatAttr *Format, Expr **Args,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001827 unsigned NumArgs, bool IsCXXMember,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001828 VariadicCallType CallType,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001829 SourceLocation Loc, SourceRange Range) {
Richard Smith831421f2012-06-25 20:30:08 +00001830 FormatStringInfo FSI;
1831 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
1832 return CheckFormatArguments(Args, NumArgs, FSI.HasVAListArg, FSI.FormatIdx,
1833 FSI.FirstDataArg, GetFormatStringType(Format),
Jordan Roseddcfbc92012-07-19 18:10:23 +00001834 CallType, Loc, Range);
Richard Smith831421f2012-06-25 20:30:08 +00001835 return false;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001836}
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001837
Richard Smith831421f2012-06-25 20:30:08 +00001838bool Sema::CheckFormatArguments(Expr **Args, unsigned NumArgs,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001839 bool HasVAListArg, unsigned format_idx,
1840 unsigned firstDataArg, FormatStringType Type,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001841 VariadicCallType CallType,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001842 SourceLocation Loc, SourceRange Range) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001843 // CHECK: printf/scanf-like function is called with no format string.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001844 if (format_idx >= NumArgs) {
1845 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith831421f2012-06-25 20:30:08 +00001846 return false;
Ted Kremenek71895b92007-08-14 17:39:48 +00001847 }
Mike Stump1eb44332009-09-09 15:08:12 +00001848
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001849 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001850
Chris Lattner59907c42007-08-10 20:18:51 +00001851 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001852 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001853 // Dynamically generated format strings are difficult to
1854 // automatically vet at compile time. Requiring that format strings
1855 // are string literals: (1) permits the checking of format strings by
1856 // the compiler and thereby (2) can practically remove the source of
1857 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001858
Mike Stump1eb44332009-09-09 15:08:12 +00001859 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001860 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001861 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001862 // the same format string checking logic for both ObjC and C strings.
Richard Smith831421f2012-06-25 20:30:08 +00001863 StringLiteralCheckType CT =
1864 checkFormatStringExpr(OrigFormatExpr, Args, NumArgs, HasVAListArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001865 format_idx, firstDataArg, Type, CallType);
Richard Smith831421f2012-06-25 20:30:08 +00001866 if (CT != SLCT_NotALiteral)
1867 // Literal format string found, check done!
1868 return CT == SLCT_CheckedLiteral;
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001869
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00001870 // Strftime is particular as it always uses a single 'time' argument,
1871 // so it is safe to pass a non-literal string.
1872 if (Type == FST_Strftime)
Richard Smith831421f2012-06-25 20:30:08 +00001873 return false;
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00001874
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00001875 // Do not emit diag when the string param is a macro expansion and the
1876 // format is either NSString or CFString. This is a hack to prevent
1877 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
1878 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupasdc170202012-05-04 21:08:08 +00001879 if (Type == FST_NSString &&
1880 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith831421f2012-06-25 20:30:08 +00001881 return false;
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00001882
Chris Lattner655f1412009-04-29 04:59:47 +00001883 // If there are no arguments specified, warn with -Wformat-security, otherwise
1884 // warn only with -Wformat-nonliteral.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001885 if (NumArgs == format_idx+1)
1886 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001887 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00001888 << OrigFormatExpr->getSourceRange();
1889 else
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001890 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001891 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00001892 << OrigFormatExpr->getSourceRange();
Richard Smith831421f2012-06-25 20:30:08 +00001893 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001894}
Ted Kremenek71895b92007-08-14 17:39:48 +00001895
Ted Kremeneke0e53132010-01-28 23:39:18 +00001896namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00001897class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1898protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001899 Sema &S;
1900 const StringLiteral *FExpr;
1901 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001902 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001903 const unsigned NumDataArgs;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001904 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001905 const bool HasVAListArg;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001906 const Expr * const *Args;
1907 const unsigned NumArgs;
Ted Kremenek0d277352010-01-29 01:06:55 +00001908 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001909 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00001910 bool usesPositionalArgs;
1911 bool atFirstArg;
Richard Trieu55733de2011-10-28 00:41:25 +00001912 bool inFunctionCall;
Jordan Roseddcfbc92012-07-19 18:10:23 +00001913 Sema::VariadicCallType CallType;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001914public:
Ted Kremenek826a3452010-07-16 02:11:22 +00001915 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00001916 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00001917 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001918 Expr **args, unsigned numArgs,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001919 unsigned formatIdx, bool inFunctionCall,
1920 Sema::VariadicCallType callType)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001921 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose50687312012-06-04 23:52:23 +00001922 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
1923 Beg(beg), HasVAListArg(hasVAListArg),
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001924 Args(args), NumArgs(numArgs), FormatIdx(formatIdx),
Richard Trieu55733de2011-10-28 00:41:25 +00001925 usesPositionalArgs(false), atFirstArg(true),
Jordan Roseddcfbc92012-07-19 18:10:23 +00001926 inFunctionCall(inFunctionCall), CallType(callType) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001927 CoveredArgs.resize(numDataArgs);
1928 CoveredArgs.reset();
1929 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001930
Ted Kremenek07d161f2010-01-29 01:50:07 +00001931 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001932
Ted Kremenek826a3452010-07-16 02:11:22 +00001933 void HandleIncompleteSpecifier(const char *startSpecifier,
1934 unsigned specifierLen);
Hans Wennborg76517422012-02-22 10:17:01 +00001935
1936 void HandleNonStandardLengthModifier(
1937 const analyze_format_string::LengthModifier &LM,
1938 const char *startSpecifier, unsigned specifierLen);
1939
1940 void HandleNonStandardConversionSpecifier(
1941 const analyze_format_string::ConversionSpecifier &CS,
1942 const char *startSpecifier, unsigned specifierLen);
1943
1944 void HandleNonStandardConversionSpecification(
1945 const analyze_format_string::LengthModifier &LM,
1946 const analyze_format_string::ConversionSpecifier &CS,
1947 const char *startSpecifier, unsigned specifierLen);
1948
Hans Wennborgf8562642012-03-09 10:10:54 +00001949 virtual void HandlePosition(const char *startPos, unsigned posLen);
1950
Ted Kremenekefaff192010-02-27 01:41:03 +00001951 virtual void HandleInvalidPosition(const char *startSpecifier,
1952 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00001953 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00001954
1955 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1956
Ted Kremeneke0e53132010-01-28 23:39:18 +00001957 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001958
Richard Trieu55733de2011-10-28 00:41:25 +00001959 template <typename Range>
1960 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
1961 const Expr *ArgumentExpr,
1962 PartialDiagnostic PDiag,
1963 SourceLocation StringLoc,
1964 bool IsStringLocation, Range StringRange,
1965 FixItHint Fixit = FixItHint());
1966
Ted Kremenek826a3452010-07-16 02:11:22 +00001967protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001968 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1969 const char *startSpec,
1970 unsigned specifierLen,
1971 const char *csStart, unsigned csLen);
Richard Trieu55733de2011-10-28 00:41:25 +00001972
1973 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
1974 const char *startSpec,
1975 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001976
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001977 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00001978 CharSourceRange getSpecifierRange(const char *startSpecifier,
1979 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001980 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001981
Ted Kremenek0d277352010-01-29 01:06:55 +00001982 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00001983
1984 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1985 const analyze_format_string::ConversionSpecifier &CS,
1986 const char *startSpecifier, unsigned specifierLen,
1987 unsigned argIndex);
Richard Trieu55733de2011-10-28 00:41:25 +00001988
1989 template <typename Range>
1990 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
1991 bool IsStringLocation, Range StringRange,
1992 FixItHint Fixit = FixItHint());
1993
1994 void CheckPositionalAndNonpositionalArgs(
1995 const analyze_format_string::FormatSpecifier *FS);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001996};
1997}
1998
Ted Kremenek826a3452010-07-16 02:11:22 +00001999SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00002000 return OrigFormatExpr->getSourceRange();
2001}
2002
Ted Kremenek826a3452010-07-16 02:11:22 +00002003CharSourceRange CheckFormatHandler::
2004getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002005 SourceLocation Start = getLocationOfByte(startSpecifier);
2006 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2007
2008 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002009 End = End.getLocWithOffset(1);
Tom Care45f9b7e2010-06-21 21:21:01 +00002010
2011 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002012}
2013
Ted Kremenek826a3452010-07-16 02:11:22 +00002014SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002015 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002016}
2017
Ted Kremenek826a3452010-07-16 02:11:22 +00002018void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2019 unsigned specifierLen){
Richard Trieu55733de2011-10-28 00:41:25 +00002020 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2021 getLocationOfByte(startSpecifier),
2022 /*IsStringLocation*/true,
2023 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek808015a2010-01-29 03:16:21 +00002024}
2025
Hans Wennborg76517422012-02-22 10:17:01 +00002026void CheckFormatHandler::HandleNonStandardLengthModifier(
2027 const analyze_format_string::LengthModifier &LM,
2028 const char *startSpecifier, unsigned specifierLen) {
2029 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) << LM.toString()
Hans Wennborgf8562642012-03-09 10:10:54 +00002030 << 0,
Hans Wennborg76517422012-02-22 10:17:01 +00002031 getLocationOfByte(LM.getStart()),
2032 /*IsStringLocation*/true,
2033 getSpecifierRange(startSpecifier, specifierLen));
2034}
2035
2036void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2037 const analyze_format_string::ConversionSpecifier &CS,
2038 const char *startSpecifier, unsigned specifierLen) {
2039 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) << CS.toString()
Hans Wennborgf8562642012-03-09 10:10:54 +00002040 << 1,
Hans Wennborg76517422012-02-22 10:17:01 +00002041 getLocationOfByte(CS.getStart()),
2042 /*IsStringLocation*/true,
2043 getSpecifierRange(startSpecifier, specifierLen));
2044}
2045
2046void CheckFormatHandler::HandleNonStandardConversionSpecification(
2047 const analyze_format_string::LengthModifier &LM,
2048 const analyze_format_string::ConversionSpecifier &CS,
2049 const char *startSpecifier, unsigned specifierLen) {
2050 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_conversion_spec)
2051 << LM.toString() << CS.toString(),
2052 getLocationOfByte(LM.getStart()),
2053 /*IsStringLocation*/true,
2054 getSpecifierRange(startSpecifier, specifierLen));
2055}
2056
Hans Wennborgf8562642012-03-09 10:10:54 +00002057void CheckFormatHandler::HandlePosition(const char *startPos,
2058 unsigned posLen) {
2059 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2060 getLocationOfByte(startPos),
2061 /*IsStringLocation*/true,
2062 getSpecifierRange(startPos, posLen));
2063}
2064
Ted Kremenekefaff192010-02-27 01:41:03 +00002065void
Ted Kremenek826a3452010-07-16 02:11:22 +00002066CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2067 analyze_format_string::PositionContext p) {
Richard Trieu55733de2011-10-28 00:41:25 +00002068 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2069 << (unsigned) p,
2070 getLocationOfByte(startPos), /*IsStringLocation*/true,
2071 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002072}
2073
Ted Kremenek826a3452010-07-16 02:11:22 +00002074void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00002075 unsigned posLen) {
Richard Trieu55733de2011-10-28 00:41:25 +00002076 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2077 getLocationOfByte(startPos),
2078 /*IsStringLocation*/true,
2079 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002080}
2081
Ted Kremenek826a3452010-07-16 02:11:22 +00002082void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose50687312012-06-04 23:52:23 +00002083 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0c069442011-03-15 21:18:48 +00002084 // The presence of a null character is likely an error.
Richard Trieu55733de2011-10-28 00:41:25 +00002085 EmitFormatDiagnostic(
2086 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2087 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2088 getFormatStringRange());
Ted Kremenek0c069442011-03-15 21:18:48 +00002089 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002090}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002091
Jordan Rose48716662012-07-19 18:10:08 +00002092// Note that this may return NULL if there was an error parsing or building
2093// one of the argument expressions.
Ted Kremenek826a3452010-07-16 02:11:22 +00002094const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002095 return Args[FirstDataArg + i];
Ted Kremenek826a3452010-07-16 02:11:22 +00002096}
2097
2098void CheckFormatHandler::DoneProcessing() {
2099 // Does the number of data arguments exceed the number of
2100 // format conversions in the format string?
2101 if (!HasVAListArg) {
2102 // Find any arguments that weren't covered.
2103 CoveredArgs.flip();
2104 signed notCoveredArg = CoveredArgs.find_first();
2105 if (notCoveredArg >= 0) {
2106 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose48716662012-07-19 18:10:08 +00002107 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2108 SourceLocation Loc = E->getLocStart();
2109 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2110 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2111 Loc, /*IsStringLocation*/false,
2112 getFormatStringRange());
2113 }
Bob Wilsonc03f2df2012-05-03 19:47:19 +00002114 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002115 }
2116 }
2117}
2118
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002119bool
2120CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2121 SourceLocation Loc,
2122 const char *startSpec,
2123 unsigned specifierLen,
2124 const char *csStart,
2125 unsigned csLen) {
2126
2127 bool keepGoing = true;
2128 if (argIndex < NumDataArgs) {
2129 // Consider the argument coverered, even though the specifier doesn't
2130 // make sense.
2131 CoveredArgs.set(argIndex);
2132 }
2133 else {
2134 // If argIndex exceeds the number of data arguments we
2135 // don't issue a warning because that is just a cascade of warnings (and
2136 // they may have intended '%%' anyway). We don't want to continue processing
2137 // the format string after this point, however, as we will like just get
2138 // gibberish when trying to match arguments.
2139 keepGoing = false;
2140 }
2141
Richard Trieu55733de2011-10-28 00:41:25 +00002142 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2143 << StringRef(csStart, csLen),
2144 Loc, /*IsStringLocation*/true,
2145 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002146
2147 return keepGoing;
2148}
2149
Richard Trieu55733de2011-10-28 00:41:25 +00002150void
2151CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2152 const char *startSpec,
2153 unsigned specifierLen) {
2154 EmitFormatDiagnostic(
2155 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2156 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2157}
2158
Ted Kremenek666a1972010-07-26 19:45:42 +00002159bool
2160CheckFormatHandler::CheckNumArgs(
2161 const analyze_format_string::FormatSpecifier &FS,
2162 const analyze_format_string::ConversionSpecifier &CS,
2163 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2164
2165 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002166 PartialDiagnostic PDiag = FS.usesPositionalArg()
2167 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2168 << (argIndex+1) << NumDataArgs)
2169 : S.PDiag(diag::warn_printf_insufficient_data_args);
2170 EmitFormatDiagnostic(
2171 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2172 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek666a1972010-07-26 19:45:42 +00002173 return false;
2174 }
2175 return true;
2176}
2177
Richard Trieu55733de2011-10-28 00:41:25 +00002178template<typename Range>
2179void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2180 SourceLocation Loc,
2181 bool IsStringLocation,
2182 Range StringRange,
2183 FixItHint FixIt) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002184 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu55733de2011-10-28 00:41:25 +00002185 Loc, IsStringLocation, StringRange, FixIt);
2186}
2187
2188/// \brief If the format string is not within the funcion call, emit a note
2189/// so that the function call and string are in diagnostic messages.
2190///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00002191/// \param InFunctionCall if true, the format string is within the function
Richard Trieu55733de2011-10-28 00:41:25 +00002192/// call and only one diagnostic message will be produced. Otherwise, an
2193/// extra note will be emitted pointing to location of the format string.
2194///
2195/// \param ArgumentExpr the expression that is passed as the format string
2196/// argument in the function call. Used for getting locations when two
2197/// diagnostics are emitted.
2198///
2199/// \param PDiag the callee should already have provided any strings for the
2200/// diagnostic message. This function only adds locations and fixits
2201/// to diagnostics.
2202///
2203/// \param Loc primary location for diagnostic. If two diagnostics are
2204/// required, one will be at Loc and a new SourceLocation will be created for
2205/// the other one.
2206///
2207/// \param IsStringLocation if true, Loc points to the format string should be
2208/// used for the note. Otherwise, Loc points to the argument list and will
2209/// be used with PDiag.
2210///
2211/// \param StringRange some or all of the string to highlight. This is
2212/// templated so it can accept either a CharSourceRange or a SourceRange.
2213///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00002214/// \param FixIt optional fix it hint for the format string.
Richard Trieu55733de2011-10-28 00:41:25 +00002215template<typename Range>
2216void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2217 const Expr *ArgumentExpr,
2218 PartialDiagnostic PDiag,
2219 SourceLocation Loc,
2220 bool IsStringLocation,
2221 Range StringRange,
2222 FixItHint FixIt) {
2223 if (InFunctionCall)
2224 S.Diag(Loc, PDiag) << StringRange << FixIt;
2225 else {
2226 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2227 << ArgumentExpr->getSourceRange();
2228 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2229 diag::note_format_string_defined)
2230 << StringRange << FixIt;
2231 }
2232}
2233
Ted Kremenek826a3452010-07-16 02:11:22 +00002234//===--- CHECK: Printf format string checking ------------------------------===//
2235
2236namespace {
2237class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose50687312012-06-04 23:52:23 +00002238 bool ObjCContext;
Ted Kremenek826a3452010-07-16 02:11:22 +00002239public:
2240 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2241 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002242 unsigned numDataArgs, bool isObjC,
Ted Kremenek826a3452010-07-16 02:11:22 +00002243 const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002244 Expr **Args, unsigned NumArgs,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002245 unsigned formatIdx, bool inFunctionCall,
2246 Sema::VariadicCallType CallType)
Ted Kremenek826a3452010-07-16 02:11:22 +00002247 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002248 numDataArgs, beg, hasVAListArg, Args, NumArgs,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002249 formatIdx, inFunctionCall, CallType), ObjCContext(isObjC)
2250 {}
2251
Ted Kremenek826a3452010-07-16 02:11:22 +00002252
2253 bool HandleInvalidPrintfConversionSpecifier(
2254 const analyze_printf::PrintfSpecifier &FS,
2255 const char *startSpecifier,
2256 unsigned specifierLen);
2257
2258 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2259 const char *startSpecifier,
2260 unsigned specifierLen);
Richard Smith831421f2012-06-25 20:30:08 +00002261 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2262 const char *StartSpecifier,
2263 unsigned SpecifierLen,
2264 const Expr *E);
2265
Ted Kremenek826a3452010-07-16 02:11:22 +00002266 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2267 const char *startSpecifier, unsigned specifierLen);
2268 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2269 const analyze_printf::OptionalAmount &Amt,
2270 unsigned type,
2271 const char *startSpecifier, unsigned specifierLen);
2272 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2273 const analyze_printf::OptionalFlag &flag,
2274 const char *startSpecifier, unsigned specifierLen);
2275 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2276 const analyze_printf::OptionalFlag &ignoredFlag,
2277 const analyze_printf::OptionalFlag &flag,
2278 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgf3749f42012-08-07 08:11:26 +00002279 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith831421f2012-06-25 20:30:08 +00002280 const Expr *E, const CharSourceRange &CSR);
2281
Ted Kremenek826a3452010-07-16 02:11:22 +00002282};
2283}
2284
2285bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2286 const analyze_printf::PrintfSpecifier &FS,
2287 const char *startSpecifier,
2288 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002289 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002290 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002291
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002292 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2293 getLocationOfByte(CS.getStart()),
2294 startSpecifier, specifierLen,
2295 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00002296}
2297
Ted Kremenek826a3452010-07-16 02:11:22 +00002298bool CheckPrintfHandler::HandleAmount(
2299 const analyze_format_string::OptionalAmount &Amt,
2300 unsigned k, const char *startSpecifier,
2301 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002302
2303 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002304 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002305 unsigned argIndex = Amt.getArgIndex();
2306 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002307 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2308 << k,
2309 getLocationOfByte(Amt.getStart()),
2310 /*IsStringLocation*/true,
2311 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002312 // Don't do any more checking. We will just emit
2313 // spurious errors.
2314 return false;
2315 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002316
Ted Kremenek0d277352010-01-29 01:06:55 +00002317 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00002318 // Although not in conformance with C99, we also allow the argument to be
2319 // an 'unsigned int' as that is a reasonably safe case. GCC also
2320 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002321 CoveredArgs.set(argIndex);
2322 const Expr *Arg = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00002323 if (!Arg)
2324 return false;
2325
Ted Kremenek0d277352010-01-29 01:06:55 +00002326 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002327
Hans Wennborgf3749f42012-08-07 08:11:26 +00002328 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
2329 assert(AT.isValid());
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002330
Hans Wennborgf3749f42012-08-07 08:11:26 +00002331 if (!AT.matchesType(S.Context, T)) {
Richard Trieu55733de2011-10-28 00:41:25 +00002332 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgf3749f42012-08-07 08:11:26 +00002333 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu55733de2011-10-28 00:41:25 +00002334 << T << Arg->getSourceRange(),
2335 getLocationOfByte(Amt.getStart()),
2336 /*IsStringLocation*/true,
2337 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002338 // Don't do any more checking. We will just emit
2339 // spurious errors.
2340 return false;
2341 }
2342 }
2343 }
2344 return true;
2345}
Ted Kremenek0d277352010-01-29 01:06:55 +00002346
Tom Caree4ee9662010-06-17 19:00:27 +00002347void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00002348 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002349 const analyze_printf::OptionalAmount &Amt,
2350 unsigned type,
2351 const char *startSpecifier,
2352 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002353 const analyze_printf::PrintfConversionSpecifier &CS =
2354 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00002355
Richard Trieu55733de2011-10-28 00:41:25 +00002356 FixItHint fixit =
2357 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2358 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2359 Amt.getConstantLength()))
2360 : FixItHint();
2361
2362 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2363 << type << CS.toString(),
2364 getLocationOfByte(Amt.getStart()),
2365 /*IsStringLocation*/true,
2366 getSpecifierRange(startSpecifier, specifierLen),
2367 fixit);
Tom Caree4ee9662010-06-17 19:00:27 +00002368}
2369
Ted Kremenek826a3452010-07-16 02:11:22 +00002370void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002371 const analyze_printf::OptionalFlag &flag,
2372 const char *startSpecifier,
2373 unsigned specifierLen) {
2374 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002375 const analyze_printf::PrintfConversionSpecifier &CS =
2376 FS.getConversionSpecifier();
Richard Trieu55733de2011-10-28 00:41:25 +00002377 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2378 << flag.toString() << CS.toString(),
2379 getLocationOfByte(flag.getPosition()),
2380 /*IsStringLocation*/true,
2381 getSpecifierRange(startSpecifier, specifierLen),
2382 FixItHint::CreateRemoval(
2383 getSpecifierRange(flag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002384}
2385
2386void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00002387 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002388 const analyze_printf::OptionalFlag &ignoredFlag,
2389 const analyze_printf::OptionalFlag &flag,
2390 const char *startSpecifier,
2391 unsigned specifierLen) {
2392 // Warn about ignored flag with a fixit removal.
Richard Trieu55733de2011-10-28 00:41:25 +00002393 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2394 << ignoredFlag.toString() << flag.toString(),
2395 getLocationOfByte(ignoredFlag.getPosition()),
2396 /*IsStringLocation*/true,
2397 getSpecifierRange(startSpecifier, specifierLen),
2398 FixItHint::CreateRemoval(
2399 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002400}
2401
Richard Smith831421f2012-06-25 20:30:08 +00002402// Determines if the specified is a C++ class or struct containing
2403// a member with the specified name and kind (e.g. a CXXMethodDecl named
2404// "c_str()").
2405template<typename MemberKind>
2406static llvm::SmallPtrSet<MemberKind*, 1>
2407CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2408 const RecordType *RT = Ty->getAs<RecordType>();
2409 llvm::SmallPtrSet<MemberKind*, 1> Results;
2410
2411 if (!RT)
2412 return Results;
2413 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
2414 if (!RD)
2415 return Results;
2416
2417 LookupResult R(S, &S.PP.getIdentifierTable().get(Name), SourceLocation(),
2418 Sema::LookupMemberName);
2419
2420 // We just need to include all members of the right kind turned up by the
2421 // filter, at this point.
2422 if (S.LookupQualifiedName(R, RT->getDecl()))
2423 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2424 NamedDecl *decl = (*I)->getUnderlyingDecl();
2425 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
2426 Results.insert(FK);
2427 }
2428 return Results;
2429}
2430
2431// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgf3749f42012-08-07 08:11:26 +00002432// better diagnostic if so. AT is assumed to be valid.
Richard Smith831421f2012-06-25 20:30:08 +00002433// Returns true when a c_str() conversion method is found.
2434bool CheckPrintfHandler::checkForCStrMembers(
Hans Wennborgf3749f42012-08-07 08:11:26 +00002435 const analyze_printf::ArgType &AT, const Expr *E,
Richard Smith831421f2012-06-25 20:30:08 +00002436 const CharSourceRange &CSR) {
2437 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2438
2439 MethodSet Results =
2440 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
2441
2442 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2443 MI != ME; ++MI) {
2444 const CXXMethodDecl *Method = *MI;
2445 if (Method->getNumParams() == 0 &&
Hans Wennborgf3749f42012-08-07 08:11:26 +00002446 AT.matchesType(S.Context, Method->getResultType())) {
Richard Smith831421f2012-06-25 20:30:08 +00002447 // FIXME: Suggest parens if the expression needs them.
2448 SourceLocation EndLoc =
2449 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd());
2450 S.Diag(E->getLocStart(), diag::note_printf_c_str)
2451 << "c_str()"
2452 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
2453 return true;
2454 }
2455 }
2456
2457 return false;
2458}
2459
Ted Kremeneke0e53132010-01-28 23:39:18 +00002460bool
Ted Kremenek826a3452010-07-16 02:11:22 +00002461CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002462 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00002463 const char *startSpecifier,
2464 unsigned specifierLen) {
2465
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002466 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00002467 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002468 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00002469
Ted Kremenekbaa40062010-07-19 22:01:06 +00002470 if (FS.consumesDataArgument()) {
2471 if (atFirstArg) {
2472 atFirstArg = false;
2473 usesPositionalArgs = FS.usesPositionalArg();
2474 }
2475 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002476 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2477 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002478 return false;
2479 }
Ted Kremenek0d277352010-01-29 01:06:55 +00002480 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002481
Ted Kremenekefaff192010-02-27 01:41:03 +00002482 // First check if the field width, precision, and conversion specifier
2483 // have matching data arguments.
2484 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2485 startSpecifier, specifierLen)) {
2486 return false;
2487 }
2488
2489 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2490 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002491 return false;
2492 }
2493
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002494 if (!CS.consumesDataArgument()) {
2495 // FIXME: Technically specifying a precision or field width here
2496 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002497 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002498 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002499
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002500 // Consume the argument.
2501 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00002502 if (argIndex < NumDataArgs) {
2503 // The check to see if the argIndex is valid will come later.
2504 // We set the bit here because we may exit early from this
2505 // function if we encounter some other error.
2506 CoveredArgs.set(argIndex);
2507 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002508
2509 // Check for using an Objective-C specific conversion specifier
2510 // in a non-ObjC literal.
Jordan Rose50687312012-06-04 23:52:23 +00002511 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002512 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2513 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002514 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002515
Tom Caree4ee9662010-06-17 19:00:27 +00002516 // Check for invalid use of field width
2517 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002518 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00002519 startSpecifier, specifierLen);
2520 }
2521
2522 // Check for invalid use of precision
2523 if (!FS.hasValidPrecision()) {
2524 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
2525 startSpecifier, specifierLen);
2526 }
2527
2528 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00002529 if (!FS.hasValidThousandsGroupingPrefix())
2530 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002531 if (!FS.hasValidLeadingZeros())
2532 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
2533 if (!FS.hasValidPlusPrefix())
2534 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00002535 if (!FS.hasValidSpacePrefix())
2536 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002537 if (!FS.hasValidAlternativeForm())
2538 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
2539 if (!FS.hasValidLeftJustified())
2540 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
2541
2542 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00002543 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
2544 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
2545 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002546 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
2547 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
2548 startSpecifier, specifierLen);
2549
2550 // Check the length modifier is valid with the given conversion specifier.
2551 const LengthModifier &LM = FS.getLengthModifier();
2552 if (!FS.hasValidLengthModifier())
Richard Trieu55733de2011-10-28 00:41:25 +00002553 EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length)
2554 << LM.toString() << CS.toString(),
2555 getLocationOfByte(LM.getStart()),
2556 /*IsStringLocation*/true,
2557 getSpecifierRange(startSpecifier, specifierLen),
2558 FixItHint::CreateRemoval(
2559 getSpecifierRange(LM.getStart(),
2560 LM.getLength())));
Hans Wennborg76517422012-02-22 10:17:01 +00002561 if (!FS.hasStandardLengthModifier())
2562 HandleNonStandardLengthModifier(LM, startSpecifier, specifierLen);
David Blaikie4e4d0842012-03-11 07:00:24 +00002563 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
Hans Wennborg76517422012-02-22 10:17:01 +00002564 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
2565 if (!FS.hasStandardLengthConversionCombination())
2566 HandleNonStandardConversionSpecification(LM, CS, startSpecifier,
2567 specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002568
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002569 // The remaining checks depend on the data arguments.
2570 if (HasVAListArg)
2571 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002572
Ted Kremenek666a1972010-07-26 19:45:42 +00002573 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002574 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002575
Jordan Rose48716662012-07-19 18:10:08 +00002576 const Expr *Arg = getDataArg(argIndex);
2577 if (!Arg)
2578 return true;
2579
2580 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith831421f2012-06-25 20:30:08 +00002581}
2582
2583bool
2584CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2585 const char *StartSpecifier,
2586 unsigned SpecifierLen,
2587 const Expr *E) {
2588 using namespace analyze_format_string;
2589 using namespace analyze_printf;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002590 // Now type check the data expression that matches the
2591 // format specifier.
Hans Wennborgf3749f42012-08-07 08:11:26 +00002592 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
2593 ObjCContext);
2594 if (AT.isValid() && !AT.matchesType(S.Context, E->getType())) {
Jordan Roseee0259d2012-06-04 22:48:57 +00002595 // Look through argument promotions for our error message's reported type.
2596 // This includes the integral and floating promotions, but excludes array
2597 // and function pointer decay; seeing that an argument intended to be a
2598 // string has type 'char [6]' is probably more confusing than 'char *'.
Richard Smith831421f2012-06-25 20:30:08 +00002599 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Jordan Roseee0259d2012-06-04 22:48:57 +00002600 if (ICE->getCastKind() == CK_IntegralCast ||
2601 ICE->getCastKind() == CK_FloatingCast) {
Richard Smith831421f2012-06-25 20:30:08 +00002602 E = ICE->getSubExpr();
Jordan Roseee0259d2012-06-04 22:48:57 +00002603
2604 // Check if we didn't match because of an implicit cast from a 'char'
2605 // or 'short' to an 'int'. This is done because printf is a varargs
2606 // function.
2607 if (ICE->getType() == S.Context.IntTy ||
2608 ICE->getType() == S.Context.UnsignedIntTy) {
2609 // All further checking is done on the subexpression.
Hans Wennborgf3749f42012-08-07 08:11:26 +00002610 if (AT.matchesType(S.Context, E->getType()))
Jordan Roseee0259d2012-06-04 22:48:57 +00002611 return true;
2612 }
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00002613 }
Jordan Roseee0259d2012-06-04 22:48:57 +00002614 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002615
2616 // We may be able to offer a FixItHint if it is a supported type.
2617 PrintfSpecifier fixedFS = FS;
Richard Smith831421f2012-06-25 20:30:08 +00002618 bool success = fixedFS.fixType(E->getType(), S.getLangOpts(),
Jordan Rose50687312012-06-04 23:52:23 +00002619 S.Context, ObjCContext);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002620
2621 if (success) {
2622 // Get the fix string from the fixed format specifier
Jordan Roseee0259d2012-06-04 22:48:57 +00002623 SmallString<16> buf;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002624 llvm::raw_svector_ostream os(buf);
2625 fixedFS.toString(os);
2626
Richard Trieu55733de2011-10-28 00:41:25 +00002627 EmitFormatDiagnostic(
2628 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborgf3749f42012-08-07 08:11:26 +00002629 << AT.getRepresentativeTypeName(S.Context) << E->getType()
Richard Smith831421f2012-06-25 20:30:08 +00002630 << E->getSourceRange(),
2631 E->getLocStart(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00002632 /*IsStringLocation*/false,
Richard Smith831421f2012-06-25 20:30:08 +00002633 getSpecifierRange(StartSpecifier, SpecifierLen),
Richard Trieu55733de2011-10-28 00:41:25 +00002634 FixItHint::CreateReplacement(
Richard Smith831421f2012-06-25 20:30:08 +00002635 getSpecifierRange(StartSpecifier, SpecifierLen),
Richard Trieu55733de2011-10-28 00:41:25 +00002636 os.str()));
Richard Smith831421f2012-06-25 20:30:08 +00002637 } else {
2638 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
2639 SpecifierLen);
2640 // Since the warning for passing non-POD types to variadic functions
2641 // was deferred until now, we emit a warning for non-POD
2642 // arguments here.
2643 if (S.isValidVarArgType(E->getType()) == Sema::VAK_Invalid) {
Jordan Roseddcfbc92012-07-19 18:10:23 +00002644 unsigned DiagKind;
2645 if (E->getType()->isObjCObjectType())
2646 DiagKind = diag::err_cannot_pass_objc_interface_to_vararg_format;
2647 else
2648 DiagKind = diag::warn_non_pod_vararg_with_format_string;
2649
Richard Smith831421f2012-06-25 20:30:08 +00002650 EmitFormatDiagnostic(
Jordan Roseddcfbc92012-07-19 18:10:23 +00002651 S.PDiag(DiagKind)
Richard Smith831421f2012-06-25 20:30:08 +00002652 << S.getLangOpts().CPlusPlus0x
2653 << E->getType()
Jordan Roseddcfbc92012-07-19 18:10:23 +00002654 << CallType
Hans Wennborgf3749f42012-08-07 08:11:26 +00002655 << AT.getRepresentativeTypeName(S.Context)
Richard Smith831421f2012-06-25 20:30:08 +00002656 << CSR
2657 << E->getSourceRange(),
2658 E->getLocStart(), /*IsStringLocation*/false, CSR);
2659
Hans Wennborgf3749f42012-08-07 08:11:26 +00002660 checkForCStrMembers(AT, E, CSR);
Richard Smith831421f2012-06-25 20:30:08 +00002661 } else
2662 EmitFormatDiagnostic(
2663 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborgf3749f42012-08-07 08:11:26 +00002664 << AT.getRepresentativeTypeName(S.Context) << E->getType()
Richard Smith831421f2012-06-25 20:30:08 +00002665 << CSR
2666 << E->getSourceRange(),
2667 E->getLocStart(), /*IsStringLocation*/false, CSR);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002668 }
2669 }
2670
Ted Kremeneke0e53132010-01-28 23:39:18 +00002671 return true;
2672}
2673
Ted Kremenek826a3452010-07-16 02:11:22 +00002674//===--- CHECK: Scanf format string checking ------------------------------===//
2675
2676namespace {
2677class CheckScanfHandler : public CheckFormatHandler {
2678public:
2679 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
2680 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002681 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002682 Expr **Args, unsigned NumArgs,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002683 unsigned formatIdx, bool inFunctionCall,
2684 Sema::VariadicCallType CallType)
Ted Kremenek826a3452010-07-16 02:11:22 +00002685 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002686 numDataArgs, beg, hasVAListArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002687 Args, NumArgs, formatIdx, inFunctionCall, CallType)
2688 {}
Ted Kremenek826a3452010-07-16 02:11:22 +00002689
2690 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
2691 const char *startSpecifier,
2692 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002693
2694 bool HandleInvalidScanfConversionSpecifier(
2695 const analyze_scanf::ScanfSpecifier &FS,
2696 const char *startSpecifier,
2697 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00002698
2699 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00002700};
Ted Kremenek07d161f2010-01-29 01:50:07 +00002701}
Ted Kremeneke0e53132010-01-28 23:39:18 +00002702
Ted Kremenekb7c21012010-07-16 18:28:03 +00002703void CheckScanfHandler::HandleIncompleteScanList(const char *start,
2704 const char *end) {
Richard Trieu55733de2011-10-28 00:41:25 +00002705 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
2706 getLocationOfByte(end), /*IsStringLocation*/true,
2707 getSpecifierRange(start, end - start));
Ted Kremenekb7c21012010-07-16 18:28:03 +00002708}
2709
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002710bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
2711 const analyze_scanf::ScanfSpecifier &FS,
2712 const char *startSpecifier,
2713 unsigned specifierLen) {
2714
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002715 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002716 FS.getConversionSpecifier();
2717
2718 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2719 getLocationOfByte(CS.getStart()),
2720 startSpecifier, specifierLen,
2721 CS.getStart(), CS.getLength());
2722}
2723
Ted Kremenek826a3452010-07-16 02:11:22 +00002724bool CheckScanfHandler::HandleScanfSpecifier(
2725 const analyze_scanf::ScanfSpecifier &FS,
2726 const char *startSpecifier,
2727 unsigned specifierLen) {
2728
2729 using namespace analyze_scanf;
2730 using namespace analyze_format_string;
2731
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002732 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002733
Ted Kremenekbaa40062010-07-19 22:01:06 +00002734 // Handle case where '%' and '*' don't consume an argument. These shouldn't
2735 // be used to decide if we are using positional arguments consistently.
2736 if (FS.consumesDataArgument()) {
2737 if (atFirstArg) {
2738 atFirstArg = false;
2739 usesPositionalArgs = FS.usesPositionalArg();
2740 }
2741 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002742 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2743 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002744 return false;
2745 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002746 }
2747
2748 // Check if the field with is non-zero.
2749 const OptionalAmount &Amt = FS.getFieldWidth();
2750 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
2751 if (Amt.getConstantAmount() == 0) {
2752 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
2753 Amt.getConstantLength());
Richard Trieu55733de2011-10-28 00:41:25 +00002754 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
2755 getLocationOfByte(Amt.getStart()),
2756 /*IsStringLocation*/true, R,
2757 FixItHint::CreateRemoval(R));
Ted Kremenek826a3452010-07-16 02:11:22 +00002758 }
2759 }
2760
2761 if (!FS.consumesDataArgument()) {
2762 // FIXME: Technically specifying a precision or field width here
2763 // makes no sense. Worth issuing a warning at some point.
2764 return true;
2765 }
2766
2767 // Consume the argument.
2768 unsigned argIndex = FS.getArgIndex();
2769 if (argIndex < NumDataArgs) {
2770 // The check to see if the argIndex is valid will come later.
2771 // We set the bit here because we may exit early from this
2772 // function if we encounter some other error.
2773 CoveredArgs.set(argIndex);
2774 }
2775
Ted Kremenek1e51c202010-07-20 20:04:47 +00002776 // Check the length modifier is valid with the given conversion specifier.
2777 const LengthModifier &LM = FS.getLengthModifier();
2778 if (!FS.hasValidLengthModifier()) {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00002779 const CharSourceRange &R = getSpecifierRange(LM.getStart(), LM.getLength());
2780 EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length)
2781 << LM.toString() << CS.toString()
2782 << getSpecifierRange(startSpecifier, specifierLen),
2783 getLocationOfByte(LM.getStart()),
2784 /*IsStringLocation*/true, R,
2785 FixItHint::CreateRemoval(R));
Ted Kremenek1e51c202010-07-20 20:04:47 +00002786 }
2787
Hans Wennborg76517422012-02-22 10:17:01 +00002788 if (!FS.hasStandardLengthModifier())
2789 HandleNonStandardLengthModifier(LM, startSpecifier, specifierLen);
David Blaikie4e4d0842012-03-11 07:00:24 +00002790 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
Hans Wennborg76517422012-02-22 10:17:01 +00002791 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
2792 if (!FS.hasStandardLengthConversionCombination())
2793 HandleNonStandardConversionSpecification(LM, CS, startSpecifier,
2794 specifierLen);
2795
Ted Kremenek826a3452010-07-16 02:11:22 +00002796 // The remaining checks depend on the data arguments.
2797 if (HasVAListArg)
2798 return true;
2799
Ted Kremenek666a1972010-07-26 19:45:42 +00002800 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00002801 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00002802
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002803 // Check that the argument type matches the format specifier.
2804 const Expr *Ex = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00002805 if (!Ex)
2806 return true;
2807
Hans Wennborg58e1e542012-08-07 08:59:46 +00002808 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
2809 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002810 ScanfSpecifier fixedFS = FS;
David Blaikie4e4d0842012-03-11 07:00:24 +00002811 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
Hans Wennborgbe6126a2012-02-15 09:59:46 +00002812 S.Context);
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002813
2814 if (success) {
2815 // Get the fix string from the fixed format specifier.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002816 SmallString<128> buf;
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002817 llvm::raw_svector_ostream os(buf);
2818 fixedFS.toString(os);
2819
2820 EmitFormatDiagnostic(
2821 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg58e1e542012-08-07 08:59:46 +00002822 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002823 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00002824 Ex->getLocStart(),
2825 /*IsStringLocation*/false,
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002826 getSpecifierRange(startSpecifier, specifierLen),
2827 FixItHint::CreateReplacement(
2828 getSpecifierRange(startSpecifier, specifierLen),
2829 os.str()));
2830 } else {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00002831 EmitFormatDiagnostic(
2832 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg58e1e542012-08-07 08:59:46 +00002833 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00002834 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00002835 Ex->getLocStart(),
2836 /*IsStringLocation*/false,
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00002837 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002838 }
2839 }
2840
Ted Kremenek826a3452010-07-16 02:11:22 +00002841 return true;
2842}
2843
2844void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002845 const Expr *OrigFormatExpr,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002846 Expr **Args, unsigned NumArgs,
2847 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002848 unsigned firstDataArg, FormatStringType Type,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002849 bool inFunctionCall, VariadicCallType CallType) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002850
Ted Kremeneke0e53132010-01-28 23:39:18 +00002851 // CHECK: is the format string a wide literal?
Richard Smithdf9ef1b2012-06-13 05:37:23 +00002852 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002853 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002854 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00002855 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
2856 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00002857 return;
2858 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002859
Ted Kremeneke0e53132010-01-28 23:39:18 +00002860 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner5f9e2722011-07-23 10:55:15 +00002861 StringRef StrRef = FExpr->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00002862 const char *Str = StrRef.data();
2863 unsigned StrLen = StrRef.size();
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002864 const unsigned numDataArgs = NumArgs - firstDataArg;
Ted Kremenek826a3452010-07-16 02:11:22 +00002865
Ted Kremeneke0e53132010-01-28 23:39:18 +00002866 // CHECK: empty format string?
Ted Kremenek4cd57912011-09-29 05:52:16 +00002867 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu55733de2011-10-28 00:41:25 +00002868 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002869 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00002870 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
2871 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00002872 return;
2873 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002874
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002875 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002876 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002877 numDataArgs, (Type == FST_NSString),
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002878 Str, HasVAListArg, Args, NumArgs, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002879 inFunctionCall, CallType);
Ted Kremenek826a3452010-07-16 02:11:22 +00002880
Hans Wennborgd02deeb2011-12-15 10:25:47 +00002881 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
David Blaikie4e4d0842012-03-11 07:00:24 +00002882 getLangOpts()))
Ted Kremenek826a3452010-07-16 02:11:22 +00002883 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002884 } else if (Type == FST_Scanf) {
Jordan Rose50687312012-06-04 23:52:23 +00002885 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002886 Str, HasVAListArg, Args, NumArgs, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002887 inFunctionCall, CallType);
Ted Kremenek826a3452010-07-16 02:11:22 +00002888
Hans Wennborgd02deeb2011-12-15 10:25:47 +00002889 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
David Blaikie4e4d0842012-03-11 07:00:24 +00002890 getLangOpts()))
Ted Kremenek826a3452010-07-16 02:11:22 +00002891 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002892 } // TODO: handle other formats
Ted Kremenekce7024e2010-01-28 01:18:22 +00002893}
2894
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002895//===--- CHECK: Standard memory functions ---------------------------------===//
2896
Douglas Gregor2a053a32011-05-03 20:05:22 +00002897/// \brief Determine whether the given type is a dynamic class type (e.g.,
2898/// whether it has a vtable).
2899static bool isDynamicClassType(QualType T) {
2900 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
2901 if (CXXRecordDecl *Definition = Record->getDefinition())
2902 if (Definition->isDynamicClass())
2903 return true;
2904
2905 return false;
2906}
2907
Chandler Carrutha72a12f2011-06-21 23:04:20 +00002908/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth000d4282011-06-16 09:09:40 +00002909/// otherwise returns NULL.
2910static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Webere4a1c642011-06-14 16:14:58 +00002911 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth000d4282011-06-16 09:09:40 +00002912 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2913 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
2914 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00002915
Chandler Carruth000d4282011-06-16 09:09:40 +00002916 return 0;
2917}
2918
Chandler Carrutha72a12f2011-06-21 23:04:20 +00002919/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth000d4282011-06-16 09:09:40 +00002920static QualType getSizeOfArgType(const Expr* E) {
2921 if (const UnaryExprOrTypeTraitExpr *SizeOf =
2922 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2923 if (SizeOf->getKind() == clang::UETT_SizeOf)
2924 return SizeOf->getTypeOfArgument();
2925
2926 return QualType();
Nico Webere4a1c642011-06-14 16:14:58 +00002927}
2928
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002929/// \brief Check for dangerous or invalid arguments to memset().
2930///
Chandler Carruth929f0132011-06-03 06:23:57 +00002931/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002932/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
2933/// function calls.
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002934///
2935/// \param Call The call expression to diagnose.
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002936void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks0a151a12012-01-17 00:37:07 +00002937 unsigned BId,
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002938 IdentifierInfo *FnName) {
Anna Zaks0a151a12012-01-17 00:37:07 +00002939 assert(BId != 0);
2940
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00002941 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor707a23e2011-06-16 17:56:04 +00002942 // we have enough arguments, and if not, abort further checking.
Anna Zaks0a151a12012-01-17 00:37:07 +00002943 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Webercda57822011-10-13 22:30:23 +00002944 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00002945 return;
2946
Anna Zaks0a151a12012-01-17 00:37:07 +00002947 unsigned LastArg = (BId == Builtin::BImemset ||
2948 BId == Builtin::BIstrndup ? 1 : 2);
2949 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Webercda57822011-10-13 22:30:23 +00002950 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth000d4282011-06-16 09:09:40 +00002951
2952 // We have special checking when the length is a sizeof expression.
2953 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
2954 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
2955 llvm::FoldingSetNodeID SizeOfArgID;
2956
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002957 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
2958 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00002959 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002960
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002961 QualType DestTy = Dest->getType();
2962 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
2963 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00002964
Chandler Carruth000d4282011-06-16 09:09:40 +00002965 // Never warn about void type pointers. This can be used to suppress
2966 // false positives.
2967 if (PointeeTy->isVoidType())
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002968 continue;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002969
Chandler Carruth000d4282011-06-16 09:09:40 +00002970 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
2971 // actually comparing the expressions for equality. Because computing the
2972 // expression IDs can be expensive, we only do this if the diagnostic is
2973 // enabled.
2974 if (SizeOfArg &&
2975 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
2976 SizeOfArg->getExprLoc())) {
2977 // We only compute IDs for expressions if the warning is enabled, and
2978 // cache the sizeof arg's ID.
2979 if (SizeOfArgID == llvm::FoldingSetNodeID())
2980 SizeOfArg->Profile(SizeOfArgID, Context, true);
2981 llvm::FoldingSetNodeID DestID;
2982 Dest->Profile(DestID, Context, true);
2983 if (DestID == SizeOfArgID) {
Nico Webercda57822011-10-13 22:30:23 +00002984 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
2985 // over sizeof(src) as well.
Chandler Carruth000d4282011-06-16 09:09:40 +00002986 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks6fcb3722012-05-30 00:34:21 +00002987 StringRef ReadableName = FnName->getName();
2988
Chandler Carruth000d4282011-06-16 09:09:40 +00002989 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaks90c78322012-05-30 23:14:52 +00002990 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth000d4282011-06-16 09:09:40 +00002991 ActionIdx = 1; // If its an address-of operator, just remove it.
2992 if (Context.getTypeSize(PointeeTy) == Context.getCharWidth())
2993 ActionIdx = 2; // If the pointee's size is sizeof(char),
2994 // suggest an explicit length.
Anna Zaks6fcb3722012-05-30 00:34:21 +00002995
2996 // If the function is defined as a builtin macro, do not show macro
2997 // expansion.
2998 SourceLocation SL = SizeOfArg->getExprLoc();
2999 SourceRange DSR = Dest->getSourceRange();
3000 SourceRange SSR = SizeOfArg->getSourceRange();
3001 SourceManager &SM = PP.getSourceManager();
3002
3003 if (SM.isMacroArgExpansion(SL)) {
3004 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
3005 SL = SM.getSpellingLoc(SL);
3006 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
3007 SM.getSpellingLoc(DSR.getEnd()));
3008 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
3009 SM.getSpellingLoc(SSR.getEnd()));
3010 }
3011
Anna Zaks90c78322012-05-30 23:14:52 +00003012 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth000d4282011-06-16 09:09:40 +00003013 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks6fcb3722012-05-30 00:34:21 +00003014 << ReadableName
Anna Zaks90c78322012-05-30 23:14:52 +00003015 << PointeeTy
3016 << DestTy
Anna Zaks6fcb3722012-05-30 00:34:21 +00003017 << DSR
Anna Zaks90c78322012-05-30 23:14:52 +00003018 << SSR);
3019 DiagRuntimeBehavior(SL, SizeOfArg,
3020 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
3021 << ActionIdx
3022 << SSR);
3023
Chandler Carruth000d4282011-06-16 09:09:40 +00003024 break;
3025 }
3026 }
3027
3028 // Also check for cases where the sizeof argument is the exact same
3029 // type as the memory argument, and where it points to a user-defined
3030 // record type.
3031 if (SizeOfArgTy != QualType()) {
3032 if (PointeeTy->isRecordType() &&
3033 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
3034 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
3035 PDiag(diag::warn_sizeof_pointer_type_memaccess)
3036 << FnName << SizeOfArgTy << ArgIdx
3037 << PointeeTy << Dest->getSourceRange()
3038 << LenExpr->getSourceRange());
3039 break;
3040 }
Nico Webere4a1c642011-06-14 16:14:58 +00003041 }
3042
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003043 // Always complain about dynamic classes.
Anna Zaks0a151a12012-01-17 00:37:07 +00003044 if (isDynamicClassType(PointeeTy)) {
3045
3046 unsigned OperationType = 0;
3047 // "overwritten" if we're warning about the destination for any call
3048 // but memcmp; otherwise a verb appropriate to the call.
3049 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
3050 if (BId == Builtin::BImemcpy)
3051 OperationType = 1;
3052 else if(BId == Builtin::BImemmove)
3053 OperationType = 2;
3054 else if (BId == Builtin::BImemcmp)
3055 OperationType = 3;
3056 }
3057
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003058 DiagRuntimeBehavior(
3059 Dest->getExprLoc(), Dest,
3060 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks0a151a12012-01-17 00:37:07 +00003061 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Anna Zaksd9b859a2012-01-13 21:52:01 +00003062 << FnName << PointeeTy
Anna Zaks0a151a12012-01-17 00:37:07 +00003063 << OperationType
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003064 << Call->getCallee()->getSourceRange());
Anna Zaks0a151a12012-01-17 00:37:07 +00003065 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
3066 BId != Builtin::BImemset)
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003067 DiagRuntimeBehavior(
3068 Dest->getExprLoc(), Dest,
3069 PDiag(diag::warn_arc_object_memaccess)
3070 << ArgIdx << FnName << PointeeTy
3071 << Call->getCallee()->getSourceRange());
John McCallf85e1932011-06-15 23:02:42 +00003072 else
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003073 continue;
John McCallf85e1932011-06-15 23:02:42 +00003074
3075 DiagRuntimeBehavior(
3076 Dest->getExprLoc(), Dest,
Chandler Carruth929f0132011-06-03 06:23:57 +00003077 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003078 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
3079 break;
3080 }
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003081 }
3082}
3083
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003084// A little helper routine: ignore addition and subtraction of integer literals.
3085// This intentionally does not ignore all integer constant expressions because
3086// we don't want to remove sizeof().
3087static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
3088 Ex = Ex->IgnoreParenCasts();
3089
3090 for (;;) {
3091 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
3092 if (!BO || !BO->isAdditiveOp())
3093 break;
3094
3095 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
3096 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
3097
3098 if (isa<IntegerLiteral>(RHS))
3099 Ex = LHS;
3100 else if (isa<IntegerLiteral>(LHS))
3101 Ex = RHS;
3102 else
3103 break;
3104 }
3105
3106 return Ex;
3107}
3108
Anna Zaks0f38ace2012-08-08 21:42:23 +00003109static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
3110 ASTContext &Context) {
3111 // Only handle constant-sized or VLAs, but not flexible members.
3112 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
3113 // Only issue the FIXIT for arrays of size > 1.
3114 if (CAT->getSize().getSExtValue() <= 1)
3115 return false;
3116 } else if (!Ty->isVariableArrayType()) {
3117 return false;
3118 }
3119 return true;
3120}
3121
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003122// Warn if the user has made the 'size' argument to strlcpy or strlcat
3123// be the size of the source, instead of the destination.
3124void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
3125 IdentifierInfo *FnName) {
3126
3127 // Don't crash if the user has the wrong number of arguments
3128 if (Call->getNumArgs() != 3)
3129 return;
3130
3131 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
3132 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
3133 const Expr *CompareWithSrc = NULL;
3134
3135 // Look for 'strlcpy(dst, x, sizeof(x))'
3136 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
3137 CompareWithSrc = Ex;
3138 else {
3139 // Look for 'strlcpy(dst, x, strlen(x))'
3140 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Richard Smith180f4792011-11-10 06:34:14 +00003141 if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003142 && SizeCall->getNumArgs() == 1)
3143 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
3144 }
3145 }
3146
3147 if (!CompareWithSrc)
3148 return;
3149
3150 // Determine if the argument to sizeof/strlen is equal to the source
3151 // argument. In principle there's all kinds of things you could do
3152 // here, for instance creating an == expression and evaluating it with
3153 // EvaluateAsBooleanCondition, but this uses a more direct technique:
3154 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
3155 if (!SrcArgDRE)
3156 return;
3157
3158 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
3159 if (!CompareWithSrcDRE ||
3160 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
3161 return;
3162
3163 const Expr *OriginalSizeArg = Call->getArg(2);
3164 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
3165 << OriginalSizeArg->getSourceRange() << FnName;
3166
3167 // Output a FIXIT hint if the destination is an array (rather than a
3168 // pointer to an array). This could be enhanced to handle some
3169 // pointers if we know the actual size, like if DstArg is 'array+2'
3170 // we could say 'sizeof(array)-2'.
3171 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks0f38ace2012-08-08 21:42:23 +00003172 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek8f746222011-08-18 22:48:41 +00003173 return;
Ted Kremenek8f746222011-08-18 22:48:41 +00003174
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003175 SmallString<128> sizeString;
Ted Kremenek8f746222011-08-18 22:48:41 +00003176 llvm::raw_svector_ostream OS(sizeString);
3177 OS << "sizeof(";
Richard Smithd1420c62012-08-16 03:56:14 +00003178 DstArg->printPretty(OS, 0, getPrintingPolicy());
Ted Kremenek8f746222011-08-18 22:48:41 +00003179 OS << ")";
3180
3181 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
3182 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
3183 OS.str());
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003184}
3185
Anna Zaksc36bedc2012-02-01 19:08:57 +00003186/// Check if two expressions refer to the same declaration.
3187static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
3188 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
3189 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
3190 return D1->getDecl() == D2->getDecl();
3191 return false;
3192}
3193
3194static const Expr *getStrlenExprArg(const Expr *E) {
3195 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
3196 const FunctionDecl *FD = CE->getDirectCallee();
3197 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
3198 return 0;
3199 return CE->getArg(0)->IgnoreParenCasts();
3200 }
3201 return 0;
3202}
3203
3204// Warn on anti-patterns as the 'size' argument to strncat.
3205// The correct size argument should look like following:
3206// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
3207void Sema::CheckStrncatArguments(const CallExpr *CE,
3208 IdentifierInfo *FnName) {
3209 // Don't crash if the user has the wrong number of arguments.
3210 if (CE->getNumArgs() < 3)
3211 return;
3212 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
3213 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
3214 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
3215
3216 // Identify common expressions, which are wrongly used as the size argument
3217 // to strncat and may lead to buffer overflows.
3218 unsigned PatternType = 0;
3219 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
3220 // - sizeof(dst)
3221 if (referToTheSameDecl(SizeOfArg, DstArg))
3222 PatternType = 1;
3223 // - sizeof(src)
3224 else if (referToTheSameDecl(SizeOfArg, SrcArg))
3225 PatternType = 2;
3226 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
3227 if (BE->getOpcode() == BO_Sub) {
3228 const Expr *L = BE->getLHS()->IgnoreParenCasts();
3229 const Expr *R = BE->getRHS()->IgnoreParenCasts();
3230 // - sizeof(dst) - strlen(dst)
3231 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
3232 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
3233 PatternType = 1;
3234 // - sizeof(src) - (anything)
3235 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
3236 PatternType = 2;
3237 }
3238 }
3239
3240 if (PatternType == 0)
3241 return;
3242
Anna Zaksafdb0412012-02-03 01:27:37 +00003243 // Generate the diagnostic.
3244 SourceLocation SL = LenArg->getLocStart();
3245 SourceRange SR = LenArg->getSourceRange();
3246 SourceManager &SM = PP.getSourceManager();
3247
3248 // If the function is defined as a builtin macro, do not show macro expansion.
3249 if (SM.isMacroArgExpansion(SL)) {
3250 SL = SM.getSpellingLoc(SL);
3251 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
3252 SM.getSpellingLoc(SR.getEnd()));
3253 }
3254
Anna Zaks0f38ace2012-08-08 21:42:23 +00003255 // Check if the destination is an array (rather than a pointer to an array).
3256 QualType DstTy = DstArg->getType();
3257 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
3258 Context);
3259 if (!isKnownSizeArray) {
3260 if (PatternType == 1)
3261 Diag(SL, diag::warn_strncat_wrong_size) << SR;
3262 else
3263 Diag(SL, diag::warn_strncat_src_size) << SR;
3264 return;
3265 }
3266
Anna Zaksc36bedc2012-02-01 19:08:57 +00003267 if (PatternType == 1)
Anna Zaksafdb0412012-02-03 01:27:37 +00003268 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003269 else
Anna Zaksafdb0412012-02-03 01:27:37 +00003270 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003271
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003272 SmallString<128> sizeString;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003273 llvm::raw_svector_ostream OS(sizeString);
3274 OS << "sizeof(";
Richard Smithd1420c62012-08-16 03:56:14 +00003275 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003276 OS << ") - ";
3277 OS << "strlen(";
Richard Smithd1420c62012-08-16 03:56:14 +00003278 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003279 OS << ") - 1";
3280
Anna Zaksafdb0412012-02-03 01:27:37 +00003281 Diag(SL, diag::note_strncat_wrong_size)
3282 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003283}
3284
Ted Kremenek06de2762007-08-17 16:46:58 +00003285//===--- CHECK: Return Address of Stack Variable --------------------------===//
3286
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003287static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3288 Decl *ParentDecl);
3289static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
3290 Decl *ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003291
3292/// CheckReturnStackAddr - Check if a return statement returns the address
3293/// of a stack variable.
3294void
3295Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
3296 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00003297
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003298 Expr *stackE = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003299 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003300
3301 // Perform checking for returned stack addresses, local blocks,
3302 // label addresses or references to temporaries.
John McCallf85e1932011-06-15 23:02:42 +00003303 if (lhsType->isPointerType() ||
David Blaikie4e4d0842012-03-11 07:00:24 +00003304 (!getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003305 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003306 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003307 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003308 }
3309
3310 if (stackE == 0)
3311 return; // Nothing suspicious was found.
3312
3313 SourceLocation diagLoc;
3314 SourceRange diagRange;
3315 if (refVars.empty()) {
3316 diagLoc = stackE->getLocStart();
3317 diagRange = stackE->getSourceRange();
3318 } else {
3319 // We followed through a reference variable. 'stackE' contains the
3320 // problematic expression but we will warn at the return statement pointing
3321 // at the reference variable. We will later display the "trail" of
3322 // reference variables using notes.
3323 diagLoc = refVars[0]->getLocStart();
3324 diagRange = refVars[0]->getSourceRange();
3325 }
3326
3327 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
3328 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
3329 : diag::warn_ret_stack_addr)
3330 << DR->getDecl()->getDeclName() << diagRange;
3331 } else if (isa<BlockExpr>(stackE)) { // local block.
3332 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
3333 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
3334 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
3335 } else { // local temporary.
3336 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
3337 : diag::warn_ret_local_temp_addr)
3338 << diagRange;
3339 }
3340
3341 // Display the "trail" of reference variables that we followed until we
3342 // found the problematic expression using notes.
3343 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
3344 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
3345 // If this var binds to another reference var, show the range of the next
3346 // var, otherwise the var binds to the problematic expression, in which case
3347 // show the range of the expression.
3348 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
3349 : stackE->getSourceRange();
3350 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
3351 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00003352 }
3353}
3354
3355/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
3356/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003357/// to a location on the stack, a local block, an address of a label, or a
3358/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00003359/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003360/// encounter a subexpression that (1) clearly does not lead to one of the
3361/// above problematic expressions (2) is something we cannot determine leads to
3362/// a problematic expression based on such local checking.
3363///
3364/// Both EvalAddr and EvalVal follow through reference variables to evaluate
3365/// the expression that they point to. Such variables are added to the
3366/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00003367///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00003368/// EvalAddr processes expressions that are pointers that are used as
3369/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003370/// At the base case of the recursion is a check for the above problematic
3371/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00003372///
3373/// This implementation handles:
3374///
3375/// * pointer-to-pointer casts
3376/// * implicit conversions from array references to pointers
3377/// * taking the address of fields
3378/// * arbitrary interplay between "&" and "*" operators
3379/// * pointer arithmetic from an address of a stack variable
3380/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003381static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3382 Decl *ParentDecl) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003383 if (E->isTypeDependent())
3384 return NULL;
3385
Ted Kremenek06de2762007-08-17 16:46:58 +00003386 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00003387 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00003388 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003389 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003390 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00003391
Peter Collingbournef111d932011-04-15 00:35:48 +00003392 E = E->IgnoreParens();
3393
Ted Kremenek06de2762007-08-17 16:46:58 +00003394 // Our "symbolic interpreter" is just a dispatch off the currently
3395 // viewed AST node. We then recursively traverse the AST by calling
3396 // EvalAddr and EvalVal appropriately.
3397 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003398 case Stmt::DeclRefExprClass: {
3399 DeclRefExpr *DR = cast<DeclRefExpr>(E);
3400
3401 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
3402 // If this is a reference variable, follow through to the expression that
3403 // it points to.
3404 if (V->hasLocalStorage() &&
3405 V->getType()->isReferenceType() && V->hasInit()) {
3406 // Add the reference variable to the "trail".
3407 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003408 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003409 }
3410
3411 return NULL;
3412 }
Ted Kremenek06de2762007-08-17 16:46:58 +00003413
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003414 case Stmt::UnaryOperatorClass: {
3415 // The only unary operator that make sense to handle here
3416 // is AddrOf. All others don't make sense as pointers.
3417 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003418
John McCall2de56d12010-08-25 11:45:40 +00003419 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003420 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003421 else
Ted Kremenek06de2762007-08-17 16:46:58 +00003422 return NULL;
3423 }
Mike Stump1eb44332009-09-09 15:08:12 +00003424
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003425 case Stmt::BinaryOperatorClass: {
3426 // Handle pointer arithmetic. All other binary operators are not valid
3427 // in this context.
3428 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00003429 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00003430
John McCall2de56d12010-08-25 11:45:40 +00003431 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003432 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00003433
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003434 Expr *Base = B->getLHS();
3435
3436 // Determine which argument is the real pointer base. It could be
3437 // the RHS argument instead of the LHS.
3438 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00003439
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003440 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003441 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003442 }
Steve Naroff61f40a22008-09-10 19:17:48 +00003443
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003444 // For conditional operators we need to see if either the LHS or RHS are
3445 // valid DeclRefExpr*s. If one of them is valid, we return it.
3446 case Stmt::ConditionalOperatorClass: {
3447 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003448
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003449 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003450 if (Expr *lhsExpr = C->getLHS()) {
3451 // In C++, we can have a throw-expression, which has 'void' type.
3452 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003453 if (Expr* LHS = EvalAddr(lhsExpr, refVars, ParentDecl))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003454 return LHS;
3455 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003456
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003457 // In C++, we can have a throw-expression, which has 'void' type.
3458 if (C->getRHS()->getType()->isVoidType())
3459 return NULL;
3460
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003461 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003462 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003463
3464 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00003465 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003466 return E; // local block.
3467 return NULL;
3468
3469 case Stmt::AddrLabelExprClass:
3470 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00003471
John McCall80ee6e82011-11-10 05:35:25 +00003472 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003473 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
3474 ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00003475
Ted Kremenek54b52742008-08-07 00:49:01 +00003476 // For casts, we need to handle conversions from arrays to
3477 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00003478 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00003479 case Stmt::CStyleCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00003480 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8b9414e2012-02-23 23:04:32 +00003481 case Stmt::ObjCBridgedCastExprClass:
Mike Stump1eb44332009-09-09 15:08:12 +00003482 case Stmt::CXXStaticCastExprClass:
3483 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00003484 case Stmt::CXXConstCastExprClass:
3485 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8b9414e2012-02-23 23:04:32 +00003486 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
3487 switch (cast<CastExpr>(E)->getCastKind()) {
3488 case CK_BitCast:
3489 case CK_LValueToRValue:
3490 case CK_NoOp:
3491 case CK_BaseToDerived:
3492 case CK_DerivedToBase:
3493 case CK_UncheckedDerivedToBase:
3494 case CK_Dynamic:
3495 case CK_CPointerToObjCPointerCast:
3496 case CK_BlockPointerToObjCPointerCast:
3497 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003498 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00003499
3500 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003501 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00003502
3503 default:
3504 return 0;
3505 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003506 }
Mike Stump1eb44332009-09-09 15:08:12 +00003507
Douglas Gregor03e80032011-06-21 17:03:29 +00003508 case Stmt::MaterializeTemporaryExprClass:
3509 if (Expr *Result = EvalAddr(
3510 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003511 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00003512 return Result;
3513
3514 return E;
3515
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003516 // Everything else: we simply don't reason about them.
3517 default:
3518 return NULL;
3519 }
Ted Kremenek06de2762007-08-17 16:46:58 +00003520}
Mike Stump1eb44332009-09-09 15:08:12 +00003521
Ted Kremenek06de2762007-08-17 16:46:58 +00003522
3523/// EvalVal - This function is complements EvalAddr in the mutual recursion.
3524/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003525static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3526 Decl *ParentDecl) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003527do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00003528 // We should only be called for evaluating non-pointer expressions, or
3529 // expressions with a pointer type that are not used as references but instead
3530 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00003531
Ted Kremenek06de2762007-08-17 16:46:58 +00003532 // Our "symbolic interpreter" is just a dispatch off the currently
3533 // viewed AST node. We then recursively traverse the AST by calling
3534 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00003535
3536 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00003537 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003538 case Stmt::ImplicitCastExprClass: {
3539 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00003540 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003541 E = IE->getSubExpr();
3542 continue;
3543 }
3544 return NULL;
3545 }
3546
John McCall80ee6e82011-11-10 05:35:25 +00003547 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003548 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00003549
Douglas Gregora2813ce2009-10-23 18:54:35 +00003550 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003551 // When we hit a DeclRefExpr we are looking at code that refers to a
3552 // variable's name. If it's not a reference variable we check if it has
3553 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00003554 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003555
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003556 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
3557 // Check if it refers to itself, e.g. "int& i = i;".
3558 if (V == ParentDecl)
3559 return DR;
3560
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003561 if (V->hasLocalStorage()) {
3562 if (!V->getType()->isReferenceType())
3563 return DR;
3564
3565 // Reference variable, follow through to the expression that
3566 // it points to.
3567 if (V->hasInit()) {
3568 // Add the reference variable to the "trail".
3569 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003570 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003571 }
3572 }
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003573 }
Mike Stump1eb44332009-09-09 15:08:12 +00003574
Ted Kremenek06de2762007-08-17 16:46:58 +00003575 return NULL;
3576 }
Mike Stump1eb44332009-09-09 15:08:12 +00003577
Ted Kremenek06de2762007-08-17 16:46:58 +00003578 case Stmt::UnaryOperatorClass: {
3579 // The only unary operator that make sense to handle here
3580 // is Deref. All others don't resolve to a "name." This includes
3581 // handling all sorts of rvalues passed to a unary operator.
3582 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003583
John McCall2de56d12010-08-25 11:45:40 +00003584 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003585 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003586
3587 return NULL;
3588 }
Mike Stump1eb44332009-09-09 15:08:12 +00003589
Ted Kremenek06de2762007-08-17 16:46:58 +00003590 case Stmt::ArraySubscriptExprClass: {
3591 // Array subscripts are potential references to data on the stack. We
3592 // retrieve the DeclRefExpr* for the array variable if it indeed
3593 // has local storage.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003594 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003595 }
Mike Stump1eb44332009-09-09 15:08:12 +00003596
Ted Kremenek06de2762007-08-17 16:46:58 +00003597 case Stmt::ConditionalOperatorClass: {
3598 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003599 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00003600 ConditionalOperator *C = cast<ConditionalOperator>(E);
3601
Anders Carlsson39073232007-11-30 19:04:31 +00003602 // Handle the GNU extension for missing LHS.
3603 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003604 if (Expr *LHS = EvalVal(lhsExpr, refVars, ParentDecl))
Anders Carlsson39073232007-11-30 19:04:31 +00003605 return LHS;
3606
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003607 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003608 }
Mike Stump1eb44332009-09-09 15:08:12 +00003609
Ted Kremenek06de2762007-08-17 16:46:58 +00003610 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00003611 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00003612 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003613
Ted Kremenek06de2762007-08-17 16:46:58 +00003614 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00003615 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00003616 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00003617
3618 // Check whether the member type is itself a reference, in which case
3619 // we're not going to refer to the member, but to what the member refers to.
3620 if (M->getMemberDecl()->getType()->isReferenceType())
3621 return NULL;
3622
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003623 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003624 }
Mike Stump1eb44332009-09-09 15:08:12 +00003625
Douglas Gregor03e80032011-06-21 17:03:29 +00003626 case Stmt::MaterializeTemporaryExprClass:
3627 if (Expr *Result = EvalVal(
3628 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003629 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00003630 return Result;
3631
3632 return E;
3633
Ted Kremenek06de2762007-08-17 16:46:58 +00003634 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003635 // Check that we don't return or take the address of a reference to a
3636 // temporary. This is only useful in C++.
3637 if (!E->isTypeDependent() && E->isRValue())
3638 return E;
3639
3640 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00003641 return NULL;
3642 }
Ted Kremenek68957a92010-08-04 20:01:07 +00003643} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00003644}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003645
3646//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
3647
3648/// Check for comparisons of floating point operands using != and ==.
3649/// Issue a warning if these are no self-comparisons, as they are not likely
3650/// to do what the programmer intended.
Richard Trieudd225092011-09-15 21:56:47 +00003651void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieudd225092011-09-15 21:56:47 +00003652 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
3653 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003654
3655 // Special case: check for x == x (which is OK).
3656 // Do not emit warnings for such cases.
3657 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
3658 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
3659 if (DRL->getDecl() == DRR->getDecl())
David Blaikie980343b2012-07-16 20:47:22 +00003660 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003661
3662
Ted Kremenek1b500bb2007-11-29 00:59:04 +00003663 // Special case: check for comparisons against literals that can be exactly
3664 // represented by APFloat. In such cases, do not emit a warning. This
3665 // is a heuristic: often comparison against such literals are used to
3666 // detect if a value in a variable has not changed. This clearly can
3667 // lead to false negatives.
David Blaikie980343b2012-07-16 20:47:22 +00003668 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
3669 if (FLL->isExact())
3670 return;
3671 } else
3672 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
3673 if (FLR->isExact())
3674 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003675
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003676 // Check for comparisons with builtin types.
David Blaikie980343b2012-07-16 20:47:22 +00003677 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
3678 if (CL->isBuiltinCall())
3679 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003680
David Blaikie980343b2012-07-16 20:47:22 +00003681 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
3682 if (CR->isBuiltinCall())
3683 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003684
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003685 // Emit the diagnostic.
David Blaikie980343b2012-07-16 20:47:22 +00003686 Diag(Loc, diag::warn_floatingpoint_eq)
3687 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003688}
John McCallba26e582010-01-04 23:21:16 +00003689
John McCallf2370c92010-01-06 05:24:50 +00003690//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
3691//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00003692
John McCallf2370c92010-01-06 05:24:50 +00003693namespace {
John McCallba26e582010-01-04 23:21:16 +00003694
John McCallf2370c92010-01-06 05:24:50 +00003695/// Structure recording the 'active' range of an integer-valued
3696/// expression.
3697struct IntRange {
3698 /// The number of bits active in the int.
3699 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00003700
John McCallf2370c92010-01-06 05:24:50 +00003701 /// True if the int is known not to have negative values.
3702 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00003703
John McCallf2370c92010-01-06 05:24:50 +00003704 IntRange(unsigned Width, bool NonNegative)
3705 : Width(Width), NonNegative(NonNegative)
3706 {}
John McCallba26e582010-01-04 23:21:16 +00003707
John McCall1844a6e2010-11-10 23:38:19 +00003708 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00003709 static IntRange forBoolType() {
3710 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00003711 }
3712
John McCall1844a6e2010-11-10 23:38:19 +00003713 /// Returns the range of an opaque value of the given integral type.
3714 static IntRange forValueOfType(ASTContext &C, QualType T) {
3715 return forValueOfCanonicalType(C,
3716 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00003717 }
3718
John McCall1844a6e2010-11-10 23:38:19 +00003719 /// Returns the range of an opaque value of a canonical integral type.
3720 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00003721 assert(T->isCanonicalUnqualified());
3722
3723 if (const VectorType *VT = dyn_cast<VectorType>(T))
3724 T = VT->getElementType().getTypePtr();
3725 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
3726 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00003727
John McCall091f23f2010-11-09 22:22:12 +00003728 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00003729 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
3730 EnumDecl *Enum = ET->getDecl();
John McCall5e1cdac2011-10-07 06:10:15 +00003731 if (!Enum->isCompleteDefinition())
John McCall091f23f2010-11-09 22:22:12 +00003732 return IntRange(C.getIntWidth(QualType(T, 0)), false);
3733
John McCall323ed742010-05-06 08:58:33 +00003734 unsigned NumPositive = Enum->getNumPositiveBits();
3735 unsigned NumNegative = Enum->getNumNegativeBits();
3736
3737 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
3738 }
John McCallf2370c92010-01-06 05:24:50 +00003739
3740 const BuiltinType *BT = cast<BuiltinType>(T);
3741 assert(BT->isInteger());
3742
3743 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
3744 }
3745
John McCall1844a6e2010-11-10 23:38:19 +00003746 /// Returns the "target" range of a canonical integral type, i.e.
3747 /// the range of values expressible in the type.
3748 ///
3749 /// This matches forValueOfCanonicalType except that enums have the
3750 /// full range of their type, not the range of their enumerators.
3751 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
3752 assert(T->isCanonicalUnqualified());
3753
3754 if (const VectorType *VT = dyn_cast<VectorType>(T))
3755 T = VT->getElementType().getTypePtr();
3756 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
3757 T = CT->getElementType().getTypePtr();
3758 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor69ff26b2011-09-08 23:29:05 +00003759 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall1844a6e2010-11-10 23:38:19 +00003760
3761 const BuiltinType *BT = cast<BuiltinType>(T);
3762 assert(BT->isInteger());
3763
3764 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
3765 }
3766
3767 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00003768 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00003769 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00003770 L.NonNegative && R.NonNegative);
3771 }
3772
John McCall1844a6e2010-11-10 23:38:19 +00003773 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00003774 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00003775 return IntRange(std::min(L.Width, R.Width),
3776 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00003777 }
3778};
3779
Ted Kremenek0692a192012-01-31 05:37:37 +00003780static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
3781 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00003782 if (value.isSigned() && value.isNegative())
3783 return IntRange(value.getMinSignedBits(), false);
3784
3785 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00003786 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00003787
3788 // isNonNegative() just checks the sign bit without considering
3789 // signedness.
3790 return IntRange(value.getActiveBits(), true);
3791}
3792
Ted Kremenek0692a192012-01-31 05:37:37 +00003793static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
3794 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00003795 if (result.isInt())
3796 return GetValueRange(C, result.getInt(), MaxWidth);
3797
3798 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00003799 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
3800 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
3801 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
3802 R = IntRange::join(R, El);
3803 }
John McCallf2370c92010-01-06 05:24:50 +00003804 return R;
3805 }
3806
3807 if (result.isComplexInt()) {
3808 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
3809 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
3810 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00003811 }
3812
3813 // This can happen with lossless casts to intptr_t of "based" lvalues.
3814 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00003815 // FIXME: The only reason we need to pass the type in here is to get
3816 // the sign right on this one case. It would be nice if APValue
3817 // preserved this.
Eli Friedman65639282012-01-04 23:13:47 +00003818 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00003819 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall51313c32010-01-04 23:31:57 +00003820}
John McCallf2370c92010-01-06 05:24:50 +00003821
3822/// Pseudo-evaluate the given integer expression, estimating the
3823/// range of values it might take.
3824///
3825/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek0692a192012-01-31 05:37:37 +00003826static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00003827 E = E->IgnoreParens();
3828
3829 // Try a full evaluation first.
3830 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00003831 if (E->EvaluateAsRValue(result, C))
John McCall0acc3112010-01-06 22:57:21 +00003832 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00003833
3834 // I think we only want to look through implicit casts here; if the
3835 // user has an explicit widening cast, we should treat the value as
3836 // being of the new, wider type.
3837 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedmanb17ee5b2011-12-15 02:41:52 +00003838 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCallf2370c92010-01-06 05:24:50 +00003839 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
3840
John McCall1844a6e2010-11-10 23:38:19 +00003841 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCallf2370c92010-01-06 05:24:50 +00003842
John McCall2de56d12010-08-25 11:45:40 +00003843 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00003844
John McCallf2370c92010-01-06 05:24:50 +00003845 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00003846 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00003847 return OutputTypeRange;
3848
3849 IntRange SubRange
3850 = GetExprRange(C, CE->getSubExpr(),
3851 std::min(MaxWidth, OutputTypeRange.Width));
3852
3853 // Bail out if the subexpr's range is as wide as the cast type.
3854 if (SubRange.Width >= OutputTypeRange.Width)
3855 return OutputTypeRange;
3856
3857 // Otherwise, we take the smaller width, and we're non-negative if
3858 // either the output type or the subexpr is.
3859 return IntRange(SubRange.Width,
3860 SubRange.NonNegative || OutputTypeRange.NonNegative);
3861 }
3862
3863 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3864 // If we can fold the condition, just take that operand.
3865 bool CondResult;
3866 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
3867 return GetExprRange(C, CondResult ? CO->getTrueExpr()
3868 : CO->getFalseExpr(),
3869 MaxWidth);
3870
3871 // Otherwise, conservatively merge.
3872 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
3873 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
3874 return IntRange::join(L, R);
3875 }
3876
3877 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3878 switch (BO->getOpcode()) {
3879
3880 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00003881 case BO_LAnd:
3882 case BO_LOr:
3883 case BO_LT:
3884 case BO_GT:
3885 case BO_LE:
3886 case BO_GE:
3887 case BO_EQ:
3888 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00003889 return IntRange::forBoolType();
3890
John McCall862ff872011-07-13 06:35:24 +00003891 // The type of the assignments is the type of the LHS, so the RHS
3892 // is not necessarily the same type.
John McCall2de56d12010-08-25 11:45:40 +00003893 case BO_MulAssign:
3894 case BO_DivAssign:
3895 case BO_RemAssign:
3896 case BO_AddAssign:
3897 case BO_SubAssign:
John McCall862ff872011-07-13 06:35:24 +00003898 case BO_XorAssign:
3899 case BO_OrAssign:
3900 // TODO: bitfields?
John McCall1844a6e2010-11-10 23:38:19 +00003901 return IntRange::forValueOfType(C, E->getType());
John McCallc0cd21d2010-02-23 19:22:29 +00003902
John McCall862ff872011-07-13 06:35:24 +00003903 // Simple assignments just pass through the RHS, which will have
3904 // been coerced to the LHS type.
3905 case BO_Assign:
3906 // TODO: bitfields?
3907 return GetExprRange(C, BO->getRHS(), MaxWidth);
3908
John McCallf2370c92010-01-06 05:24:50 +00003909 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00003910 case BO_PtrMemD:
3911 case BO_PtrMemI:
John McCall1844a6e2010-11-10 23:38:19 +00003912 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003913
John McCall60fad452010-01-06 22:07:33 +00003914 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00003915 case BO_And:
3916 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00003917 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
3918 GetExprRange(C, BO->getRHS(), MaxWidth));
3919
John McCallf2370c92010-01-06 05:24:50 +00003920 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00003921 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00003922 // ...except that we want to treat '1 << (blah)' as logically
3923 // positive. It's an important idiom.
3924 if (IntegerLiteral *I
3925 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
3926 if (I->getValue() == 1) {
John McCall1844a6e2010-11-10 23:38:19 +00003927 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall3aae6092010-04-07 01:14:35 +00003928 return IntRange(R.Width, /*NonNegative*/ true);
3929 }
3930 }
3931 // fallthrough
3932
John McCall2de56d12010-08-25 11:45:40 +00003933 case BO_ShlAssign:
John McCall1844a6e2010-11-10 23:38:19 +00003934 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003935
John McCall60fad452010-01-06 22:07:33 +00003936 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00003937 case BO_Shr:
3938 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00003939 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3940
3941 // If the shift amount is a positive constant, drop the width by
3942 // that much.
3943 llvm::APSInt shift;
3944 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
3945 shift.isNonNegative()) {
3946 unsigned zext = shift.getZExtValue();
3947 if (zext >= L.Width)
3948 L.Width = (L.NonNegative ? 0 : 1);
3949 else
3950 L.Width -= zext;
3951 }
3952
3953 return L;
3954 }
3955
3956 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00003957 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00003958 return GetExprRange(C, BO->getRHS(), MaxWidth);
3959
John McCall60fad452010-01-06 22:07:33 +00003960 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00003961 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00003962 if (BO->getLHS()->getType()->isPointerType())
John McCall1844a6e2010-11-10 23:38:19 +00003963 return IntRange::forValueOfType(C, E->getType());
John McCall00fe7612011-07-14 22:39:48 +00003964 break;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003965
John McCall00fe7612011-07-14 22:39:48 +00003966 // The width of a division result is mostly determined by the size
3967 // of the LHS.
3968 case BO_Div: {
3969 // Don't 'pre-truncate' the operands.
3970 unsigned opWidth = C.getIntWidth(E->getType());
3971 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3972
3973 // If the divisor is constant, use that.
3974 llvm::APSInt divisor;
3975 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
3976 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
3977 if (log2 >= L.Width)
3978 L.Width = (L.NonNegative ? 0 : 1);
3979 else
3980 L.Width = std::min(L.Width - log2, MaxWidth);
3981 return L;
3982 }
3983
3984 // Otherwise, just use the LHS's width.
3985 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3986 return IntRange(L.Width, L.NonNegative && R.NonNegative);
3987 }
3988
3989 // The result of a remainder can't be larger than the result of
3990 // either side.
3991 case BO_Rem: {
3992 // Don't 'pre-truncate' the operands.
3993 unsigned opWidth = C.getIntWidth(E->getType());
3994 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3995 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3996
3997 IntRange meet = IntRange::meet(L, R);
3998 meet.Width = std::min(meet.Width, MaxWidth);
3999 return meet;
4000 }
4001
4002 // The default behavior is okay for these.
4003 case BO_Mul:
4004 case BO_Add:
4005 case BO_Xor:
4006 case BO_Or:
John McCallf2370c92010-01-06 05:24:50 +00004007 break;
4008 }
4009
John McCall00fe7612011-07-14 22:39:48 +00004010 // The default case is to treat the operation as if it were closed
4011 // on the narrowest type that encompasses both operands.
John McCallf2370c92010-01-06 05:24:50 +00004012 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4013 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
4014 return IntRange::join(L, R);
4015 }
4016
4017 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
4018 switch (UO->getOpcode()) {
4019 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00004020 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00004021 return IntRange::forBoolType();
4022
4023 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00004024 case UO_Deref:
4025 case UO_AddrOf: // should be impossible
John McCall1844a6e2010-11-10 23:38:19 +00004026 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00004027
4028 default:
4029 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
4030 }
4031 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004032
4033 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall1844a6e2010-11-10 23:38:19 +00004034 IntRange::forValueOfType(C, E->getType());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004035 }
John McCallf2370c92010-01-06 05:24:50 +00004036
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004037 if (FieldDecl *BitField = E->getBitField())
4038 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00004039 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00004040
John McCall1844a6e2010-11-10 23:38:19 +00004041 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00004042}
John McCall51313c32010-01-04 23:31:57 +00004043
Ted Kremenek0692a192012-01-31 05:37:37 +00004044static IntRange GetExprRange(ASTContext &C, Expr *E) {
John McCall323ed742010-05-06 08:58:33 +00004045 return GetExprRange(C, E, C.getIntWidth(E->getType()));
4046}
4047
John McCall51313c32010-01-04 23:31:57 +00004048/// Checks whether the given value, which currently has the given
4049/// source semantics, has the same value when coerced through the
4050/// target semantics.
Ted Kremenek0692a192012-01-31 05:37:37 +00004051static bool IsSameFloatAfterCast(const llvm::APFloat &value,
4052 const llvm::fltSemantics &Src,
4053 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00004054 llvm::APFloat truncated = value;
4055
4056 bool ignored;
4057 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
4058 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
4059
4060 return truncated.bitwiseIsEqual(value);
4061}
4062
4063/// Checks whether the given value, which currently has the given
4064/// source semantics, has the same value when coerced through the
4065/// target semantics.
4066///
4067/// The value might be a vector of floats (or a complex number).
Ted Kremenek0692a192012-01-31 05:37:37 +00004068static bool IsSameFloatAfterCast(const APValue &value,
4069 const llvm::fltSemantics &Src,
4070 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00004071 if (value.isFloat())
4072 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
4073
4074 if (value.isVector()) {
4075 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
4076 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
4077 return false;
4078 return true;
4079 }
4080
4081 assert(value.isComplexFloat());
4082 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
4083 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
4084}
4085
Ted Kremenek0692a192012-01-31 05:37:37 +00004086static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00004087
Ted Kremeneke3b159c2010-09-23 21:43:44 +00004088static bool IsZero(Sema &S, Expr *E) {
4089 // Suppress cases where we are comparing against an enum constant.
4090 if (const DeclRefExpr *DR =
4091 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
4092 if (isa<EnumConstantDecl>(DR->getDecl()))
4093 return false;
4094
4095 // Suppress cases where the '0' value is expanded from a macro.
4096 if (E->getLocStart().isMacroID())
4097 return false;
4098
John McCall323ed742010-05-06 08:58:33 +00004099 llvm::APSInt Value;
4100 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
4101}
4102
John McCall372e1032010-10-06 00:25:24 +00004103static bool HasEnumType(Expr *E) {
4104 // Strip off implicit integral promotions.
4105 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00004106 if (ICE->getCastKind() != CK_IntegralCast &&
4107 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00004108 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00004109 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00004110 }
4111
4112 return E->getType()->isEnumeralType();
4113}
4114
Ted Kremenek0692a192012-01-31 05:37:37 +00004115static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00004116 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00004117 if (E->isValueDependent())
4118 return;
4119
John McCall2de56d12010-08-25 11:45:40 +00004120 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00004121 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004122 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00004123 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004124 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00004125 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004126 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00004127 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004128 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00004129 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004130 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00004131 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004132 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00004133 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004134 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00004135 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4136 }
4137}
4138
4139/// Analyze the operands of the given comparison. Implements the
4140/// fallback case from AnalyzeComparison.
Ted Kremenek0692a192012-01-31 05:37:37 +00004141static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00004142 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4143 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00004144}
John McCall51313c32010-01-04 23:31:57 +00004145
John McCallba26e582010-01-04 23:21:16 +00004146/// \brief Implements -Wsign-compare.
4147///
Richard Trieudd225092011-09-15 21:56:47 +00004148/// \param E the binary operator to check for warnings
Ted Kremenek0692a192012-01-31 05:37:37 +00004149static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCall323ed742010-05-06 08:58:33 +00004150 // The type the comparison is being performed in.
4151 QualType T = E->getLHS()->getType();
4152 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
4153 && "comparison with mismatched types");
John McCallba26e582010-01-04 23:21:16 +00004154
John McCall323ed742010-05-06 08:58:33 +00004155 // We don't do anything special if this isn't an unsigned integral
4156 // comparison: we're only interested in integral comparisons, and
4157 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00004158 //
4159 // We also don't care about value-dependent expressions or expressions
4160 // whose result is a constant.
4161 if (!T->hasUnsignedIntegerRepresentation()
4162 || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
John McCall323ed742010-05-06 08:58:33 +00004163 return AnalyzeImpConvsInComparison(S, E);
John McCallf2370c92010-01-06 05:24:50 +00004164
Richard Trieudd225092011-09-15 21:56:47 +00004165 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
4166 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
John McCallba26e582010-01-04 23:21:16 +00004167
John McCall323ed742010-05-06 08:58:33 +00004168 // Check to see if one of the (unmodified) operands is of different
4169 // signedness.
4170 Expr *signedOperand, *unsignedOperand;
Richard Trieudd225092011-09-15 21:56:47 +00004171 if (LHS->getType()->hasSignedIntegerRepresentation()) {
4172 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00004173 "unsigned comparison between two signed integer expressions?");
Richard Trieudd225092011-09-15 21:56:47 +00004174 signedOperand = LHS;
4175 unsignedOperand = RHS;
4176 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
4177 signedOperand = RHS;
4178 unsignedOperand = LHS;
John McCallba26e582010-01-04 23:21:16 +00004179 } else {
John McCall323ed742010-05-06 08:58:33 +00004180 CheckTrivialUnsignedComparison(S, E);
4181 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004182 }
4183
John McCall323ed742010-05-06 08:58:33 +00004184 // Otherwise, calculate the effective range of the signed operand.
4185 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00004186
John McCall323ed742010-05-06 08:58:33 +00004187 // Go ahead and analyze implicit conversions in the operands. Note
4188 // that we skip the implicit conversions on both sides.
Richard Trieudd225092011-09-15 21:56:47 +00004189 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
4190 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00004191
John McCall323ed742010-05-06 08:58:33 +00004192 // If the signed range is non-negative, -Wsign-compare won't fire,
4193 // but we should still check for comparisons which are always true
4194 // or false.
4195 if (signedRange.NonNegative)
4196 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004197
4198 // For (in)equality comparisons, if the unsigned operand is a
4199 // constant which cannot collide with a overflowed signed operand,
4200 // then reinterpreting the signed operand as unsigned will not
4201 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00004202 if (E->isEqualityOp()) {
4203 unsigned comparisonWidth = S.Context.getIntWidth(T);
4204 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00004205
John McCall323ed742010-05-06 08:58:33 +00004206 // We should never be unable to prove that the unsigned operand is
4207 // non-negative.
4208 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
4209
4210 if (unsignedRange.Width < comparisonWidth)
4211 return;
4212 }
4213
Douglas Gregor6d3b93d2012-05-01 01:53:49 +00004214 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
4215 S.PDiag(diag::warn_mixed_sign_comparison)
4216 << LHS->getType() << RHS->getType()
4217 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallba26e582010-01-04 23:21:16 +00004218}
4219
John McCall15d7d122010-11-11 03:21:53 +00004220/// Analyzes an attempt to assign the given value to a bitfield.
4221///
4222/// Returns true if there was something fishy about the attempt.
Ted Kremenek0692a192012-01-31 05:37:37 +00004223static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
4224 SourceLocation InitLoc) {
John McCall15d7d122010-11-11 03:21:53 +00004225 assert(Bitfield->isBitField());
4226 if (Bitfield->isInvalidDecl())
4227 return false;
4228
John McCall91b60142010-11-11 05:33:51 +00004229 // White-list bool bitfields.
4230 if (Bitfield->getType()->isBooleanType())
4231 return false;
4232
Douglas Gregor46ff3032011-02-04 13:09:01 +00004233 // Ignore value- or type-dependent expressions.
4234 if (Bitfield->getBitWidth()->isValueDependent() ||
4235 Bitfield->getBitWidth()->isTypeDependent() ||
4236 Init->isValueDependent() ||
4237 Init->isTypeDependent())
4238 return false;
4239
John McCall15d7d122010-11-11 03:21:53 +00004240 Expr *OriginalInit = Init->IgnoreParenImpCasts();
4241
Richard Smith80d4b552011-12-28 19:48:30 +00004242 llvm::APSInt Value;
4243 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall15d7d122010-11-11 03:21:53 +00004244 return false;
4245
John McCall15d7d122010-11-11 03:21:53 +00004246 unsigned OriginalWidth = Value.getBitWidth();
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004247 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall15d7d122010-11-11 03:21:53 +00004248
4249 if (OriginalWidth <= FieldWidth)
4250 return false;
4251
Eli Friedman3a643af2012-01-26 23:11:39 +00004252 // Compute the value which the bitfield will contain.
Jay Foad9f71a8f2010-12-07 08:25:34 +00004253 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedman3a643af2012-01-26 23:11:39 +00004254 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall15d7d122010-11-11 03:21:53 +00004255
Eli Friedman3a643af2012-01-26 23:11:39 +00004256 // Check whether the stored value is equal to the original value.
4257 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieue1ecdc12012-07-23 20:21:35 +00004258 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall15d7d122010-11-11 03:21:53 +00004259 return false;
4260
Eli Friedman3a643af2012-01-26 23:11:39 +00004261 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedman34ff0622012-02-02 00:40:20 +00004262 // therefore don't strictly fit into a signed bitfield of width 1.
4263 if (FieldWidth == 1 && Value == 1)
Eli Friedman3a643af2012-01-26 23:11:39 +00004264 return false;
4265
John McCall15d7d122010-11-11 03:21:53 +00004266 std::string PrettyValue = Value.toString(10);
4267 std::string PrettyTrunc = TruncatedValue.toString(10);
4268
4269 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
4270 << PrettyValue << PrettyTrunc << OriginalInit->getType()
4271 << Init->getSourceRange();
4272
4273 return true;
4274}
4275
John McCallbeb22aa2010-11-09 23:24:47 +00004276/// Analyze the given simple or compound assignment for warning-worthy
4277/// operations.
Ted Kremenek0692a192012-01-31 05:37:37 +00004278static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCallbeb22aa2010-11-09 23:24:47 +00004279 // Just recurse on the LHS.
4280 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4281
4282 // We want to recurse on the RHS as normal unless we're assigning to
4283 // a bitfield.
4284 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
John McCall15d7d122010-11-11 03:21:53 +00004285 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
4286 E->getOperatorLoc())) {
4287 // Recurse, ignoring any implicit conversions on the RHS.
4288 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
4289 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00004290 }
4291 }
4292
4293 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
4294}
4295
John McCall51313c32010-01-04 23:31:57 +00004296/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00004297static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00004298 SourceLocation CContext, unsigned diag,
4299 bool pruneControlFlow = false) {
4300 if (pruneControlFlow) {
4301 S.DiagRuntimeBehavior(E->getExprLoc(), E,
4302 S.PDiag(diag)
4303 << SourceType << T << E->getSourceRange()
4304 << SourceRange(CContext));
4305 return;
4306 }
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004307 S.Diag(E->getExprLoc(), diag)
4308 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
4309}
4310
Chandler Carruthe1b02e02011-04-05 06:47:57 +00004311/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00004312static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00004313 SourceLocation CContext, unsigned diag,
4314 bool pruneControlFlow = false) {
4315 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruthe1b02e02011-04-05 06:47:57 +00004316}
4317
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004318/// Diagnose an implicit cast from a literal expression. Does not warn when the
4319/// cast wouldn't lose information.
Chandler Carruthf65076e2011-04-10 08:36:24 +00004320void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
4321 SourceLocation CContext) {
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004322 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruthf65076e2011-04-10 08:36:24 +00004323 bool isExact = false;
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004324 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00004325 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
4326 T->hasUnsignedIntegerRepresentation());
4327 if (Value.convertToInteger(IntegerValue,
Chandler Carruthf65076e2011-04-10 08:36:24 +00004328 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004329 == llvm::APFloat::opOK && isExact)
Chandler Carruthf65076e2011-04-10 08:36:24 +00004330 return;
4331
David Blaikiebe0ee872012-05-15 16:56:36 +00004332 SmallString<16> PrettySourceValue;
4333 Value.toString(PrettySourceValue);
David Blaikiede7e7b82012-05-15 17:18:27 +00004334 SmallString<16> PrettyTargetValue;
David Blaikiebe0ee872012-05-15 16:56:36 +00004335 if (T->isSpecificBuiltinType(BuiltinType::Bool))
4336 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
4337 else
David Blaikiede7e7b82012-05-15 17:18:27 +00004338 IntegerValue.toString(PrettyTargetValue);
David Blaikiebe0ee872012-05-15 16:56:36 +00004339
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004340 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikiebe0ee872012-05-15 16:56:36 +00004341 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
4342 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruthf65076e2011-04-10 08:36:24 +00004343}
4344
John McCall091f23f2010-11-09 22:22:12 +00004345std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
4346 if (!Range.Width) return "0";
4347
4348 llvm::APSInt ValueInRange = Value;
4349 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00004350 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00004351 return ValueInRange.toString(10);
4352}
4353
John McCall323ed742010-05-06 08:58:33 +00004354void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00004355 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00004356 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00004357
John McCall323ed742010-05-06 08:58:33 +00004358 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
4359 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
4360 if (Source == Target) return;
4361 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00004362
Chandler Carruth108f7562011-07-26 05:40:03 +00004363 // If the conversion context location is invalid don't complain. We also
4364 // don't want to emit a warning if the issue occurs from the expansion of
4365 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
4366 // delay this check as long as possible. Once we detect we are in that
4367 // scenario, we just return.
Ted Kremenekef9ff882011-03-10 20:03:42 +00004368 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00004369 return;
4370
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004371 // Diagnose implicit casts to bool.
4372 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
4373 if (isa<StringLiteral>(E))
4374 // Warn on string literal to bool. Checks for string literals in logical
4375 // expressions, for instances, assert(0 && "error here"), is prevented
4376 // by a check in AnalyzeImplicitConversions().
4377 return DiagnoseImpCast(S, E, T, CC,
4378 diag::warn_impcast_string_literal_to_bool);
Lang Hamese14ca9f2011-12-05 20:49:50 +00004379 if (Source->isFunctionType()) {
4380 // Warn on function to bool. Checks free functions and static member
4381 // functions. Weakly imported functions are excluded from the check,
4382 // since it's common to test their value to check whether the linker
4383 // found a definition for them.
4384 ValueDecl *D = 0;
4385 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
4386 D = R->getDecl();
4387 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
4388 D = M->getMemberDecl();
4389 }
4390
4391 if (D && !D->isWeak()) {
Richard Trieu26b45d82011-12-06 04:48:01 +00004392 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
4393 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
4394 << F << E->getSourceRange() << SourceRange(CC);
David Blaikie2def7732011-12-09 21:42:37 +00004395 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
4396 << FixItHint::CreateInsertion(E->getExprLoc(), "&");
4397 QualType ReturnType;
4398 UnresolvedSet<4> NonTemplateOverloads;
4399 S.isExprCallable(*E, ReturnType, NonTemplateOverloads);
4400 if (!ReturnType.isNull()
4401 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
4402 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
4403 << FixItHint::CreateInsertion(
4404 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu26b45d82011-12-06 04:48:01 +00004405 return;
4406 }
Lang Hamese14ca9f2011-12-05 20:49:50 +00004407 }
4408 }
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004409 }
John McCall51313c32010-01-04 23:31:57 +00004410
4411 // Strip vector types.
4412 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004413 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004414 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004415 return;
John McCallb4eb64d2010-10-08 02:01:28 +00004416 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004417 }
Chris Lattnerb792b302011-06-14 04:51:15 +00004418
4419 // If the vector cast is cast between two vectors of the same size, it is
4420 // a bitcast, not a conversion.
4421 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
4422 return;
John McCall51313c32010-01-04 23:31:57 +00004423
4424 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
4425 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
4426 }
4427
4428 // Strip complex types.
4429 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004430 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004431 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004432 return;
4433
John McCallb4eb64d2010-10-08 02:01:28 +00004434 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004435 }
John McCall51313c32010-01-04 23:31:57 +00004436
4437 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
4438 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
4439 }
4440
4441 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
4442 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
4443
4444 // If the source is floating point...
4445 if (SourceBT && SourceBT->isFloatingPoint()) {
4446 // ...and the target is floating point...
4447 if (TargetBT && TargetBT->isFloatingPoint()) {
4448 // ...then warn if we're dropping FP rank.
4449
4450 // Builtin FP kinds are ordered by increasing FP rank.
4451 if (SourceBT->getKind() > TargetBT->getKind()) {
4452 // Don't warn about float constants that are precisely
4453 // representable in the target type.
4454 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00004455 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00004456 // Value might be a float, a float vector, or a float complex.
4457 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00004458 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
4459 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00004460 return;
4461 }
4462
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004463 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004464 return;
4465
John McCallb4eb64d2010-10-08 02:01:28 +00004466 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00004467 }
4468 return;
4469 }
4470
Ted Kremenekef9ff882011-03-10 20:03:42 +00004471 // If the target is integral, always warn.
David Blaikiebe0ee872012-05-15 16:56:36 +00004472 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004473 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004474 return;
4475
Chandler Carrutha5b93322011-02-17 11:05:49 +00004476 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay634c8af2011-09-08 22:30:47 +00004477 // We also want to warn on, e.g., "int i = -1.234"
4478 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
4479 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
4480 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
4481
Chandler Carruthf65076e2011-04-10 08:36:24 +00004482 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
4483 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00004484 } else {
4485 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
4486 }
4487 }
John McCall51313c32010-01-04 23:31:57 +00004488
4489 return;
4490 }
4491
Richard Trieu1838ca52011-05-29 19:59:02 +00004492 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
David Blaikieb26331b2012-06-19 21:19:06 +00004493 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
David Blaikie28a5f0c2012-06-21 18:51:10 +00004494 && !Target->isBlockPointerType() && !Target->isMemberPointerType()) {
David Blaikieb1360492012-03-16 20:30:12 +00004495 SourceLocation Loc = E->getSourceRange().getBegin();
4496 if (Loc.isMacroID())
4497 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
David Blaikie9fb1ac52012-05-15 21:57:38 +00004498 if (!Loc.isMacroID() || CC.isMacroID())
4499 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
4500 << T << clang::SourceRange(CC)
4501 << FixItHint::CreateReplacement(Loc, S.getFixItZeroLiteralForType(T));
Richard Trieu1838ca52011-05-29 19:59:02 +00004502 }
4503
David Blaikieb26331b2012-06-19 21:19:06 +00004504 if (!Source->isIntegerType() || !Target->isIntegerType())
4505 return;
4506
David Blaikiebe0ee872012-05-15 16:56:36 +00004507 // TODO: remove this early return once the false positives for constant->bool
4508 // in templates, macros, etc, are reduced or removed.
4509 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
4510 return;
4511
John McCall323ed742010-05-06 08:58:33 +00004512 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00004513 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00004514
4515 if (SourceRange.Width > TargetRange.Width) {
John McCall091f23f2010-11-09 22:22:12 +00004516 // If the source is a constant, use a default-on diagnostic.
4517 // TODO: this should happen for bitfield stores, too.
4518 llvm::APSInt Value(32);
4519 if (E->isIntegerConstantExpr(Value, S.Context)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004520 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004521 return;
4522
John McCall091f23f2010-11-09 22:22:12 +00004523 std::string PrettySourceValue = Value.toString(10);
4524 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
4525
Ted Kremenek5e745da2011-10-22 02:37:33 +00004526 S.DiagRuntimeBehavior(E->getExprLoc(), E,
4527 S.PDiag(diag::warn_impcast_integer_precision_constant)
4528 << PrettySourceValue << PrettyTargetValue
4529 << E->getType() << T << E->getSourceRange()
4530 << clang::SourceRange(CC));
John McCall091f23f2010-11-09 22:22:12 +00004531 return;
4532 }
4533
Chris Lattnerb792b302011-06-14 04:51:15 +00004534 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004535 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004536 return;
4537
David Blaikie37050842012-04-12 22:40:54 +00004538 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaksc36bedc2012-02-01 19:08:57 +00004539 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
4540 /* pruneControlFlow */ true);
John McCallb4eb64d2010-10-08 02:01:28 +00004541 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00004542 }
4543
4544 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
4545 (!TargetRange.NonNegative && SourceRange.NonNegative &&
4546 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004547
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004548 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004549 return;
4550
John McCall323ed742010-05-06 08:58:33 +00004551 unsigned DiagID = diag::warn_impcast_integer_sign;
4552
4553 // Traditionally, gcc has warned about this under -Wsign-compare.
4554 // We also want to warn about it in -Wconversion.
4555 // So if -Wconversion is off, use a completely identical diagnostic
4556 // in the sign-compare group.
4557 // The conditional-checking code will
4558 if (ICContext) {
4559 DiagID = diag::warn_impcast_integer_sign_conditional;
4560 *ICContext = true;
4561 }
4562
John McCallb4eb64d2010-10-08 02:01:28 +00004563 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00004564 }
4565
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004566 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004567 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
4568 // type, to give us better diagnostics.
4569 QualType SourceType = E->getType();
David Blaikie4e4d0842012-03-11 07:00:24 +00004570 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004571 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
4572 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
4573 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
4574 SourceType = S.Context.getTypeDeclType(Enum);
4575 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
4576 }
4577 }
4578
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004579 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
4580 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
4581 if ((SourceEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00004582 SourceEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004583 (TargetEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00004584 TargetEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00004585 SourceEnum != TargetEnum) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004586 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004587 return;
4588
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004589 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004590 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004591 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004592
John McCall51313c32010-01-04 23:31:57 +00004593 return;
4594}
4595
David Blaikie9fb1ac52012-05-15 21:57:38 +00004596void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
4597 SourceLocation CC, QualType T);
John McCall323ed742010-05-06 08:58:33 +00004598
4599void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00004600 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00004601 E = E->IgnoreParenImpCasts();
4602
4603 if (isa<ConditionalOperator>(E))
David Blaikie9fb1ac52012-05-15 21:57:38 +00004604 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCall323ed742010-05-06 08:58:33 +00004605
John McCallb4eb64d2010-10-08 02:01:28 +00004606 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00004607 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00004608 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00004609 return;
4610}
4611
David Blaikie9fb1ac52012-05-15 21:57:38 +00004612void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
4613 SourceLocation CC, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00004614 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00004615
4616 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00004617 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
4618 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00004619
4620 // If -Wconversion would have warned about either of the candidates
4621 // for a signedness conversion to the context type...
4622 if (!Suspicious) return;
4623
4624 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00004625 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
4626 CC))
John McCall323ed742010-05-06 08:58:33 +00004627 return;
4628
John McCall323ed742010-05-06 08:58:33 +00004629 // ...then check whether it would have warned about either of the
4630 // candidates for a signedness conversion to the condition type.
Richard Trieu52541612011-07-21 02:46:28 +00004631 if (E->getType() == T) return;
4632
4633 Suspicious = false;
4634 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
4635 E->getType(), CC, &Suspicious);
4636 if (!Suspicious)
4637 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00004638 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00004639}
4640
4641/// AnalyzeImplicitConversions - Find and report any interesting
4642/// implicit conversions in the given expression. There are a couple
4643/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00004644void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00004645 QualType T = OrigE->getType();
4646 Expr *E = OrigE->IgnoreParenImpCasts();
4647
Douglas Gregorf8b6e152011-10-10 17:38:18 +00004648 if (E->isTypeDependent() || E->isValueDependent())
4649 return;
4650
John McCall323ed742010-05-06 08:58:33 +00004651 // For conditional operators, we analyze the arguments as if they
4652 // were being fed directly into the output.
4653 if (isa<ConditionalOperator>(E)) {
4654 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie9fb1ac52012-05-15 21:57:38 +00004655 CheckConditionalOperator(S, CO, CC, T);
John McCall323ed742010-05-06 08:58:33 +00004656 return;
4657 }
4658
4659 // Go ahead and check any implicit conversions we might have skipped.
4660 // The non-canonical typecheck is just an optimization;
4661 // CheckImplicitConversion will filter out dead implicit conversions.
4662 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00004663 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00004664
4665 // Now continue drilling into this expression.
4666
4667 // Skip past explicit casts.
4668 if (isa<ExplicitCastExpr>(E)) {
4669 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00004670 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00004671 }
4672
John McCallbeb22aa2010-11-09 23:24:47 +00004673 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4674 // Do a somewhat different check with comparison operators.
4675 if (BO->isComparisonOp())
4676 return AnalyzeComparison(S, BO);
4677
Eli Friedman0fa06382012-01-26 23:34:06 +00004678 // And with simple assignments.
4679 if (BO->getOpcode() == BO_Assign)
John McCallbeb22aa2010-11-09 23:24:47 +00004680 return AnalyzeAssignment(S, BO);
4681 }
John McCall323ed742010-05-06 08:58:33 +00004682
4683 // These break the otherwise-useful invariant below. Fortunately,
4684 // we don't really need to recurse into them, because any internal
4685 // expressions should have been analyzed already when they were
4686 // built into statements.
4687 if (isa<StmtExpr>(E)) return;
4688
4689 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004690 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00004691
4692 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00004693 CC = E->getExprLoc();
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004694 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
4695 bool IsLogicalOperator = BO && BO->isLogicalOp();
4696 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor54042f12012-02-09 10:18:50 +00004697 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor503384f2012-02-09 00:47:04 +00004698 if (!ChildExpr)
4699 continue;
4700
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004701 if (IsLogicalOperator &&
4702 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
4703 // Ignore checking string literals that are in logical operators.
4704 continue;
4705 AnalyzeImplicitConversions(S, ChildExpr, CC);
4706 }
John McCall323ed742010-05-06 08:58:33 +00004707}
4708
4709} // end anonymous namespace
4710
4711/// Diagnoses "dangerous" implicit conversions within the given
4712/// expression (which is a full expression). Implements -Wconversion
4713/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00004714///
4715/// \param CC the "context" location of the implicit conversion, i.e.
4716/// the most location of the syntactic entity requiring the implicit
4717/// conversion
4718void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00004719 // Don't diagnose in unevaluated contexts.
David Blaikie71f55f72012-08-06 22:47:24 +00004720 if (isUnevaluatedContext())
John McCall323ed742010-05-06 08:58:33 +00004721 return;
4722
4723 // Don't diagnose for value- or type-dependent expressions.
4724 if (E->isTypeDependent() || E->isValueDependent())
4725 return;
4726
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004727 // Check for array bounds violations in cases where the check isn't triggered
4728 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
4729 // ArraySubscriptExpr is on the RHS of a variable initialization.
4730 CheckArrayAccess(E);
4731
John McCallb4eb64d2010-10-08 02:01:28 +00004732 // This is not the right CC for (e.g.) a variable initialization.
4733 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00004734}
4735
John McCall15d7d122010-11-11 03:21:53 +00004736void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
4737 FieldDecl *BitField,
4738 Expr *Init) {
4739 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
4740}
4741
Mike Stumpf8c49212010-01-21 03:59:47 +00004742/// CheckParmsForFunctionDef - Check that the parameters of the given
4743/// function are appropriate for the definition of a function. This
4744/// takes care of any checks that cannot be performed on the
4745/// declaration itself, e.g., that the types of each of the function
4746/// parameters are complete.
Douglas Gregor82aa7132010-11-01 18:37:59 +00004747bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
4748 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00004749 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00004750 for (; P != PEnd; ++P) {
4751 ParmVarDecl *Param = *P;
4752
Mike Stumpf8c49212010-01-21 03:59:47 +00004753 // C99 6.7.5.3p4: the parameters in a parameter type list in a
4754 // function declarator that is part of a function definition of
4755 // that function shall not have incomplete type.
4756 //
4757 // This is also C++ [dcl.fct]p6.
4758 if (!Param->isInvalidDecl() &&
4759 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00004760 diag::err_typecheck_decl_incomplete_type)) {
Mike Stumpf8c49212010-01-21 03:59:47 +00004761 Param->setInvalidDecl();
4762 HasInvalidParm = true;
4763 }
4764
4765 // C99 6.9.1p5: If the declarator includes a parameter type list, the
4766 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00004767 if (CheckParameterNames &&
4768 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00004769 !Param->isImplicit() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00004770 !getLangOpts().CPlusPlus)
Mike Stumpf8c49212010-01-21 03:59:47 +00004771 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00004772
4773 // C99 6.7.5.3p12:
4774 // If the function declarator is not part of a definition of that
4775 // function, parameters may have incomplete type and may use the [*]
4776 // notation in their sequences of declarator specifiers to specify
4777 // variable length array types.
4778 QualType PType = Param->getOriginalType();
4779 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
4780 if (AT->getSizeModifier() == ArrayType::Star) {
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00004781 // FIXME: This diagnosic should point the '[*]' if source-location
Sam Weinigd17e3402010-02-01 05:02:49 +00004782 // information is added for it.
4783 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
4784 }
4785 }
Mike Stumpf8c49212010-01-21 03:59:47 +00004786 }
4787
4788 return HasInvalidParm;
4789}
John McCallb7f4ffe2010-08-12 21:44:57 +00004790
4791/// CheckCastAlign - Implements -Wcast-align, which warns when a
4792/// pointer cast increases the alignment requirements.
4793void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
4794 // This is actually a lot of work to potentially be doing on every
4795 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00004796 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
4797 TRange.getBegin())
David Blaikied6471f72011-09-25 23:23:43 +00004798 == DiagnosticsEngine::Ignored)
John McCallb7f4ffe2010-08-12 21:44:57 +00004799 return;
4800
4801 // Ignore dependent types.
4802 if (T->isDependentType() || Op->getType()->isDependentType())
4803 return;
4804
4805 // Require that the destination be a pointer type.
4806 const PointerType *DestPtr = T->getAs<PointerType>();
4807 if (!DestPtr) return;
4808
4809 // If the destination has alignment 1, we're done.
4810 QualType DestPointee = DestPtr->getPointeeType();
4811 if (DestPointee->isIncompleteType()) return;
4812 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
4813 if (DestAlign.isOne()) return;
4814
4815 // Require that the source be a pointer type.
4816 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
4817 if (!SrcPtr) return;
4818 QualType SrcPointee = SrcPtr->getPointeeType();
4819
4820 // Whitelist casts from cv void*. We already implicitly
4821 // whitelisted casts to cv void*, since they have alignment 1.
4822 // Also whitelist casts involving incomplete types, which implicitly
4823 // includes 'void'.
4824 if (SrcPointee->isIncompleteType()) return;
4825
4826 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
4827 if (SrcAlign >= DestAlign) return;
4828
4829 Diag(TRange.getBegin(), diag::warn_cast_align)
4830 << Op->getType() << T
4831 << static_cast<unsigned>(SrcAlign.getQuantity())
4832 << static_cast<unsigned>(DestAlign.getQuantity())
4833 << TRange << Op->getSourceRange();
4834}
4835
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004836static const Type* getElementType(const Expr *BaseExpr) {
4837 const Type* EltType = BaseExpr->getType().getTypePtr();
4838 if (EltType->isAnyPointerType())
4839 return EltType->getPointeeType().getTypePtr();
4840 else if (EltType->isArrayType())
4841 return EltType->getBaseElementTypeUnsafe();
4842 return EltType;
4843}
4844
Chandler Carruthc2684342011-08-05 09:10:50 +00004845/// \brief Check whether this array fits the idiom of a size-one tail padded
4846/// array member of a struct.
4847///
4848/// We avoid emitting out-of-bounds access warnings for such arrays as they are
4849/// commonly used to emulate flexible arrays in C89 code.
4850static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
4851 const NamedDecl *ND) {
4852 if (Size != 1 || !ND) return false;
4853
4854 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
4855 if (!FD) return false;
4856
4857 // Don't consider sizes resulting from macro expansions or template argument
4858 // substitution to form C89 tail-padded arrays.
Sean Callanand2cf3482012-05-04 18:22:53 +00004859
4860 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00004861 while (TInfo) {
4862 TypeLoc TL = TInfo->getTypeLoc();
4863 // Look through typedefs.
4864 const TypedefTypeLoc *TTL = dyn_cast<TypedefTypeLoc>(&TL);
4865 if (TTL) {
4866 const TypedefNameDecl *TDL = TTL->getTypedefNameDecl();
4867 TInfo = TDL->getTypeSourceInfo();
4868 continue;
4869 }
4870 ConstantArrayTypeLoc CTL = cast<ConstantArrayTypeLoc>(TL);
4871 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Sean Callanand2cf3482012-05-04 18:22:53 +00004872 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
4873 return false;
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00004874 break;
Sean Callanand2cf3482012-05-04 18:22:53 +00004875 }
Chandler Carruthc2684342011-08-05 09:10:50 +00004876
4877 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gay381711c2011-11-29 22:43:53 +00004878 if (!RD) return false;
4879 if (RD->isUnion()) return false;
4880 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
4881 if (!CRD->isStandardLayout()) return false;
4882 }
Chandler Carruthc2684342011-08-05 09:10:50 +00004883
Benjamin Kramer22d4fed2011-08-06 03:04:42 +00004884 // See if this is the last field decl in the record.
4885 const Decl *D = FD;
4886 while ((D = D->getNextDeclInContext()))
4887 if (isa<FieldDecl>(D))
4888 return false;
4889 return true;
Chandler Carruthc2684342011-08-05 09:10:50 +00004890}
4891
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004892void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004893 const ArraySubscriptExpr *ASE,
Richard Smith25b009a2011-12-16 19:31:14 +00004894 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman92b670e2012-02-27 21:21:40 +00004895 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004896 if (IndexExpr->isValueDependent())
4897 return;
4898
Matt Beaumont-Gay8ef8f432011-12-12 22:35:02 +00004899 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004900 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00004901 const ConstantArrayType *ArrayTy =
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004902 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00004903 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00004904 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00004905
Chandler Carruth34064582011-02-17 20:55:08 +00004906 llvm::APSInt index;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004907 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00004908 return;
Richard Smith25b009a2011-12-16 19:31:14 +00004909 if (IndexNegated)
4910 index = -index;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00004911
Chandler Carruthba447122011-08-05 08:07:29 +00004912 const NamedDecl *ND = NULL;
Chandler Carruthba447122011-08-05 08:07:29 +00004913 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
4914 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruthc2684342011-08-05 09:10:50 +00004915 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruthba447122011-08-05 08:07:29 +00004916 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruthba447122011-08-05 08:07:29 +00004917
Ted Kremenek9e060ca2011-02-23 23:06:04 +00004918 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00004919 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00004920 if (!size.isStrictlyPositive())
4921 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004922
4923 const Type* BaseType = getElementType(BaseExpr);
Nico Weberde5998f2011-09-17 22:59:41 +00004924 if (BaseType != EffectiveType) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004925 // Make sure we're comparing apples to apples when comparing index to size
4926 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
4927 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhraind10f4bc2011-08-10 19:47:25 +00004928 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhrain18f16972011-08-10 18:49:28 +00004929 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004930 if (ptrarith_typesize != array_typesize) {
4931 // There's a cast to a different size type involved
4932 uint64_t ratio = array_typesize / ptrarith_typesize;
4933 // TODO: Be smarter about handling cases where array_typesize is not a
4934 // multiple of ptrarith_typesize
4935 if (ptrarith_typesize * ratio == array_typesize)
4936 size *= llvm::APInt(size.getBitWidth(), ratio);
4937 }
4938 }
4939
Chandler Carruth34064582011-02-17 20:55:08 +00004940 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00004941 index = index.zext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00004942 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00004943 size = size.zext(index.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00004944
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004945 // For array subscripting the index must be less than size, but for pointer
4946 // arithmetic also allow the index (offset) to be equal to size since
4947 // computing the next address after the end of the array is legal and
4948 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman92b670e2012-02-27 21:21:40 +00004949 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruthba447122011-08-05 08:07:29 +00004950 return;
4951
4952 // Also don't warn for arrays of size 1 which are members of some
4953 // structure. These are often used to approximate flexible arrays in C89
4954 // code.
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004955 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00004956 return;
Chandler Carruth34064582011-02-17 20:55:08 +00004957
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004958 // Suppress the warning if the subscript expression (as identified by the
4959 // ']' location) and the index expression are both from macro expansions
4960 // within a system header.
4961 if (ASE) {
4962 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
4963 ASE->getRBracketLoc());
4964 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
4965 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
4966 IndexExpr->getLocStart());
4967 if (SourceMgr.isFromSameFile(RBracketLoc, IndexLoc))
4968 return;
4969 }
4970 }
4971
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004972 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004973 if (ASE)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004974 DiagID = diag::warn_array_index_exceeds_bounds;
4975
4976 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
4977 PDiag(DiagID) << index.toString(10, true)
4978 << size.toString(10, true)
4979 << (unsigned)size.getLimitedValue(~0U)
4980 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00004981 } else {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004982 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004983 if (!ASE) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004984 DiagID = diag::warn_ptr_arith_precedes_bounds;
4985 if (index.isNegative()) index = -index;
4986 }
4987
4988 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
4989 PDiag(DiagID) << index.toString(10, true)
4990 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00004991 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00004992
Matt Beaumont-Gaycfbc5b52011-11-29 19:27:11 +00004993 if (!ND) {
4994 // Try harder to find a NamedDecl to point at in the note.
4995 while (const ArraySubscriptExpr *ASE =
4996 dyn_cast<ArraySubscriptExpr>(BaseExpr))
4997 BaseExpr = ASE->getBase()->IgnoreParenCasts();
4998 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
4999 ND = dyn_cast<NamedDecl>(DRE->getDecl());
5000 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
5001 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
5002 }
5003
Chandler Carruth35001ca2011-02-17 21:10:52 +00005004 if (ND)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005005 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
5006 PDiag(diag::note_array_index_out_of_bounds)
5007 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00005008}
5009
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005010void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005011 int AllowOnePastEnd = 0;
5012 while (expr) {
5013 expr = expr->IgnoreParenImpCasts();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005014 switch (expr->getStmtClass()) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005015 case Stmt::ArraySubscriptExprClass: {
5016 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005017 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005018 AllowOnePastEnd > 0);
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005019 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005020 }
5021 case Stmt::UnaryOperatorClass: {
5022 // Only unwrap the * and & unary operators
5023 const UnaryOperator *UO = cast<UnaryOperator>(expr);
5024 expr = UO->getSubExpr();
5025 switch (UO->getOpcode()) {
5026 case UO_AddrOf:
5027 AllowOnePastEnd++;
5028 break;
5029 case UO_Deref:
5030 AllowOnePastEnd--;
5031 break;
5032 default:
5033 return;
5034 }
5035 break;
5036 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005037 case Stmt::ConditionalOperatorClass: {
5038 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
5039 if (const Expr *lhs = cond->getLHS())
5040 CheckArrayAccess(lhs);
5041 if (const Expr *rhs = cond->getRHS())
5042 CheckArrayAccess(rhs);
5043 return;
5044 }
5045 default:
5046 return;
5047 }
Peter Collingbournef111d932011-04-15 00:35:48 +00005048 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005049}
John McCallf85e1932011-06-15 23:02:42 +00005050
5051//===--- CHECK: Objective-C retain cycles ----------------------------------//
5052
5053namespace {
5054 struct RetainCycleOwner {
5055 RetainCycleOwner() : Variable(0), Indirect(false) {}
5056 VarDecl *Variable;
5057 SourceRange Range;
5058 SourceLocation Loc;
5059 bool Indirect;
5060
5061 void setLocsFrom(Expr *e) {
5062 Loc = e->getExprLoc();
5063 Range = e->getSourceRange();
5064 }
5065 };
5066}
5067
5068/// Consider whether capturing the given variable can possibly lead to
5069/// a retain cycle.
5070static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
5071 // In ARC, it's captured strongly iff the variable has __strong
5072 // lifetime. In MRR, it's captured strongly if the variable is
5073 // __block and has an appropriate type.
5074 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
5075 return false;
5076
5077 owner.Variable = var;
5078 owner.setLocsFrom(ref);
5079 return true;
5080}
5081
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00005082static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCallf85e1932011-06-15 23:02:42 +00005083 while (true) {
5084 e = e->IgnoreParens();
5085 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
5086 switch (cast->getCastKind()) {
5087 case CK_BitCast:
5088 case CK_LValueBitCast:
5089 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00005090 case CK_ARCReclaimReturnedObject:
John McCallf85e1932011-06-15 23:02:42 +00005091 e = cast->getSubExpr();
5092 continue;
5093
John McCallf85e1932011-06-15 23:02:42 +00005094 default:
5095 return false;
5096 }
5097 }
5098
5099 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
5100 ObjCIvarDecl *ivar = ref->getDecl();
5101 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
5102 return false;
5103
5104 // Try to find a retain cycle in the base.
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00005105 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCallf85e1932011-06-15 23:02:42 +00005106 return false;
5107
5108 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
5109 owner.Indirect = true;
5110 return true;
5111 }
5112
5113 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
5114 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
5115 if (!var) return false;
5116 return considerVariable(var, ref, owner);
5117 }
5118
John McCallf85e1932011-06-15 23:02:42 +00005119 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
5120 if (member->isArrow()) return false;
5121
5122 // Don't count this as an indirect ownership.
5123 e = member->getBase();
5124 continue;
5125 }
5126
John McCall4b9c2d22011-11-06 09:01:30 +00005127 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
5128 // Only pay attention to pseudo-objects on property references.
5129 ObjCPropertyRefExpr *pre
5130 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
5131 ->IgnoreParens());
5132 if (!pre) return false;
5133 if (pre->isImplicitProperty()) return false;
5134 ObjCPropertyDecl *property = pre->getExplicitProperty();
5135 if (!property->isRetaining() &&
5136 !(property->getPropertyIvarDecl() &&
5137 property->getPropertyIvarDecl()->getType()
5138 .getObjCLifetime() == Qualifiers::OCL_Strong))
5139 return false;
5140
5141 owner.Indirect = true;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00005142 if (pre->isSuperReceiver()) {
5143 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
5144 if (!owner.Variable)
5145 return false;
5146 owner.Loc = pre->getLocation();
5147 owner.Range = pre->getSourceRange();
5148 return true;
5149 }
John McCall4b9c2d22011-11-06 09:01:30 +00005150 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
5151 ->getSourceExpr());
5152 continue;
5153 }
5154
John McCallf85e1932011-06-15 23:02:42 +00005155 // Array ivars?
5156
5157 return false;
5158 }
5159}
5160
5161namespace {
5162 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
5163 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
5164 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
5165 Variable(variable), Capturer(0) {}
5166
5167 VarDecl *Variable;
5168 Expr *Capturer;
5169
5170 void VisitDeclRefExpr(DeclRefExpr *ref) {
5171 if (ref->getDecl() == Variable && !Capturer)
5172 Capturer = ref;
5173 }
5174
John McCallf85e1932011-06-15 23:02:42 +00005175 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
5176 if (Capturer) return;
5177 Visit(ref->getBase());
5178 if (Capturer && ref->isFreeIvar())
5179 Capturer = ref;
5180 }
5181
5182 void VisitBlockExpr(BlockExpr *block) {
5183 // Look inside nested blocks
5184 if (block->getBlockDecl()->capturesVariable(Variable))
5185 Visit(block->getBlockDecl()->getBody());
5186 }
5187 };
5188}
5189
5190/// Check whether the given argument is a block which captures a
5191/// variable.
5192static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
5193 assert(owner.Variable && owner.Loc.isValid());
5194
5195 e = e->IgnoreParenCasts();
5196 BlockExpr *block = dyn_cast<BlockExpr>(e);
5197 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
5198 return 0;
5199
5200 FindCaptureVisitor visitor(S.Context, owner.Variable);
5201 visitor.Visit(block->getBlockDecl()->getBody());
5202 return visitor.Capturer;
5203}
5204
5205static void diagnoseRetainCycle(Sema &S, Expr *capturer,
5206 RetainCycleOwner &owner) {
5207 assert(capturer);
5208 assert(owner.Variable && owner.Loc.isValid());
5209
5210 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
5211 << owner.Variable << capturer->getSourceRange();
5212 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
5213 << owner.Indirect << owner.Range;
5214}
5215
5216/// Check for a keyword selector that starts with the word 'add' or
5217/// 'set'.
5218static bool isSetterLikeSelector(Selector sel) {
5219 if (sel.isUnarySelector()) return false;
5220
Chris Lattner5f9e2722011-07-23 10:55:15 +00005221 StringRef str = sel.getNameForSlot(0);
John McCallf85e1932011-06-15 23:02:42 +00005222 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00005223 if (str.startswith("set"))
John McCallf85e1932011-06-15 23:02:42 +00005224 str = str.substr(3);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00005225 else if (str.startswith("add")) {
5226 // Specially whitelist 'addOperationWithBlock:'.
5227 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
5228 return false;
5229 str = str.substr(3);
5230 }
John McCallf85e1932011-06-15 23:02:42 +00005231 else
5232 return false;
5233
5234 if (str.empty()) return true;
5235 return !islower(str.front());
5236}
5237
5238/// Check a message send to see if it's likely to cause a retain cycle.
5239void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
5240 // Only check instance methods whose selector looks like a setter.
5241 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
5242 return;
5243
5244 // Try to find a variable that the receiver is strongly owned by.
5245 RetainCycleOwner owner;
5246 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00005247 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCallf85e1932011-06-15 23:02:42 +00005248 return;
5249 } else {
5250 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
5251 owner.Variable = getCurMethodDecl()->getSelfDecl();
5252 owner.Loc = msg->getSuperLoc();
5253 owner.Range = msg->getSuperLoc();
5254 }
5255
5256 // Check whether the receiver is captured by any of the arguments.
5257 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
5258 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
5259 return diagnoseRetainCycle(*this, capturer, owner);
5260}
5261
5262/// Check a property assign to see if it's likely to cause a retain cycle.
5263void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
5264 RetainCycleOwner owner;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00005265 if (!findRetainCycleOwner(*this, receiver, owner))
John McCallf85e1932011-06-15 23:02:42 +00005266 return;
5267
5268 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
5269 diagnoseRetainCycle(*this, capturer, owner);
5270}
5271
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005272bool Sema::checkUnsafeAssigns(SourceLocation Loc,
John McCallf85e1932011-06-15 23:02:42 +00005273 QualType LHS, Expr *RHS) {
5274 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
5275 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005276 return false;
5277 // strip off any implicit cast added to get to the one arc-specific
5278 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00005279 if (cast->getCastKind() == CK_ARCConsumeObject) {
John McCallf85e1932011-06-15 23:02:42 +00005280 Diag(Loc, diag::warn_arc_retained_assign)
Fariborz Jahanianbd2e27e2012-07-06 21:09:27 +00005281 << (LT == Qualifiers::OCL_ExplicitNone) << 1
John McCallf85e1932011-06-15 23:02:42 +00005282 << RHS->getSourceRange();
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005283 return true;
5284 }
5285 RHS = cast->getSubExpr();
5286 }
5287 return false;
John McCallf85e1932011-06-15 23:02:42 +00005288}
5289
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005290void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
5291 Expr *LHS, Expr *RHS) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00005292 QualType LHSType;
5293 // PropertyRef on LHS type need be directly obtained from
5294 // its declaration as it has a PsuedoType.
5295 ObjCPropertyRefExpr *PRE
5296 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
5297 if (PRE && !PRE->isImplicitProperty()) {
5298 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
5299 if (PD)
5300 LHSType = PD->getType();
5301 }
5302
5303 if (LHSType.isNull())
5304 LHSType = LHS->getType();
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005305 if (checkUnsafeAssigns(Loc, LHSType, RHS))
5306 return;
5307 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
5308 // FIXME. Check for other life times.
5309 if (LT != Qualifiers::OCL_None)
5310 return;
5311
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00005312 if (PRE) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005313 if (PRE->isImplicitProperty())
5314 return;
5315 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
5316 if (!PD)
5317 return;
5318
5319 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00005320 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
5321 // when 'assign' attribute was not explicitly specified
5322 // by user, ignore it and rely on property type itself
5323 // for lifetime info.
5324 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
5325 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
5326 LHSType->isObjCRetainableType())
5327 return;
5328
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005329 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00005330 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005331 Diag(Loc, diag::warn_arc_retained_property_assign)
5332 << RHS->getSourceRange();
5333 return;
5334 }
5335 RHS = cast->getSubExpr();
5336 }
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00005337 }
Fariborz Jahanianbd2e27e2012-07-06 21:09:27 +00005338 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
5339 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
5340 if (cast->getCastKind() == CK_ARCConsumeObject) {
5341 Diag(Loc, diag::warn_arc_retained_assign)
5342 << 0 << 0<< RHS->getSourceRange();
5343 return;
5344 }
5345 RHS = cast->getSubExpr();
5346 }
5347 }
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005348 }
5349}
Dmitri Gribenko625bb562012-02-14 22:14:32 +00005350
5351//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
5352
5353namespace {
5354bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
5355 SourceLocation StmtLoc,
5356 const NullStmt *Body) {
5357 // Do not warn if the body is a macro that expands to nothing, e.g:
5358 //
5359 // #define CALL(x)
5360 // if (condition)
5361 // CALL(0);
5362 //
5363 if (Body->hasLeadingEmptyMacro())
5364 return false;
5365
5366 // Get line numbers of statement and body.
5367 bool StmtLineInvalid;
5368 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
5369 &StmtLineInvalid);
5370 if (StmtLineInvalid)
5371 return false;
5372
5373 bool BodyLineInvalid;
5374 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
5375 &BodyLineInvalid);
5376 if (BodyLineInvalid)
5377 return false;
5378
5379 // Warn if null statement and body are on the same line.
5380 if (StmtLine != BodyLine)
5381 return false;
5382
5383 return true;
5384}
5385} // Unnamed namespace
5386
5387void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
5388 const Stmt *Body,
5389 unsigned DiagID) {
5390 // Since this is a syntactic check, don't emit diagnostic for template
5391 // instantiations, this just adds noise.
5392 if (CurrentInstantiationScope)
5393 return;
5394
5395 // The body should be a null statement.
5396 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
5397 if (!NBody)
5398 return;
5399
5400 // Do the usual checks.
5401 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
5402 return;
5403
5404 Diag(NBody->getSemiLoc(), DiagID);
5405 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
5406}
5407
5408void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
5409 const Stmt *PossibleBody) {
5410 assert(!CurrentInstantiationScope); // Ensured by caller
5411
5412 SourceLocation StmtLoc;
5413 const Stmt *Body;
5414 unsigned DiagID;
5415 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
5416 StmtLoc = FS->getRParenLoc();
5417 Body = FS->getBody();
5418 DiagID = diag::warn_empty_for_body;
5419 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
5420 StmtLoc = WS->getCond()->getSourceRange().getEnd();
5421 Body = WS->getBody();
5422 DiagID = diag::warn_empty_while_body;
5423 } else
5424 return; // Neither `for' nor `while'.
5425
5426 // The body should be a null statement.
5427 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
5428 if (!NBody)
5429 return;
5430
5431 // Skip expensive checks if diagnostic is disabled.
5432 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
5433 DiagnosticsEngine::Ignored)
5434 return;
5435
5436 // Do the usual checks.
5437 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
5438 return;
5439
5440 // `for(...);' and `while(...);' are popular idioms, so in order to keep
5441 // noise level low, emit diagnostics only if for/while is followed by a
5442 // CompoundStmt, e.g.:
5443 // for (int i = 0; i < n; i++);
5444 // {
5445 // a(i);
5446 // }
5447 // or if for/while is followed by a statement with more indentation
5448 // than for/while itself:
5449 // for (int i = 0; i < n; i++);
5450 // a(i);
5451 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
5452 if (!ProbableTypo) {
5453 bool BodyColInvalid;
5454 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
5455 PossibleBody->getLocStart(),
5456 &BodyColInvalid);
5457 if (BodyColInvalid)
5458 return;
5459
5460 bool StmtColInvalid;
5461 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
5462 S->getLocStart(),
5463 &StmtColInvalid);
5464 if (StmtColInvalid)
5465 return;
5466
5467 if (BodyCol > StmtCol)
5468 ProbableTypo = true;
5469 }
5470
5471 if (ProbableTypo) {
5472 Diag(NBody->getSemiLoc(), DiagID);
5473 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
5474 }
5475}
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00005476
5477//===--- Layout compatibility ----------------------------------------------//
5478
5479namespace {
5480
5481bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
5482
5483/// \brief Check if two enumeration types are layout-compatible.
5484bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
5485 // C++11 [dcl.enum] p8:
5486 // Two enumeration types are layout-compatible if they have the same
5487 // underlying type.
5488 return ED1->isComplete() && ED2->isComplete() &&
5489 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
5490}
5491
5492/// \brief Check if two fields are layout-compatible.
5493bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
5494 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
5495 return false;
5496
5497 if (Field1->isBitField() != Field2->isBitField())
5498 return false;
5499
5500 if (Field1->isBitField()) {
5501 // Make sure that the bit-fields are the same length.
5502 unsigned Bits1 = Field1->getBitWidthValue(C);
5503 unsigned Bits2 = Field2->getBitWidthValue(C);
5504
5505 if (Bits1 != Bits2)
5506 return false;
5507 }
5508
5509 return true;
5510}
5511
5512/// \brief Check if two standard-layout structs are layout-compatible.
5513/// (C++11 [class.mem] p17)
5514bool isLayoutCompatibleStruct(ASTContext &C,
5515 RecordDecl *RD1,
5516 RecordDecl *RD2) {
5517 // If both records are C++ classes, check that base classes match.
5518 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
5519 // If one of records is a CXXRecordDecl we are in C++ mode,
5520 // thus the other one is a CXXRecordDecl, too.
5521 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
5522 // Check number of base classes.
5523 if (D1CXX->getNumBases() != D2CXX->getNumBases())
5524 return false;
5525
5526 // Check the base classes.
5527 for (CXXRecordDecl::base_class_const_iterator
5528 Base1 = D1CXX->bases_begin(),
5529 BaseEnd1 = D1CXX->bases_end(),
5530 Base2 = D2CXX->bases_begin();
5531 Base1 != BaseEnd1;
5532 ++Base1, ++Base2) {
5533 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
5534 return false;
5535 }
5536 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
5537 // If only RD2 is a C++ class, it should have zero base classes.
5538 if (D2CXX->getNumBases() > 0)
5539 return false;
5540 }
5541
5542 // Check the fields.
5543 RecordDecl::field_iterator Field2 = RD2->field_begin(),
5544 Field2End = RD2->field_end(),
5545 Field1 = RD1->field_begin(),
5546 Field1End = RD1->field_end();
5547 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
5548 if (!isLayoutCompatible(C, *Field1, *Field2))
5549 return false;
5550 }
5551 if (Field1 != Field1End || Field2 != Field2End)
5552 return false;
5553
5554 return true;
5555}
5556
5557/// \brief Check if two standard-layout unions are layout-compatible.
5558/// (C++11 [class.mem] p18)
5559bool isLayoutCompatibleUnion(ASTContext &C,
5560 RecordDecl *RD1,
5561 RecordDecl *RD2) {
5562 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
5563 for (RecordDecl::field_iterator Field2 = RD2->field_begin(),
5564 Field2End = RD2->field_end();
5565 Field2 != Field2End; ++Field2) {
5566 UnmatchedFields.insert(*Field2);
5567 }
5568
5569 for (RecordDecl::field_iterator Field1 = RD1->field_begin(),
5570 Field1End = RD1->field_end();
5571 Field1 != Field1End; ++Field1) {
5572 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
5573 I = UnmatchedFields.begin(),
5574 E = UnmatchedFields.end();
5575
5576 for ( ; I != E; ++I) {
5577 if (isLayoutCompatible(C, *Field1, *I)) {
5578 bool Result = UnmatchedFields.erase(*I);
5579 (void) Result;
5580 assert(Result);
5581 break;
5582 }
5583 }
5584 if (I == E)
5585 return false;
5586 }
5587
5588 return UnmatchedFields.empty();
5589}
5590
5591bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
5592 if (RD1->isUnion() != RD2->isUnion())
5593 return false;
5594
5595 if (RD1->isUnion())
5596 return isLayoutCompatibleUnion(C, RD1, RD2);
5597 else
5598 return isLayoutCompatibleStruct(C, RD1, RD2);
5599}
5600
5601/// \brief Check if two types are layout-compatible in C++11 sense.
5602bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
5603 if (T1.isNull() || T2.isNull())
5604 return false;
5605
5606 // C++11 [basic.types] p11:
5607 // If two types T1 and T2 are the same type, then T1 and T2 are
5608 // layout-compatible types.
5609 if (C.hasSameType(T1, T2))
5610 return true;
5611
5612 T1 = T1.getCanonicalType().getUnqualifiedType();
5613 T2 = T2.getCanonicalType().getUnqualifiedType();
5614
5615 const Type::TypeClass TC1 = T1->getTypeClass();
5616 const Type::TypeClass TC2 = T2->getTypeClass();
5617
5618 if (TC1 != TC2)
5619 return false;
5620
5621 if (TC1 == Type::Enum) {
5622 return isLayoutCompatible(C,
5623 cast<EnumType>(T1)->getDecl(),
5624 cast<EnumType>(T2)->getDecl());
5625 } else if (TC1 == Type::Record) {
5626 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
5627 return false;
5628
5629 return isLayoutCompatible(C,
5630 cast<RecordType>(T1)->getDecl(),
5631 cast<RecordType>(T2)->getDecl());
5632 }
5633
5634 return false;
5635}
5636}
5637
5638//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
5639
5640namespace {
5641/// \brief Given a type tag expression find the type tag itself.
5642///
5643/// \param TypeExpr Type tag expression, as it appears in user's code.
5644///
5645/// \param VD Declaration of an identifier that appears in a type tag.
5646///
5647/// \param MagicValue Type tag magic value.
5648bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
5649 const ValueDecl **VD, uint64_t *MagicValue) {
5650 while(true) {
5651 if (!TypeExpr)
5652 return false;
5653
5654 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
5655
5656 switch (TypeExpr->getStmtClass()) {
5657 case Stmt::UnaryOperatorClass: {
5658 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
5659 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
5660 TypeExpr = UO->getSubExpr();
5661 continue;
5662 }
5663 return false;
5664 }
5665
5666 case Stmt::DeclRefExprClass: {
5667 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
5668 *VD = DRE->getDecl();
5669 return true;
5670 }
5671
5672 case Stmt::IntegerLiteralClass: {
5673 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
5674 llvm::APInt MagicValueAPInt = IL->getValue();
5675 if (MagicValueAPInt.getActiveBits() <= 64) {
5676 *MagicValue = MagicValueAPInt.getZExtValue();
5677 return true;
5678 } else
5679 return false;
5680 }
5681
5682 case Stmt::BinaryConditionalOperatorClass:
5683 case Stmt::ConditionalOperatorClass: {
5684 const AbstractConditionalOperator *ACO =
5685 cast<AbstractConditionalOperator>(TypeExpr);
5686 bool Result;
5687 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
5688 if (Result)
5689 TypeExpr = ACO->getTrueExpr();
5690 else
5691 TypeExpr = ACO->getFalseExpr();
5692 continue;
5693 }
5694 return false;
5695 }
5696
5697 case Stmt::BinaryOperatorClass: {
5698 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
5699 if (BO->getOpcode() == BO_Comma) {
5700 TypeExpr = BO->getRHS();
5701 continue;
5702 }
5703 return false;
5704 }
5705
5706 default:
5707 return false;
5708 }
5709 }
5710}
5711
5712/// \brief Retrieve the C type corresponding to type tag TypeExpr.
5713///
5714/// \param TypeExpr Expression that specifies a type tag.
5715///
5716/// \param MagicValues Registered magic values.
5717///
5718/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
5719/// kind.
5720///
5721/// \param TypeInfo Information about the corresponding C type.
5722///
5723/// \returns true if the corresponding C type was found.
5724bool GetMatchingCType(
5725 const IdentifierInfo *ArgumentKind,
5726 const Expr *TypeExpr, const ASTContext &Ctx,
5727 const llvm::DenseMap<Sema::TypeTagMagicValue,
5728 Sema::TypeTagData> *MagicValues,
5729 bool &FoundWrongKind,
5730 Sema::TypeTagData &TypeInfo) {
5731 FoundWrongKind = false;
5732
5733 // Variable declaration that has type_tag_for_datatype attribute.
5734 const ValueDecl *VD = NULL;
5735
5736 uint64_t MagicValue;
5737
5738 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
5739 return false;
5740
5741 if (VD) {
5742 for (specific_attr_iterator<TypeTagForDatatypeAttr>
5743 I = VD->specific_attr_begin<TypeTagForDatatypeAttr>(),
5744 E = VD->specific_attr_end<TypeTagForDatatypeAttr>();
5745 I != E; ++I) {
5746 if (I->getArgumentKind() != ArgumentKind) {
5747 FoundWrongKind = true;
5748 return false;
5749 }
5750 TypeInfo.Type = I->getMatchingCType();
5751 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
5752 TypeInfo.MustBeNull = I->getMustBeNull();
5753 return true;
5754 }
5755 return false;
5756 }
5757
5758 if (!MagicValues)
5759 return false;
5760
5761 llvm::DenseMap<Sema::TypeTagMagicValue,
5762 Sema::TypeTagData>::const_iterator I =
5763 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
5764 if (I == MagicValues->end())
5765 return false;
5766
5767 TypeInfo = I->second;
5768 return true;
5769}
5770} // unnamed namespace
5771
5772void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
5773 uint64_t MagicValue, QualType Type,
5774 bool LayoutCompatible,
5775 bool MustBeNull) {
5776 if (!TypeTagForDatatypeMagicValues)
5777 TypeTagForDatatypeMagicValues.reset(
5778 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
5779
5780 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
5781 (*TypeTagForDatatypeMagicValues)[Magic] =
5782 TypeTagData(Type, LayoutCompatible, MustBeNull);
5783}
5784
5785namespace {
5786bool IsSameCharType(QualType T1, QualType T2) {
5787 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
5788 if (!BT1)
5789 return false;
5790
5791 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
5792 if (!BT2)
5793 return false;
5794
5795 BuiltinType::Kind T1Kind = BT1->getKind();
5796 BuiltinType::Kind T2Kind = BT2->getKind();
5797
5798 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
5799 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
5800 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
5801 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
5802}
5803} // unnamed namespace
5804
5805void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
5806 const Expr * const *ExprArgs) {
5807 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
5808 bool IsPointerAttr = Attr->getIsPointer();
5809
5810 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
5811 bool FoundWrongKind;
5812 TypeTagData TypeInfo;
5813 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
5814 TypeTagForDatatypeMagicValues.get(),
5815 FoundWrongKind, TypeInfo)) {
5816 if (FoundWrongKind)
5817 Diag(TypeTagExpr->getExprLoc(),
5818 diag::warn_type_tag_for_datatype_wrong_kind)
5819 << TypeTagExpr->getSourceRange();
5820 return;
5821 }
5822
5823 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
5824 if (IsPointerAttr) {
5825 // Skip implicit cast of pointer to `void *' (as a function argument).
5826 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
5827 if (ICE->getType()->isVoidPointerType())
5828 ArgumentExpr = ICE->getSubExpr();
5829 }
5830 QualType ArgumentType = ArgumentExpr->getType();
5831
5832 // Passing a `void*' pointer shouldn't trigger a warning.
5833 if (IsPointerAttr && ArgumentType->isVoidPointerType())
5834 return;
5835
5836 if (TypeInfo.MustBeNull) {
5837 // Type tag with matching void type requires a null pointer.
5838 if (!ArgumentExpr->isNullPointerConstant(Context,
5839 Expr::NPC_ValueDependentIsNotNull)) {
5840 Diag(ArgumentExpr->getExprLoc(),
5841 diag::warn_type_safety_null_pointer_required)
5842 << ArgumentKind->getName()
5843 << ArgumentExpr->getSourceRange()
5844 << TypeTagExpr->getSourceRange();
5845 }
5846 return;
5847 }
5848
5849 QualType RequiredType = TypeInfo.Type;
5850 if (IsPointerAttr)
5851 RequiredType = Context.getPointerType(RequiredType);
5852
5853 bool mismatch = false;
5854 if (!TypeInfo.LayoutCompatible) {
5855 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
5856
5857 // C++11 [basic.fundamental] p1:
5858 // Plain char, signed char, and unsigned char are three distinct types.
5859 //
5860 // But we treat plain `char' as equivalent to `signed char' or `unsigned
5861 // char' depending on the current char signedness mode.
5862 if (mismatch)
5863 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
5864 RequiredType->getPointeeType())) ||
5865 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
5866 mismatch = false;
5867 } else
5868 if (IsPointerAttr)
5869 mismatch = !isLayoutCompatible(Context,
5870 ArgumentType->getPointeeType(),
5871 RequiredType->getPointeeType());
5872 else
5873 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
5874
5875 if (mismatch)
5876 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
5877 << ArgumentType << ArgumentKind->getName()
5878 << TypeInfo.LayoutCompatible << RequiredType
5879 << ArgumentExpr->getSourceRange()
5880 << TypeTagExpr->getSourceRange();
5881}
5882