blob: 63c7bdd0cb301715a4acfacd0a4f8270075ae246 [file] [log] [blame]
Chris Lattner59907c42007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner59907c42007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
Mike Stump1eb44332009-09-09 15:08:12 +000010// This file implements extra semantic analysis beyond what is enforced
Chris Lattner59907c42007-08-10 20:18:51 +000011// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
John McCall5f8d6042011-08-27 01:09:30 +000015#include "clang/Sema/Initialization.h"
Douglas Gregore737f502010-08-12 20:07:10 +000016#include "clang/Sema/Sema.h"
John McCall2d887082010-08-25 22:03:47 +000017#include "clang/Sema/SemaInternal.h"
Eli Friedman276b0612011-10-11 02:20:01 +000018#include "clang/Sema/Initialization.h"
Richard Smith831421f2012-06-25 20:30:08 +000019#include "clang/Sema/Lookup.h"
John McCall781472f2010-08-25 08:40:02 +000020#include "clang/Sema/ScopeInfo.h"
Ted Kremenek826a3452010-07-16 02:11:22 +000021#include "clang/Analysis/Analyses/FormatString.h"
Chris Lattner59907c42007-08-10 20:18:51 +000022#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000023#include "clang/AST/CharUnits.h"
John McCall384aff82010-08-25 07:42:41 +000024#include "clang/AST/DeclCXX.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000025#include "clang/AST/DeclObjC.h"
David Blaikiebe0ee872012-05-15 16:56:36 +000026#include "clang/AST/Expr.h"
Ted Kremenek23245122007-08-20 16:18:38 +000027#include "clang/AST/ExprCXX.h"
Ted Kremenek7ff22b22008-06-16 18:00:42 +000028#include "clang/AST/ExprObjC.h"
John McCallf85e1932011-06-15 23:02:42 +000029#include "clang/AST/EvaluatedExprVisitor.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000030#include "clang/AST/DeclObjC.h"
31#include "clang/AST/StmtCXX.h"
32#include "clang/AST/StmtObjC.h"
Chris Lattner59907c42007-08-10 20:18:51 +000033#include "clang/Lex/Preprocessor.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000034#include "llvm/ADT/BitVector.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000035#include "llvm/ADT/SmallString.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000036#include "llvm/ADT/STLExtras.h"
Tom Care3bfc5f42010-06-09 04:11:11 +000037#include "llvm/Support/raw_ostream.h"
Eric Christopher691ebc32010-04-17 02:26:23 +000038#include "clang/Basic/TargetBuiltins.h"
Nate Begeman26a31422010-06-08 02:47:44 +000039#include "clang/Basic/TargetInfo.h"
Fariborz Jahanian7da71022010-09-07 19:38:13 +000040#include "clang/Basic/ConvertUTF.h"
Zhongxing Xua1f3dba2009-05-20 01:55:10 +000041#include <limits>
Chris Lattner59907c42007-08-10 20:18:51 +000042using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000043using namespace sema;
Chris Lattner59907c42007-08-10 20:18:51 +000044
Chris Lattner60800082009-02-18 17:49:48 +000045SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
46 unsigned ByteNo) const {
Chris Lattner08f92e32010-11-17 07:37:15 +000047 return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +000048 PP.getLangOpts(), PP.getTargetInfo());
Chris Lattner60800082009-02-18 17:49:48 +000049}
50
John McCall8e10f3b2011-02-26 05:39:39 +000051/// Checks that a call expression's argument count is the desired number.
52/// This is useful when doing custom type-checking. Returns true on error.
53static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
54 unsigned argCount = call->getNumArgs();
55 if (argCount == desiredArgCount) return false;
56
57 if (argCount < desiredArgCount)
58 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
59 << 0 /*function call*/ << desiredArgCount << argCount
60 << call->getSourceRange();
61
62 // Highlight all the excess arguments.
63 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
64 call->getArg(argCount - 1)->getLocEnd());
65
66 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
67 << 0 /*function call*/ << desiredArgCount << argCount
68 << call->getArg(1)->getSourceRange();
69}
70
Julien Lerougee5939212012-04-28 17:39:16 +000071/// Check that the first argument to __builtin_annotation is an integer
72/// and the second argument is a non-wide string literal.
73static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
74 if (checkArgCount(S, TheCall, 2))
75 return true;
76
77 // First argument should be an integer.
78 Expr *ValArg = TheCall->getArg(0);
79 QualType Ty = ValArg->getType();
80 if (!Ty->isIntegerType()) {
81 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
82 << ValArg->getSourceRange();
Julien Lerouge77f68bb2011-09-09 22:41:49 +000083 return true;
84 }
Julien Lerougee5939212012-04-28 17:39:16 +000085
86 // Second argument should be a constant string.
87 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
88 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
89 if (!Literal || !Literal->isAscii()) {
90 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
91 << StrArg->getSourceRange();
92 return true;
93 }
94
95 TheCall->setType(Ty);
Julien Lerouge77f68bb2011-09-09 22:41:49 +000096 return false;
97}
98
John McCall60d7b3a2010-08-24 06:29:42 +000099ExprResult
Anders Carlssond406bf02009-08-16 01:56:34 +0000100Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
John McCall60d7b3a2010-08-24 06:29:42 +0000101 ExprResult TheCallResult(Owned(TheCall));
Douglas Gregor2def4832008-11-17 20:34:05 +0000102
Chris Lattner946928f2010-10-01 23:23:24 +0000103 // Find out if any arguments are required to be integer constant expressions.
104 unsigned ICEArguments = 0;
105 ASTContext::GetBuiltinTypeError Error;
106 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
107 if (Error != ASTContext::GE_None)
108 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
109
110 // If any arguments are required to be ICE's, check and diagnose.
111 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
112 // Skip arguments not required to be ICE's.
113 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
114
115 llvm::APSInt Result;
116 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
117 return true;
118 ICEArguments &= ~(1 << ArgNo);
119 }
120
Anders Carlssond406bf02009-08-16 01:56:34 +0000121 switch (BuiltinID) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000122 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000123 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000124 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000125 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000126 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000127 break;
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000128 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000129 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000130 if (SemaBuiltinVAStart(TheCall))
131 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000132 break;
Chris Lattner1b9a0792007-12-20 00:26:33 +0000133 case Builtin::BI__builtin_isgreater:
134 case Builtin::BI__builtin_isgreaterequal:
135 case Builtin::BI__builtin_isless:
136 case Builtin::BI__builtin_islessequal:
137 case Builtin::BI__builtin_islessgreater:
138 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000139 if (SemaBuiltinUnorderedCompare(TheCall))
140 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000141 break;
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000142 case Builtin::BI__builtin_fpclassify:
143 if (SemaBuiltinFPClassification(TheCall, 6))
144 return ExprError();
145 break;
Eli Friedman9ac6f622009-08-31 20:06:00 +0000146 case Builtin::BI__builtin_isfinite:
147 case Builtin::BI__builtin_isinf:
148 case Builtin::BI__builtin_isinf_sign:
149 case Builtin::BI__builtin_isnan:
150 case Builtin::BI__builtin_isnormal:
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000151 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman9ac6f622009-08-31 20:06:00 +0000152 return ExprError();
153 break;
Eli Friedmand38617c2008-05-14 19:38:39 +0000154 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000155 return SemaBuiltinShuffleVector(TheCall);
156 // TheCall will be freed by the smart pointer here, but that's fine, since
157 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000158 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000159 if (SemaBuiltinPrefetch(TheCall))
160 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000161 break;
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000162 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000163 if (SemaBuiltinObjectSize(TheCall))
164 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000165 break;
Eli Friedmand875fed2009-05-03 04:46:36 +0000166 case Builtin::BI__builtin_longjmp:
167 if (SemaBuiltinLongjmp(TheCall))
168 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000169 break;
John McCall8e10f3b2011-02-26 05:39:39 +0000170
171 case Builtin::BI__builtin_classify_type:
172 if (checkArgCount(*this, TheCall, 1)) return true;
173 TheCall->setType(Context.IntTy);
174 break;
Chris Lattner75c29a02010-10-12 17:47:42 +0000175 case Builtin::BI__builtin_constant_p:
John McCall8e10f3b2011-02-26 05:39:39 +0000176 if (checkArgCount(*this, TheCall, 1)) return true;
177 TheCall->setType(Context.IntTy);
Chris Lattner75c29a02010-10-12 17:47:42 +0000178 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000179 case Builtin::BI__sync_fetch_and_add:
Douglas Gregora9766412011-11-28 16:30:08 +0000180 case Builtin::BI__sync_fetch_and_add_1:
181 case Builtin::BI__sync_fetch_and_add_2:
182 case Builtin::BI__sync_fetch_and_add_4:
183 case Builtin::BI__sync_fetch_and_add_8:
184 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000185 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregora9766412011-11-28 16:30:08 +0000186 case Builtin::BI__sync_fetch_and_sub_1:
187 case Builtin::BI__sync_fetch_and_sub_2:
188 case Builtin::BI__sync_fetch_and_sub_4:
189 case Builtin::BI__sync_fetch_and_sub_8:
190 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000191 case Builtin::BI__sync_fetch_and_or:
Douglas Gregora9766412011-11-28 16:30:08 +0000192 case Builtin::BI__sync_fetch_and_or_1:
193 case Builtin::BI__sync_fetch_and_or_2:
194 case Builtin::BI__sync_fetch_and_or_4:
195 case Builtin::BI__sync_fetch_and_or_8:
196 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000197 case Builtin::BI__sync_fetch_and_and:
Douglas Gregora9766412011-11-28 16:30:08 +0000198 case Builtin::BI__sync_fetch_and_and_1:
199 case Builtin::BI__sync_fetch_and_and_2:
200 case Builtin::BI__sync_fetch_and_and_4:
201 case Builtin::BI__sync_fetch_and_and_8:
202 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000203 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregora9766412011-11-28 16:30:08 +0000204 case Builtin::BI__sync_fetch_and_xor_1:
205 case Builtin::BI__sync_fetch_and_xor_2:
206 case Builtin::BI__sync_fetch_and_xor_4:
207 case Builtin::BI__sync_fetch_and_xor_8:
208 case Builtin::BI__sync_fetch_and_xor_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000209 case Builtin::BI__sync_add_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000210 case Builtin::BI__sync_add_and_fetch_1:
211 case Builtin::BI__sync_add_and_fetch_2:
212 case Builtin::BI__sync_add_and_fetch_4:
213 case Builtin::BI__sync_add_and_fetch_8:
214 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000215 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000216 case Builtin::BI__sync_sub_and_fetch_1:
217 case Builtin::BI__sync_sub_and_fetch_2:
218 case Builtin::BI__sync_sub_and_fetch_4:
219 case Builtin::BI__sync_sub_and_fetch_8:
220 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000221 case Builtin::BI__sync_and_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000222 case Builtin::BI__sync_and_and_fetch_1:
223 case Builtin::BI__sync_and_and_fetch_2:
224 case Builtin::BI__sync_and_and_fetch_4:
225 case Builtin::BI__sync_and_and_fetch_8:
226 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000227 case Builtin::BI__sync_or_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000228 case Builtin::BI__sync_or_and_fetch_1:
229 case Builtin::BI__sync_or_and_fetch_2:
230 case Builtin::BI__sync_or_and_fetch_4:
231 case Builtin::BI__sync_or_and_fetch_8:
232 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000233 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000234 case Builtin::BI__sync_xor_and_fetch_1:
235 case Builtin::BI__sync_xor_and_fetch_2:
236 case Builtin::BI__sync_xor_and_fetch_4:
237 case Builtin::BI__sync_xor_and_fetch_8:
238 case Builtin::BI__sync_xor_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000239 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000240 case Builtin::BI__sync_val_compare_and_swap_1:
241 case Builtin::BI__sync_val_compare_and_swap_2:
242 case Builtin::BI__sync_val_compare_and_swap_4:
243 case Builtin::BI__sync_val_compare_and_swap_8:
244 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000245 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000246 case Builtin::BI__sync_bool_compare_and_swap_1:
247 case Builtin::BI__sync_bool_compare_and_swap_2:
248 case Builtin::BI__sync_bool_compare_and_swap_4:
249 case Builtin::BI__sync_bool_compare_and_swap_8:
250 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000251 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregora9766412011-11-28 16:30:08 +0000252 case Builtin::BI__sync_lock_test_and_set_1:
253 case Builtin::BI__sync_lock_test_and_set_2:
254 case Builtin::BI__sync_lock_test_and_set_4:
255 case Builtin::BI__sync_lock_test_and_set_8:
256 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000257 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +0000258 case Builtin::BI__sync_lock_release_1:
259 case Builtin::BI__sync_lock_release_2:
260 case Builtin::BI__sync_lock_release_4:
261 case Builtin::BI__sync_lock_release_8:
262 case Builtin::BI__sync_lock_release_16:
Chris Lattner23aa9c82011-04-09 03:57:26 +0000263 case Builtin::BI__sync_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000264 case Builtin::BI__sync_swap_1:
265 case Builtin::BI__sync_swap_2:
266 case Builtin::BI__sync_swap_4:
267 case Builtin::BI__sync_swap_8:
268 case Builtin::BI__sync_swap_16:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000269 return SemaBuiltinAtomicOverloaded(TheCallResult);
Richard Smithff34d402012-04-12 05:08:17 +0000270#define BUILTIN(ID, TYPE, ATTRS)
271#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
272 case Builtin::BI##ID: \
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000273 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithff34d402012-04-12 05:08:17 +0000274#include "clang/Basic/Builtins.def"
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000275 case Builtin::BI__builtin_annotation:
Julien Lerougee5939212012-04-28 17:39:16 +0000276 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000277 return ExprError();
278 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000279 }
280
281 // Since the target specific builtins for each arch overlap, only check those
282 // of the arch we are compiling for.
283 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000284 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman26a31422010-06-08 02:47:44 +0000285 case llvm::Triple::arm:
286 case llvm::Triple::thumb:
287 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
288 return ExprError();
289 break;
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000290 case llvm::Triple::mips:
291 case llvm::Triple::mipsel:
292 case llvm::Triple::mips64:
293 case llvm::Triple::mips64el:
294 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
295 return ExprError();
296 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000297 default:
298 break;
299 }
300 }
301
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000302 return TheCallResult;
Nate Begeman26a31422010-06-08 02:47:44 +0000303}
304
Nate Begeman61eecf52010-06-14 05:21:25 +0000305// Get the valid immediate range for the specified NEON type code.
306static unsigned RFT(unsigned t, bool shift = false) {
Bob Wilsonda95f732011-11-08 01:16:11 +0000307 NeonTypeFlags Type(t);
308 int IsQuad = Type.isQuad();
309 switch (Type.getEltType()) {
310 case NeonTypeFlags::Int8:
311 case NeonTypeFlags::Poly8:
312 return shift ? 7 : (8 << IsQuad) - 1;
313 case NeonTypeFlags::Int16:
314 case NeonTypeFlags::Poly16:
315 return shift ? 15 : (4 << IsQuad) - 1;
316 case NeonTypeFlags::Int32:
317 return shift ? 31 : (2 << IsQuad) - 1;
318 case NeonTypeFlags::Int64:
319 return shift ? 63 : (1 << IsQuad) - 1;
320 case NeonTypeFlags::Float16:
321 assert(!shift && "cannot shift float types!");
322 return (4 << IsQuad) - 1;
323 case NeonTypeFlags::Float32:
324 assert(!shift && "cannot shift float types!");
325 return (2 << IsQuad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000326 }
David Blaikie7530c032012-01-17 06:56:22 +0000327 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman61eecf52010-06-14 05:21:25 +0000328}
329
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000330/// getNeonEltType - Return the QualType corresponding to the elements of
331/// the vector type specified by the NeonTypeFlags. This is used to check
332/// the pointer arguments for Neon load/store intrinsics.
333static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context) {
334 switch (Flags.getEltType()) {
335 case NeonTypeFlags::Int8:
336 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
337 case NeonTypeFlags::Int16:
338 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
339 case NeonTypeFlags::Int32:
340 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
341 case NeonTypeFlags::Int64:
342 return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy;
343 case NeonTypeFlags::Poly8:
344 return Context.SignedCharTy;
345 case NeonTypeFlags::Poly16:
346 return Context.ShortTy;
347 case NeonTypeFlags::Float16:
348 return Context.UnsignedShortTy;
349 case NeonTypeFlags::Float32:
350 return Context.FloatTy;
351 }
David Blaikie7530c032012-01-17 06:56:22 +0000352 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000353}
354
Nate Begeman26a31422010-06-08 02:47:44 +0000355bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000356 llvm::APSInt Result;
357
Richard Smithf8ee6bc2012-08-14 01:28:02 +0000358 uint64_t mask = 0;
Nate Begeman61eecf52010-06-14 05:21:25 +0000359 unsigned TV = 0;
Bob Wilson46482552011-11-16 21:32:23 +0000360 int PtrArgNum = -1;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000361 bool HasConstPtr = false;
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000362 switch (BuiltinID) {
Nate Begemana23326b2010-06-17 04:17:01 +0000363#define GET_NEON_OVERLOAD_CHECK
364#include "clang/Basic/arm_neon.inc"
365#undef GET_NEON_OVERLOAD_CHECK
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000366 }
367
Nate Begeman0d15c532010-06-13 04:47:52 +0000368 // For NEON intrinsics which are overloaded on vector element type, validate
369 // the immediate which specifies which variant to emit.
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000370 unsigned ImmArg = TheCall->getNumArgs()-1;
Nate Begeman0d15c532010-06-13 04:47:52 +0000371 if (mask) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000372 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
Nate Begeman0d15c532010-06-13 04:47:52 +0000373 return true;
374
Bob Wilsonda95f732011-11-08 01:16:11 +0000375 TV = Result.getLimitedValue(64);
Richard Smithf8ee6bc2012-08-14 01:28:02 +0000376 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
Nate Begeman0d15c532010-06-13 04:47:52 +0000377 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000378 << TheCall->getArg(ImmArg)->getSourceRange();
379 }
380
Bob Wilson46482552011-11-16 21:32:23 +0000381 if (PtrArgNum >= 0) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000382 // Check that pointer arguments have the specified type.
Bob Wilson46482552011-11-16 21:32:23 +0000383 Expr *Arg = TheCall->getArg(PtrArgNum);
384 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
385 Arg = ICE->getSubExpr();
386 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
387 QualType RHSTy = RHS.get()->getType();
388 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context);
389 if (HasConstPtr)
390 EltTy = EltTy.withConst();
391 QualType LHSTy = Context.getPointerType(EltTy);
392 AssignConvertType ConvTy;
393 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
394 if (RHS.isInvalid())
395 return true;
396 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
397 RHS.get(), AA_Assigning))
398 return true;
Nate Begeman0d15c532010-06-13 04:47:52 +0000399 }
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000400
Nate Begeman0d15c532010-06-13 04:47:52 +0000401 // For NEON intrinsics which take an immediate value as part of the
402 // instruction, range check them here.
Nate Begeman61eecf52010-06-14 05:21:25 +0000403 unsigned i = 0, l = 0, u = 0;
Nate Begeman0d15c532010-06-13 04:47:52 +0000404 switch (BuiltinID) {
405 default: return false;
Nate Begemanbb37f502010-07-29 22:48:34 +0000406 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
407 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begeman99c40bb2010-08-03 21:32:34 +0000408 case ARM::BI__builtin_arm_vcvtr_f:
409 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Nate Begemana23326b2010-06-17 04:17:01 +0000410#define GET_NEON_IMMEDIATE_CHECK
411#include "clang/Basic/arm_neon.inc"
412#undef GET_NEON_IMMEDIATE_CHECK
Nate Begeman0d15c532010-06-13 04:47:52 +0000413 };
414
Douglas Gregor592a4232012-06-29 01:05:22 +0000415 // We can't check the value of a dependent argument.
416 if (TheCall->getArg(i)->isTypeDependent() ||
417 TheCall->getArg(i)->isValueDependent())
418 return false;
419
Nate Begeman61eecf52010-06-14 05:21:25 +0000420 // Check that the immediate argument is actually a constant.
Nate Begeman0d15c532010-06-13 04:47:52 +0000421 if (SemaBuiltinConstantArg(TheCall, i, Result))
422 return true;
423
Nate Begeman61eecf52010-06-14 05:21:25 +0000424 // Range check against the upper/lower values for this isntruction.
Nate Begeman0d15c532010-06-13 04:47:52 +0000425 unsigned Val = Result.getZExtValue();
Nate Begeman61eecf52010-06-14 05:21:25 +0000426 if (Val < l || Val > (u + l))
Nate Begeman0d15c532010-06-13 04:47:52 +0000427 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramer476d8b82010-08-11 14:47:12 +0000428 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begeman0d15c532010-06-13 04:47:52 +0000429
Nate Begeman99c40bb2010-08-03 21:32:34 +0000430 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman26a31422010-06-08 02:47:44 +0000431 return false;
Anders Carlssond406bf02009-08-16 01:56:34 +0000432}
Daniel Dunbarde454282008-10-02 18:44:07 +0000433
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000434bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
435 unsigned i = 0, l = 0, u = 0;
436 switch (BuiltinID) {
437 default: return false;
438 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
439 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyanbe22cb82012-08-27 12:29:20 +0000440 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
441 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
442 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
443 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
444 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000445 };
446
447 // We can't check the value of a dependent argument.
448 if (TheCall->getArg(i)->isTypeDependent() ||
449 TheCall->getArg(i)->isValueDependent())
450 return false;
451
452 // Check that the immediate argument is actually a constant.
453 llvm::APSInt Result;
454 if (SemaBuiltinConstantArg(TheCall, i, Result))
455 return true;
456
457 // Range check against the upper/lower values for this instruction.
458 unsigned Val = Result.getZExtValue();
459 if (Val < l || Val > u)
460 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
461 << l << u << TheCall->getArg(i)->getSourceRange();
462
463 return false;
464}
465
Richard Smith831421f2012-06-25 20:30:08 +0000466/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
467/// parameter with the FormatAttr's correct format_idx and firstDataArg.
468/// Returns true when the format fits the function and the FormatStringInfo has
469/// been populated.
470bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
471 FormatStringInfo *FSI) {
472 FSI->HasVAListArg = Format->getFirstArg() == 0;
473 FSI->FormatIdx = Format->getFormatIdx() - 1;
474 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssond406bf02009-08-16 01:56:34 +0000475
Richard Smith831421f2012-06-25 20:30:08 +0000476 // The way the format attribute works in GCC, the implicit this argument
477 // of member functions is counted. However, it doesn't appear in our own
478 // lists, so decrement format_idx in that case.
479 if (IsCXXMember) {
480 if(FSI->FormatIdx == 0)
481 return false;
482 --FSI->FormatIdx;
483 if (FSI->FirstDataArg != 0)
484 --FSI->FirstDataArg;
485 }
486 return true;
487}
Mike Stump1eb44332009-09-09 15:08:12 +0000488
Richard Smith831421f2012-06-25 20:30:08 +0000489/// Handles the checks for format strings, non-POD arguments to vararg
490/// functions, and NULL arguments passed to non-NULL parameters.
491void Sema::checkCall(NamedDecl *FDecl, Expr **Args,
492 unsigned NumArgs,
493 unsigned NumProtoArgs,
494 bool IsMemberFunction,
495 SourceLocation Loc,
496 SourceRange Range,
497 VariadicCallType CallType) {
Jordan Rose66360e22012-10-02 01:49:54 +0000498 if (CurContext->isDependentContext())
499 return;
Daniel Dunbarde454282008-10-02 18:44:07 +0000500
Ted Kremenekc82faca2010-09-09 04:33:05 +0000501 // Printf and scanf checking.
Richard Smith831421f2012-06-25 20:30:08 +0000502 bool HandledFormatString = false;
Ted Kremenekc82faca2010-09-09 04:33:05 +0000503 for (specific_attr_iterator<FormatAttr>
Richard Smith831421f2012-06-25 20:30:08 +0000504 I = FDecl->specific_attr_begin<FormatAttr>(),
505 E = FDecl->specific_attr_end<FormatAttr>(); I != E ; ++I)
Jordan Roseddcfbc92012-07-19 18:10:23 +0000506 if (CheckFormatArguments(*I, Args, NumArgs, IsMemberFunction, CallType,
507 Loc, Range))
Richard Smith831421f2012-06-25 20:30:08 +0000508 HandledFormatString = true;
509
510 // Refuse POD arguments that weren't caught by the format string
511 // checks above.
512 if (!HandledFormatString && CallType != VariadicDoesNotApply)
513 for (unsigned ArgIdx = NumProtoArgs; ArgIdx < NumArgs; ++ArgIdx)
514 variadicArgumentPODCheck(Args[ArgIdx], CallType);
Mike Stump1eb44332009-09-09 15:08:12 +0000515
Ted Kremenekc82faca2010-09-09 04:33:05 +0000516 for (specific_attr_iterator<NonNullAttr>
Richard Smith831421f2012-06-25 20:30:08 +0000517 I = FDecl->specific_attr_begin<NonNullAttr>(),
518 E = FDecl->specific_attr_end<NonNullAttr>(); I != E; ++I)
519 CheckNonNullArguments(*I, Args, Loc);
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +0000520
521 // Type safety checking.
522 for (specific_attr_iterator<ArgumentWithTypeTagAttr>
523 i = FDecl->specific_attr_begin<ArgumentWithTypeTagAttr>(),
524 e = FDecl->specific_attr_end<ArgumentWithTypeTagAttr>(); i != e; ++i) {
525 CheckArgumentWithTypeTag(*i, Args);
526 }
Richard Smith831421f2012-06-25 20:30:08 +0000527}
528
529/// CheckConstructorCall - Check a constructor call for correctness and safety
530/// properties not enforced by the C type system.
531void Sema::CheckConstructorCall(FunctionDecl *FDecl, Expr **Args,
532 unsigned NumArgs,
533 const FunctionProtoType *Proto,
534 SourceLocation Loc) {
535 VariadicCallType CallType =
536 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
537 checkCall(FDecl, Args, NumArgs, Proto->getNumArgs(),
538 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
539}
540
541/// CheckFunctionCall - Check a direct function call for various correctness
542/// and safety properties not strictly enforced by the C type system.
543bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
544 const FunctionProtoType *Proto) {
Eli Friedman2edcde82012-10-11 00:30:58 +0000545 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
546 isa<CXXMethodDecl>(FDecl);
547 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
548 IsMemberOperatorCall;
Richard Smith831421f2012-06-25 20:30:08 +0000549 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
550 TheCall->getCallee());
551 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
Eli Friedman2edcde82012-10-11 00:30:58 +0000552 Expr** Args = TheCall->getArgs();
553 unsigned NumArgs = TheCall->getNumArgs();
554 if (isa<CXXOperatorCallExpr>(TheCall) && isa<CXXMethodDecl>(FDecl)) {
555 // If this is a call to a member operator, hide the first argument
556 // from checkCall.
557 // FIXME: Our choice of AST representation here is less than ideal.
558 ++Args;
559 --NumArgs;
560 }
561 checkCall(FDecl, Args, NumArgs, NumProtoArgs,
Richard Smith831421f2012-06-25 20:30:08 +0000562 IsMemberFunction, TheCall->getRParenLoc(),
563 TheCall->getCallee()->getSourceRange(), CallType);
564
565 IdentifierInfo *FnInfo = FDecl->getIdentifier();
566 // None of the checks below are needed for functions that don't have
567 // simple names (e.g., C++ conversion functions).
568 if (!FnInfo)
569 return false;
Sebastian Redl0eb23302009-01-19 00:08:26 +0000570
Anna Zaks0a151a12012-01-17 00:37:07 +0000571 unsigned CMId = FDecl->getMemoryFunctionKind();
572 if (CMId == 0)
Anna Zaksd9b859a2012-01-13 21:52:01 +0000573 return false;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000574
Anna Zaksd9b859a2012-01-13 21:52:01 +0000575 // Handle memory setting and copying functions.
Anna Zaks0a151a12012-01-17 00:37:07 +0000576 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000577 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaksc36bedc2012-02-01 19:08:57 +0000578 else if (CMId == Builtin::BIstrncat)
579 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaksd9b859a2012-01-13 21:52:01 +0000580 else
Anna Zaks0a151a12012-01-17 00:37:07 +0000581 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth7ccc95b2011-04-27 07:05:31 +0000582
Anders Carlssond406bf02009-08-16 01:56:34 +0000583 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000584}
585
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000586bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
587 Expr **Args, unsigned NumArgs) {
Richard Smith831421f2012-06-25 20:30:08 +0000588 VariadicCallType CallType =
589 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000590
Richard Smith831421f2012-06-25 20:30:08 +0000591 checkCall(Method, Args, NumArgs, Method->param_size(),
592 /*IsMemberFunction=*/false,
593 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000594
595 return false;
596}
597
Richard Smith831421f2012-06-25 20:30:08 +0000598bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall,
599 const FunctionProtoType *Proto) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000600 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
601 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000602 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000603
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000604 QualType Ty = V->getType();
605 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000606 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000607
Richard Smith831421f2012-06-25 20:30:08 +0000608 VariadicCallType CallType =
609 Proto && Proto->isVariadic() ? VariadicBlock : VariadicDoesNotApply ;
610 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
Anders Carlssond406bf02009-08-16 01:56:34 +0000611
Richard Smith831421f2012-06-25 20:30:08 +0000612 checkCall(NDecl, TheCall->getArgs(), TheCall->getNumArgs(),
613 NumProtoArgs, /*IsMemberFunction=*/false,
614 TheCall->getRParenLoc(),
615 TheCall->getCallee()->getSourceRange(), CallType);
616
Anders Carlssond406bf02009-08-16 01:56:34 +0000617 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000618}
619
Richard Smithff34d402012-04-12 05:08:17 +0000620ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
621 AtomicExpr::AtomicOp Op) {
Eli Friedman276b0612011-10-11 02:20:01 +0000622 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
623 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedman276b0612011-10-11 02:20:01 +0000624
Richard Smithff34d402012-04-12 05:08:17 +0000625 // All these operations take one of the following forms:
626 enum {
627 // C __c11_atomic_init(A *, C)
628 Init,
629 // C __c11_atomic_load(A *, int)
630 Load,
631 // void __atomic_load(A *, CP, int)
632 Copy,
633 // C __c11_atomic_add(A *, M, int)
634 Arithmetic,
635 // C __atomic_exchange_n(A *, CP, int)
636 Xchg,
637 // void __atomic_exchange(A *, C *, CP, int)
638 GNUXchg,
639 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
640 C11CmpXchg,
641 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
642 GNUCmpXchg
643 } Form = Init;
644 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
645 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
646 // where:
647 // C is an appropriate type,
648 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
649 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
650 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
651 // the int parameters are for orderings.
Eli Friedman276b0612011-10-11 02:20:01 +0000652
Richard Smithff34d402012-04-12 05:08:17 +0000653 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
654 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
655 && "need to update code for modified C11 atomics");
656 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
657 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
658 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
659 Op == AtomicExpr::AO__atomic_store_n ||
660 Op == AtomicExpr::AO__atomic_exchange_n ||
661 Op == AtomicExpr::AO__atomic_compare_exchange_n;
662 bool IsAddSub = false;
663
664 switch (Op) {
665 case AtomicExpr::AO__c11_atomic_init:
666 Form = Init;
667 break;
668
669 case AtomicExpr::AO__c11_atomic_load:
670 case AtomicExpr::AO__atomic_load_n:
671 Form = Load;
672 break;
673
674 case AtomicExpr::AO__c11_atomic_store:
675 case AtomicExpr::AO__atomic_load:
676 case AtomicExpr::AO__atomic_store:
677 case AtomicExpr::AO__atomic_store_n:
678 Form = Copy;
679 break;
680
681 case AtomicExpr::AO__c11_atomic_fetch_add:
682 case AtomicExpr::AO__c11_atomic_fetch_sub:
683 case AtomicExpr::AO__atomic_fetch_add:
684 case AtomicExpr::AO__atomic_fetch_sub:
685 case AtomicExpr::AO__atomic_add_fetch:
686 case AtomicExpr::AO__atomic_sub_fetch:
687 IsAddSub = true;
688 // Fall through.
689 case AtomicExpr::AO__c11_atomic_fetch_and:
690 case AtomicExpr::AO__c11_atomic_fetch_or:
691 case AtomicExpr::AO__c11_atomic_fetch_xor:
692 case AtomicExpr::AO__atomic_fetch_and:
693 case AtomicExpr::AO__atomic_fetch_or:
694 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smith51b92402012-04-13 06:31:38 +0000695 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithff34d402012-04-12 05:08:17 +0000696 case AtomicExpr::AO__atomic_and_fetch:
697 case AtomicExpr::AO__atomic_or_fetch:
698 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smith51b92402012-04-13 06:31:38 +0000699 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithff34d402012-04-12 05:08:17 +0000700 Form = Arithmetic;
701 break;
702
703 case AtomicExpr::AO__c11_atomic_exchange:
704 case AtomicExpr::AO__atomic_exchange_n:
705 Form = Xchg;
706 break;
707
708 case AtomicExpr::AO__atomic_exchange:
709 Form = GNUXchg;
710 break;
711
712 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
713 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
714 Form = C11CmpXchg;
715 break;
716
717 case AtomicExpr::AO__atomic_compare_exchange:
718 case AtomicExpr::AO__atomic_compare_exchange_n:
719 Form = GNUCmpXchg;
720 break;
721 }
722
723 // Check we have the right number of arguments.
724 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedman276b0612011-10-11 02:20:01 +0000725 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithff34d402012-04-12 05:08:17 +0000726 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +0000727 << TheCall->getCallee()->getSourceRange();
728 return ExprError();
Richard Smithff34d402012-04-12 05:08:17 +0000729 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
730 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedman276b0612011-10-11 02:20:01 +0000731 diag::err_typecheck_call_too_many_args)
Richard Smithff34d402012-04-12 05:08:17 +0000732 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +0000733 << TheCall->getCallee()->getSourceRange();
734 return ExprError();
735 }
736
Richard Smithff34d402012-04-12 05:08:17 +0000737 // Inspect the first argument of the atomic operation.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000738 Expr *Ptr = TheCall->getArg(0);
Eli Friedman276b0612011-10-11 02:20:01 +0000739 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
740 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
741 if (!pointerType) {
Richard Smithff34d402012-04-12 05:08:17 +0000742 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedman276b0612011-10-11 02:20:01 +0000743 << Ptr->getType() << Ptr->getSourceRange();
744 return ExprError();
745 }
746
Richard Smithff34d402012-04-12 05:08:17 +0000747 // For a __c11 builtin, this should be a pointer to an _Atomic type.
748 QualType AtomTy = pointerType->getPointeeType(); // 'A'
749 QualType ValType = AtomTy; // 'C'
750 if (IsC11) {
751 if (!AtomTy->isAtomicType()) {
752 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
753 << Ptr->getType() << Ptr->getSourceRange();
754 return ExprError();
755 }
Richard Smithbc57b102012-09-15 06:09:58 +0000756 if (AtomTy.isConstQualified()) {
757 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
758 << Ptr->getType() << Ptr->getSourceRange();
759 return ExprError();
760 }
Richard Smithff34d402012-04-12 05:08:17 +0000761 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedman276b0612011-10-11 02:20:01 +0000762 }
Eli Friedman276b0612011-10-11 02:20:01 +0000763
Richard Smithff34d402012-04-12 05:08:17 +0000764 // For an arithmetic operation, the implied arithmetic must be well-formed.
765 if (Form == Arithmetic) {
766 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
767 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
768 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
769 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
770 return ExprError();
771 }
772 if (!IsAddSub && !ValType->isIntegerType()) {
773 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
774 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
775 return ExprError();
776 }
777 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
778 // For __atomic_*_n operations, the value type must be a scalar integral or
779 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedman276b0612011-10-11 02:20:01 +0000780 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithff34d402012-04-12 05:08:17 +0000781 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
782 return ExprError();
783 }
784
785 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context)) {
786 // For GNU atomics, require a trivially-copyable type. This is not part of
787 // the GNU atomics specification, but we enforce it for sanity.
788 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedman276b0612011-10-11 02:20:01 +0000789 << Ptr->getType() << Ptr->getSourceRange();
790 return ExprError();
791 }
792
Richard Smithff34d402012-04-12 05:08:17 +0000793 // FIXME: For any builtin other than a load, the ValType must not be
794 // const-qualified.
Eli Friedman276b0612011-10-11 02:20:01 +0000795
796 switch (ValType.getObjCLifetime()) {
797 case Qualifiers::OCL_None:
798 case Qualifiers::OCL_ExplicitNone:
799 // okay
800 break;
801
802 case Qualifiers::OCL_Weak:
803 case Qualifiers::OCL_Strong:
804 case Qualifiers::OCL_Autoreleasing:
Richard Smithff34d402012-04-12 05:08:17 +0000805 // FIXME: Can this happen? By this point, ValType should be known
806 // to be trivially copyable.
Eli Friedman276b0612011-10-11 02:20:01 +0000807 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
808 << ValType << Ptr->getSourceRange();
809 return ExprError();
810 }
811
812 QualType ResultType = ValType;
Richard Smithff34d402012-04-12 05:08:17 +0000813 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedman276b0612011-10-11 02:20:01 +0000814 ResultType = Context.VoidTy;
Richard Smithff34d402012-04-12 05:08:17 +0000815 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedman276b0612011-10-11 02:20:01 +0000816 ResultType = Context.BoolTy;
817
Richard Smithff34d402012-04-12 05:08:17 +0000818 // The type of a parameter passed 'by value'. In the GNU atomics, such
819 // arguments are actually passed as pointers.
820 QualType ByValType = ValType; // 'CP'
821 if (!IsC11 && !IsN)
822 ByValType = Ptr->getType();
823
Eli Friedman276b0612011-10-11 02:20:01 +0000824 // The first argument --- the pointer --- has a fixed type; we
825 // deduce the types of the rest of the arguments accordingly. Walk
826 // the remaining arguments, converting them to the deduced value type.
Richard Smithff34d402012-04-12 05:08:17 +0000827 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedman276b0612011-10-11 02:20:01 +0000828 QualType Ty;
Richard Smithff34d402012-04-12 05:08:17 +0000829 if (i < NumVals[Form] + 1) {
830 switch (i) {
831 case 1:
832 // The second argument is the non-atomic operand. For arithmetic, this
833 // is always passed by value, and for a compare_exchange it is always
834 // passed by address. For the rest, GNU uses by-address and C11 uses
835 // by-value.
836 assert(Form != Load);
837 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
838 Ty = ValType;
839 else if (Form == Copy || Form == Xchg)
840 Ty = ByValType;
841 else if (Form == Arithmetic)
842 Ty = Context.getPointerDiffType();
843 else
844 Ty = Context.getPointerType(ValType.getUnqualifiedType());
845 break;
846 case 2:
847 // The third argument to compare_exchange / GNU exchange is a
848 // (pointer to a) desired value.
849 Ty = ByValType;
850 break;
851 case 3:
852 // The fourth argument to GNU compare_exchange is a 'weak' flag.
853 Ty = Context.BoolTy;
854 break;
855 }
Eli Friedman276b0612011-10-11 02:20:01 +0000856 } else {
857 // The order(s) are always converted to int.
858 Ty = Context.IntTy;
859 }
Richard Smithff34d402012-04-12 05:08:17 +0000860
Eli Friedman276b0612011-10-11 02:20:01 +0000861 InitializedEntity Entity =
862 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithff34d402012-04-12 05:08:17 +0000863 ExprResult Arg = TheCall->getArg(i);
Eli Friedman276b0612011-10-11 02:20:01 +0000864 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
865 if (Arg.isInvalid())
866 return true;
867 TheCall->setArg(i, Arg.get());
868 }
869
Richard Smithff34d402012-04-12 05:08:17 +0000870 // Permute the arguments into a 'consistent' order.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000871 SmallVector<Expr*, 5> SubExprs;
872 SubExprs.push_back(Ptr);
Richard Smithff34d402012-04-12 05:08:17 +0000873 switch (Form) {
874 case Init:
875 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnall7a7ee302012-01-16 17:27:18 +0000876 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +0000877 break;
878 case Load:
879 SubExprs.push_back(TheCall->getArg(1)); // Order
880 break;
881 case Copy:
882 case Arithmetic:
883 case Xchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000884 SubExprs.push_back(TheCall->getArg(2)); // Order
885 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +0000886 break;
887 case GNUXchg:
888 // Note, AtomicExpr::getVal2() has a special case for this atomic.
889 SubExprs.push_back(TheCall->getArg(3)); // Order
890 SubExprs.push_back(TheCall->getArg(1)); // Val1
891 SubExprs.push_back(TheCall->getArg(2)); // Val2
892 break;
893 case C11CmpXchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000894 SubExprs.push_back(TheCall->getArg(3)); // Order
895 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000896 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall2ebb98a2012-03-29 17:58:59 +0000897 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithff34d402012-04-12 05:08:17 +0000898 break;
899 case GNUCmpXchg:
900 SubExprs.push_back(TheCall->getArg(4)); // Order
901 SubExprs.push_back(TheCall->getArg(1)); // Val1
902 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
903 SubExprs.push_back(TheCall->getArg(2)); // Val2
904 SubExprs.push_back(TheCall->getArg(3)); // Weak
905 break;
Eli Friedman276b0612011-10-11 02:20:01 +0000906 }
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000907
908 return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +0000909 SubExprs, ResultType, Op,
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000910 TheCall->getRParenLoc()));
Eli Friedman276b0612011-10-11 02:20:01 +0000911}
912
913
John McCall5f8d6042011-08-27 01:09:30 +0000914/// checkBuiltinArgument - Given a call to a builtin function, perform
915/// normal type-checking on the given argument, updating the call in
916/// place. This is useful when a builtin function requires custom
917/// type-checking for some of its arguments but not necessarily all of
918/// them.
919///
920/// Returns true on error.
921static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
922 FunctionDecl *Fn = E->getDirectCallee();
923 assert(Fn && "builtin call without direct callee!");
924
925 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
926 InitializedEntity Entity =
927 InitializedEntity::InitializeParameter(S.Context, Param);
928
929 ExprResult Arg = E->getArg(0);
930 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
931 if (Arg.isInvalid())
932 return true;
933
934 E->setArg(ArgIndex, Arg.take());
935 return false;
936}
937
Chris Lattner5caa3702009-05-08 06:58:22 +0000938/// SemaBuiltinAtomicOverloaded - We have a call to a function like
939/// __sync_fetch_and_add, which is an overloaded function based on the pointer
940/// type of its first argument. The main ActOnCallExpr routines have already
941/// promoted the types of arguments because all of these calls are prototyped as
942/// void(...).
943///
944/// This function goes through and does final semantic checking for these
945/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +0000946ExprResult
947Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000948 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +0000949 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
950 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
951
952 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +0000953 if (TheCall->getNumArgs() < 1) {
954 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
955 << 0 << 1 << TheCall->getNumArgs()
956 << TheCall->getCallee()->getSourceRange();
957 return ExprError();
958 }
Mike Stump1eb44332009-09-09 15:08:12 +0000959
Chris Lattner5caa3702009-05-08 06:58:22 +0000960 // Inspect the first argument of the atomic builtin. This should always be
961 // a pointer type, whose element is an integral scalar or pointer type.
962 // Because it is a pointer type, we don't have to worry about any implicit
963 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +0000964 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +0000965 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman8c382062012-01-23 02:35:22 +0000966 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
967 if (FirstArgResult.isInvalid())
968 return ExprError();
969 FirstArg = FirstArgResult.take();
970 TheCall->setArg(0, FirstArg);
971
John McCallf85e1932011-06-15 23:02:42 +0000972 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
973 if (!pointerType) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000974 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
975 << FirstArg->getType() << FirstArg->getSourceRange();
976 return ExprError();
977 }
Mike Stump1eb44332009-09-09 15:08:12 +0000978
John McCallf85e1932011-06-15 23:02:42 +0000979 QualType ValType = pointerType->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +0000980 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +0000981 !ValType->isBlockPointerType()) {
982 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
983 << FirstArg->getType() << FirstArg->getSourceRange();
984 return ExprError();
985 }
Chris Lattner5caa3702009-05-08 06:58:22 +0000986
John McCallf85e1932011-06-15 23:02:42 +0000987 switch (ValType.getObjCLifetime()) {
988 case Qualifiers::OCL_None:
989 case Qualifiers::OCL_ExplicitNone:
990 // okay
991 break;
992
993 case Qualifiers::OCL_Weak:
994 case Qualifiers::OCL_Strong:
995 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +0000996 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCallf85e1932011-06-15 23:02:42 +0000997 << ValType << FirstArg->getSourceRange();
998 return ExprError();
999 }
1000
John McCallb45ae252011-10-05 07:41:44 +00001001 // Strip any qualifiers off ValType.
1002 ValType = ValType.getUnqualifiedType();
1003
Chandler Carruth8d13d222010-07-18 20:54:12 +00001004 // The majority of builtins return a value, but a few have special return
1005 // types, so allow them to override appropriately below.
1006 QualType ResultType = ValType;
1007
Chris Lattner5caa3702009-05-08 06:58:22 +00001008 // We need to figure out which concrete builtin this maps onto. For example,
1009 // __sync_fetch_and_add with a 2 byte object turns into
1010 // __sync_fetch_and_add_2.
1011#define BUILTIN_ROW(x) \
1012 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1013 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +00001014
Chris Lattner5caa3702009-05-08 06:58:22 +00001015 static const unsigned BuiltinIndices[][5] = {
1016 BUILTIN_ROW(__sync_fetch_and_add),
1017 BUILTIN_ROW(__sync_fetch_and_sub),
1018 BUILTIN_ROW(__sync_fetch_and_or),
1019 BUILTIN_ROW(__sync_fetch_and_and),
1020 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +00001021
Chris Lattner5caa3702009-05-08 06:58:22 +00001022 BUILTIN_ROW(__sync_add_and_fetch),
1023 BUILTIN_ROW(__sync_sub_and_fetch),
1024 BUILTIN_ROW(__sync_and_and_fetch),
1025 BUILTIN_ROW(__sync_or_and_fetch),
1026 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +00001027
Chris Lattner5caa3702009-05-08 06:58:22 +00001028 BUILTIN_ROW(__sync_val_compare_and_swap),
1029 BUILTIN_ROW(__sync_bool_compare_and_swap),
1030 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +00001031 BUILTIN_ROW(__sync_lock_release),
1032 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +00001033 };
Mike Stump1eb44332009-09-09 15:08:12 +00001034#undef BUILTIN_ROW
1035
Chris Lattner5caa3702009-05-08 06:58:22 +00001036 // Determine the index of the size.
1037 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +00001038 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +00001039 case 1: SizeIndex = 0; break;
1040 case 2: SizeIndex = 1; break;
1041 case 4: SizeIndex = 2; break;
1042 case 8: SizeIndex = 3; break;
1043 case 16: SizeIndex = 4; break;
1044 default:
Chandler Carruthd2014572010-07-09 18:59:35 +00001045 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1046 << FirstArg->getType() << FirstArg->getSourceRange();
1047 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +00001048 }
Mike Stump1eb44332009-09-09 15:08:12 +00001049
Chris Lattner5caa3702009-05-08 06:58:22 +00001050 // Each of these builtins has one pointer argument, followed by some number of
1051 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1052 // that we ignore. Find out which row of BuiltinIndices to read from as well
1053 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00001054 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +00001055 unsigned BuiltinIndex, NumFixed = 1;
1056 switch (BuiltinID) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001057 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregora9766412011-11-28 16:30:08 +00001058 case Builtin::BI__sync_fetch_and_add:
1059 case Builtin::BI__sync_fetch_and_add_1:
1060 case Builtin::BI__sync_fetch_and_add_2:
1061 case Builtin::BI__sync_fetch_and_add_4:
1062 case Builtin::BI__sync_fetch_and_add_8:
1063 case Builtin::BI__sync_fetch_and_add_16:
1064 BuiltinIndex = 0;
1065 break;
1066
1067 case Builtin::BI__sync_fetch_and_sub:
1068 case Builtin::BI__sync_fetch_and_sub_1:
1069 case Builtin::BI__sync_fetch_and_sub_2:
1070 case Builtin::BI__sync_fetch_and_sub_4:
1071 case Builtin::BI__sync_fetch_and_sub_8:
1072 case Builtin::BI__sync_fetch_and_sub_16:
1073 BuiltinIndex = 1;
1074 break;
1075
1076 case Builtin::BI__sync_fetch_and_or:
1077 case Builtin::BI__sync_fetch_and_or_1:
1078 case Builtin::BI__sync_fetch_and_or_2:
1079 case Builtin::BI__sync_fetch_and_or_4:
1080 case Builtin::BI__sync_fetch_and_or_8:
1081 case Builtin::BI__sync_fetch_and_or_16:
1082 BuiltinIndex = 2;
1083 break;
1084
1085 case Builtin::BI__sync_fetch_and_and:
1086 case Builtin::BI__sync_fetch_and_and_1:
1087 case Builtin::BI__sync_fetch_and_and_2:
1088 case Builtin::BI__sync_fetch_and_and_4:
1089 case Builtin::BI__sync_fetch_and_and_8:
1090 case Builtin::BI__sync_fetch_and_and_16:
1091 BuiltinIndex = 3;
1092 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001093
Douglas Gregora9766412011-11-28 16:30:08 +00001094 case Builtin::BI__sync_fetch_and_xor:
1095 case Builtin::BI__sync_fetch_and_xor_1:
1096 case Builtin::BI__sync_fetch_and_xor_2:
1097 case Builtin::BI__sync_fetch_and_xor_4:
1098 case Builtin::BI__sync_fetch_and_xor_8:
1099 case Builtin::BI__sync_fetch_and_xor_16:
1100 BuiltinIndex = 4;
1101 break;
1102
1103 case Builtin::BI__sync_add_and_fetch:
1104 case Builtin::BI__sync_add_and_fetch_1:
1105 case Builtin::BI__sync_add_and_fetch_2:
1106 case Builtin::BI__sync_add_and_fetch_4:
1107 case Builtin::BI__sync_add_and_fetch_8:
1108 case Builtin::BI__sync_add_and_fetch_16:
1109 BuiltinIndex = 5;
1110 break;
1111
1112 case Builtin::BI__sync_sub_and_fetch:
1113 case Builtin::BI__sync_sub_and_fetch_1:
1114 case Builtin::BI__sync_sub_and_fetch_2:
1115 case Builtin::BI__sync_sub_and_fetch_4:
1116 case Builtin::BI__sync_sub_and_fetch_8:
1117 case Builtin::BI__sync_sub_and_fetch_16:
1118 BuiltinIndex = 6;
1119 break;
1120
1121 case Builtin::BI__sync_and_and_fetch:
1122 case Builtin::BI__sync_and_and_fetch_1:
1123 case Builtin::BI__sync_and_and_fetch_2:
1124 case Builtin::BI__sync_and_and_fetch_4:
1125 case Builtin::BI__sync_and_and_fetch_8:
1126 case Builtin::BI__sync_and_and_fetch_16:
1127 BuiltinIndex = 7;
1128 break;
1129
1130 case Builtin::BI__sync_or_and_fetch:
1131 case Builtin::BI__sync_or_and_fetch_1:
1132 case Builtin::BI__sync_or_and_fetch_2:
1133 case Builtin::BI__sync_or_and_fetch_4:
1134 case Builtin::BI__sync_or_and_fetch_8:
1135 case Builtin::BI__sync_or_and_fetch_16:
1136 BuiltinIndex = 8;
1137 break;
1138
1139 case Builtin::BI__sync_xor_and_fetch:
1140 case Builtin::BI__sync_xor_and_fetch_1:
1141 case Builtin::BI__sync_xor_and_fetch_2:
1142 case Builtin::BI__sync_xor_and_fetch_4:
1143 case Builtin::BI__sync_xor_and_fetch_8:
1144 case Builtin::BI__sync_xor_and_fetch_16:
1145 BuiltinIndex = 9;
1146 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001147
Chris Lattner5caa3702009-05-08 06:58:22 +00001148 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001149 case Builtin::BI__sync_val_compare_and_swap_1:
1150 case Builtin::BI__sync_val_compare_and_swap_2:
1151 case Builtin::BI__sync_val_compare_and_swap_4:
1152 case Builtin::BI__sync_val_compare_and_swap_8:
1153 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001154 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +00001155 NumFixed = 2;
1156 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001157
Chris Lattner5caa3702009-05-08 06:58:22 +00001158 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001159 case Builtin::BI__sync_bool_compare_and_swap_1:
1160 case Builtin::BI__sync_bool_compare_and_swap_2:
1161 case Builtin::BI__sync_bool_compare_and_swap_4:
1162 case Builtin::BI__sync_bool_compare_and_swap_8:
1163 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001164 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +00001165 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001166 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001167 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001168
1169 case Builtin::BI__sync_lock_test_and_set:
1170 case Builtin::BI__sync_lock_test_and_set_1:
1171 case Builtin::BI__sync_lock_test_and_set_2:
1172 case Builtin::BI__sync_lock_test_and_set_4:
1173 case Builtin::BI__sync_lock_test_and_set_8:
1174 case Builtin::BI__sync_lock_test_and_set_16:
1175 BuiltinIndex = 12;
1176 break;
1177
Chris Lattner5caa3702009-05-08 06:58:22 +00001178 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +00001179 case Builtin::BI__sync_lock_release_1:
1180 case Builtin::BI__sync_lock_release_2:
1181 case Builtin::BI__sync_lock_release_4:
1182 case Builtin::BI__sync_lock_release_8:
1183 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001184 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +00001185 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001186 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001187 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001188
1189 case Builtin::BI__sync_swap:
1190 case Builtin::BI__sync_swap_1:
1191 case Builtin::BI__sync_swap_2:
1192 case Builtin::BI__sync_swap_4:
1193 case Builtin::BI__sync_swap_8:
1194 case Builtin::BI__sync_swap_16:
1195 BuiltinIndex = 14;
1196 break;
Chris Lattner5caa3702009-05-08 06:58:22 +00001197 }
Mike Stump1eb44332009-09-09 15:08:12 +00001198
Chris Lattner5caa3702009-05-08 06:58:22 +00001199 // Now that we know how many fixed arguments we expect, first check that we
1200 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +00001201 if (TheCall->getNumArgs() < 1+NumFixed) {
1202 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1203 << 0 << 1+NumFixed << TheCall->getNumArgs()
1204 << TheCall->getCallee()->getSourceRange();
1205 return ExprError();
1206 }
Mike Stump1eb44332009-09-09 15:08:12 +00001207
Chris Lattnere7ac0a92009-05-08 15:36:58 +00001208 // Get the decl for the concrete builtin from this, we can tell what the
1209 // concrete integer type we should convert to is.
1210 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1211 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara2ad11cd2012-09-22 09:05:22 +00001212 FunctionDecl *NewBuiltinDecl;
1213 if (NewBuiltinID == BuiltinID)
1214 NewBuiltinDecl = FDecl;
1215 else {
1216 // Perform builtin lookup to avoid redeclaring it.
1217 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1218 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1219 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1220 assert(Res.getFoundDecl());
1221 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
1222 if (NewBuiltinDecl == 0)
1223 return ExprError();
1224 }
Chandler Carruthd2014572010-07-09 18:59:35 +00001225
John McCallf871d0c2010-08-07 06:22:56 +00001226 // The first argument --- the pointer --- has a fixed type; we
1227 // deduce the types of the rest of the arguments accordingly. Walk
1228 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +00001229 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +00001230 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +00001231
Chris Lattner5caa3702009-05-08 06:58:22 +00001232 // GCC does an implicit conversion to the pointer or integer ValType. This
1233 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb45ae252011-10-05 07:41:44 +00001234 // Initialize the argument.
1235 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1236 ValType, /*consume*/ false);
1237 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley429bb272011-04-08 18:41:53 +00001238 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +00001239 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001240
Chris Lattner5caa3702009-05-08 06:58:22 +00001241 // Okay, we have something that *can* be converted to the right type. Check
1242 // to see if there is a potentially weird extension going on here. This can
1243 // happen when you do an atomic operation on something like an char* and
1244 // pass in 42. The 42 gets converted to char. This is even more strange
1245 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +00001246 // FIXME: Do this check.
John McCallb45ae252011-10-05 07:41:44 +00001247 TheCall->setArg(i+1, Arg.take());
Chris Lattner5caa3702009-05-08 06:58:22 +00001248 }
Mike Stump1eb44332009-09-09 15:08:12 +00001249
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001250 ASTContext& Context = this->getASTContext();
1251
1252 // Create a new DeclRefExpr to refer to the new decl.
1253 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1254 Context,
1255 DRE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001256 SourceLocation(),
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001257 NewBuiltinDecl,
John McCallf4b88a42012-03-10 09:33:50 +00001258 /*enclosing*/ false,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001259 DRE->getLocation(),
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001260 Context.BuiltinFnTy,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001261 DRE->getValueKind());
Mike Stump1eb44332009-09-09 15:08:12 +00001262
Chris Lattner5caa3702009-05-08 06:58:22 +00001263 // Set the callee in the CallExpr.
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001264 // FIXME: This loses syntactic information.
1265 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1266 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1267 CK_BuiltinFnToFnPtr);
John Wiegley429bb272011-04-08 18:41:53 +00001268 TheCall->setCallee(PromotedCall.take());
Mike Stump1eb44332009-09-09 15:08:12 +00001269
Chandler Carruthdb4325b2010-07-18 07:23:17 +00001270 // Change the result type of the call to match the original value type. This
1271 // is arbitrary, but the codegen for these builtins ins design to handle it
1272 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +00001273 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +00001274
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001275 return TheCallResult;
Chris Lattner5caa3702009-05-08 06:58:22 +00001276}
1277
Chris Lattner69039812009-02-18 06:01:06 +00001278/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +00001279/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +00001280/// Note: It might also make sense to do the UTF-16 conversion here (would
1281/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +00001282bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +00001283 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +00001284 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1285
Douglas Gregor5cee1192011-07-27 05:40:30 +00001286 if (!Literal || !Literal->isAscii()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001287 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1288 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001289 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +00001290 }
Mike Stump1eb44332009-09-09 15:08:12 +00001291
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001292 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001293 StringRef String = Literal->getString();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001294 unsigned NumBytes = String.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001295 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divacky31ba6132012-09-06 15:59:27 +00001296 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001297 UTF16 *ToPtr = &ToBuf[0];
1298
1299 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1300 &ToPtr, ToPtr + NumBytes,
1301 strictConversion);
1302 // Check for conversion failure.
1303 if (Result != conversionOK)
1304 Diag(Arg->getLocStart(),
1305 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1306 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001307 return false;
Chris Lattner59907c42007-08-10 20:18:51 +00001308}
1309
Chris Lattnerc27c6652007-12-20 00:05:45 +00001310/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1311/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +00001312bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1313 Expr *Fn = TheCall->getCallee();
1314 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +00001315 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001316 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001317 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1318 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +00001319 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001320 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +00001321 return true;
1322 }
Eli Friedman56f20ae2008-12-15 22:05:35 +00001323
1324 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +00001325 return Diag(TheCall->getLocEnd(),
1326 diag::err_typecheck_call_too_few_args_at_least)
1327 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +00001328 }
1329
John McCall5f8d6042011-08-27 01:09:30 +00001330 // Type-check the first argument normally.
1331 if (checkBuiltinArgument(*this, TheCall, 0))
1332 return true;
1333
Chris Lattnerc27c6652007-12-20 00:05:45 +00001334 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001335 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +00001336 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001337 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +00001338 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +00001339 else if (FunctionDecl *FD = getCurFunctionDecl())
1340 isVariadic = FD->isVariadic();
1341 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001342 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +00001343
Chris Lattnerc27c6652007-12-20 00:05:45 +00001344 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001345 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1346 return true;
1347 }
Mike Stump1eb44332009-09-09 15:08:12 +00001348
Chris Lattner30ce3442007-12-19 23:59:04 +00001349 // Verify that the second argument to the builtin is the last argument of the
1350 // current function or method.
1351 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +00001352 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001353
Anders Carlsson88cf2262008-02-11 04:20:54 +00001354 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1355 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001356 // FIXME: This isn't correct for methods (results in bogus warning).
1357 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +00001358 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001359 if (CurBlock)
1360 LastArg = *(CurBlock->TheDecl->param_end()-1);
1361 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +00001362 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001363 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001364 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001365 SecondArgIsLastNamedArgument = PV == LastArg;
1366 }
1367 }
Mike Stump1eb44332009-09-09 15:08:12 +00001368
Chris Lattner30ce3442007-12-19 23:59:04 +00001369 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001370 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +00001371 diag::warn_second_parameter_of_va_start_not_last_named_argument);
1372 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +00001373}
Chris Lattner30ce3442007-12-19 23:59:04 +00001374
Chris Lattner1b9a0792007-12-20 00:26:33 +00001375/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1376/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +00001377bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1378 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +00001379 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001380 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +00001381 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +00001382 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001383 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001384 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001385 << SourceRange(TheCall->getArg(2)->getLocStart(),
1386 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001387
John Wiegley429bb272011-04-08 18:41:53 +00001388 ExprResult OrigArg0 = TheCall->getArg(0);
1389 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +00001390
Chris Lattner1b9a0792007-12-20 00:26:33 +00001391 // Do standard promotions between the two arguments, returning their common
1392 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +00001393 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +00001394 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1395 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +00001396
1397 // Make sure any conversions are pushed back into the call; this is
1398 // type safe since unordered compare builtins are declared as "_Bool
1399 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +00001400 TheCall->setArg(0, OrigArg0.get());
1401 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001402
John Wiegley429bb272011-04-08 18:41:53 +00001403 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +00001404 return false;
1405
Chris Lattner1b9a0792007-12-20 00:26:33 +00001406 // If the common type isn't a real floating type, then the arguments were
1407 // invalid for this operation.
Eli Friedman860a3192012-06-16 02:19:17 +00001408 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +00001409 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001410 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +00001411 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1412 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001413
Chris Lattner1b9a0792007-12-20 00:26:33 +00001414 return false;
1415}
1416
Benjamin Kramere771a7a2010-02-15 22:42:31 +00001417/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1418/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001419/// to check everything. We expect the last argument to be a floating point
1420/// value.
1421bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1422 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +00001423 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001424 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001425 if (TheCall->getNumArgs() > NumArgs)
1426 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001427 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001428 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001429 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001430 (*(TheCall->arg_end()-1))->getLocEnd());
1431
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001432 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001433
Eli Friedman9ac6f622009-08-31 20:06:00 +00001434 if (OrigArg->isTypeDependent())
1435 return false;
1436
Chris Lattner81368fb2010-05-06 05:50:07 +00001437 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +00001438 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +00001439 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001440 diag::err_typecheck_call_invalid_unary_fp)
1441 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001442
Chris Lattner81368fb2010-05-06 05:50:07 +00001443 // If this is an implicit conversion from float -> double, remove it.
1444 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1445 Expr *CastArg = Cast->getSubExpr();
1446 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1447 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1448 "promotion from float to double is the only expected cast here");
1449 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +00001450 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner81368fb2010-05-06 05:50:07 +00001451 }
1452 }
1453
Eli Friedman9ac6f622009-08-31 20:06:00 +00001454 return false;
1455}
1456
Eli Friedmand38617c2008-05-14 19:38:39 +00001457/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1458// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +00001459ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001460 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001461 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +00001462 diag::err_typecheck_call_too_few_args_at_least)
Nate Begeman37b6a572010-06-08 00:16:34 +00001463 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherd77b9a22010-04-16 04:48:22 +00001464 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001465
Nate Begeman37b6a572010-06-08 00:16:34 +00001466 // Determine which of the following types of shufflevector we're checking:
1467 // 1) unary, vector mask: (lhs, mask)
1468 // 2) binary, vector mask: (lhs, rhs, mask)
1469 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1470 QualType resType = TheCall->getArg(0)->getType();
1471 unsigned numElements = 0;
1472
Douglas Gregorcde01732009-05-19 22:10:17 +00001473 if (!TheCall->getArg(0)->isTypeDependent() &&
1474 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001475 QualType LHSType = TheCall->getArg(0)->getType();
1476 QualType RHSType = TheCall->getArg(1)->getType();
1477
1478 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001479 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001480 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001481 TheCall->getArg(1)->getLocEnd());
1482 return ExprError();
1483 }
Nate Begeman37b6a572010-06-08 00:16:34 +00001484
1485 numElements = LHSType->getAs<VectorType>()->getNumElements();
1486 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +00001487
Nate Begeman37b6a572010-06-08 00:16:34 +00001488 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1489 // with mask. If so, verify that RHS is an integer vector type with the
1490 // same number of elts as lhs.
1491 if (TheCall->getNumArgs() == 2) {
Douglas Gregorf6094622010-07-23 15:58:24 +00001492 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +00001493 RHSType->getAs<VectorType>()->getNumElements() != numElements)
1494 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1495 << SourceRange(TheCall->getArg(1)->getLocStart(),
1496 TheCall->getArg(1)->getLocEnd());
1497 numResElements = numElements;
1498 }
1499 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001500 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001501 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001502 TheCall->getArg(1)->getLocEnd());
1503 return ExprError();
Nate Begeman37b6a572010-06-08 00:16:34 +00001504 } else if (numElements != numResElements) {
1505 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +00001506 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001507 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +00001508 }
Eli Friedmand38617c2008-05-14 19:38:39 +00001509 }
1510
1511 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001512 if (TheCall->getArg(i)->isTypeDependent() ||
1513 TheCall->getArg(i)->isValueDependent())
1514 continue;
1515
Nate Begeman37b6a572010-06-08 00:16:34 +00001516 llvm::APSInt Result(32);
1517 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1518 return ExprError(Diag(TheCall->getLocStart(),
1519 diag::err_shufflevector_nonconstant_argument)
1520 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001521
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001522 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001523 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001524 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001525 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001526 }
1527
Chris Lattner5f9e2722011-07-23 10:55:15 +00001528 SmallVector<Expr*, 32> exprs;
Eli Friedmand38617c2008-05-14 19:38:39 +00001529
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001530 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +00001531 exprs.push_back(TheCall->getArg(i));
1532 TheCall->setArg(i, 0);
1533 }
1534
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001535 return Owned(new (Context) ShuffleVectorExpr(Context, exprs, resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001536 TheCall->getCallee()->getLocStart(),
1537 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +00001538}
Chris Lattner30ce3442007-12-19 23:59:04 +00001539
Daniel Dunbar4493f792008-07-21 22:59:13 +00001540/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1541// This is declared to take (const void*, ...) and can take two
1542// optional constant int args.
1543bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001544 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001545
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001546 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +00001547 return Diag(TheCall->getLocEnd(),
1548 diag::err_typecheck_call_too_many_args_at_most)
1549 << 0 /*function call*/ << 3 << NumArgs
1550 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001551
1552 // Argument 0 is checked for us and the remaining arguments must be
1553 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001554 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +00001555 Expr *Arg = TheCall->getArg(i);
Douglas Gregor592a4232012-06-29 01:05:22 +00001556
1557 // We can't check the value of a dependent argument.
1558 if (Arg->isTypeDependent() || Arg->isValueDependent())
1559 continue;
1560
Eli Friedman9aef7262009-12-04 00:30:06 +00001561 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +00001562 if (SemaBuiltinConstantArg(TheCall, i, Result))
1563 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001564
Daniel Dunbar4493f792008-07-21 22:59:13 +00001565 // FIXME: gcc issues a warning and rewrites these to 0. These
1566 // seems especially odd for the third argument since the default
1567 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001568 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +00001569 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001570 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001571 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001572 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +00001573 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001574 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001575 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001576 }
1577 }
1578
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001579 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +00001580}
1581
Eric Christopher691ebc32010-04-17 02:26:23 +00001582/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1583/// TheCall is a constant expression.
1584bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1585 llvm::APSInt &Result) {
1586 Expr *Arg = TheCall->getArg(ArgNum);
1587 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1588 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1589
1590 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1591
1592 if (!Arg->isIntegerConstantExpr(Result, Context))
1593 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +00001594 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +00001595
Chris Lattner21fb98e2009-09-23 06:06:36 +00001596 return false;
1597}
1598
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001599/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1600/// int type). This simply type checks that type is one of the defined
1601/// constants (0-3).
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001602// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001603bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +00001604 llvm::APSInt Result;
Douglas Gregor592a4232012-06-29 01:05:22 +00001605
1606 // We can't check the value of a dependent argument.
1607 if (TheCall->getArg(1)->isTypeDependent() ||
1608 TheCall->getArg(1)->isValueDependent())
1609 return false;
1610
Eric Christopher691ebc32010-04-17 02:26:23 +00001611 // Check constant-ness first.
1612 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1613 return true;
1614
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001615 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001616 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001617 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1618 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001619 }
1620
1621 return false;
1622}
1623
Eli Friedman586d6a82009-05-03 06:04:26 +00001624/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +00001625/// This checks that val is a constant 1.
1626bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1627 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +00001628 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +00001629
Eric Christopher691ebc32010-04-17 02:26:23 +00001630 // TODO: This is less than ideal. Overload this to take a value.
1631 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1632 return true;
1633
1634 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +00001635 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1636 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1637
1638 return false;
1639}
1640
Richard Smith831421f2012-06-25 20:30:08 +00001641// Determine if an expression is a string literal or constant string.
1642// If this function returns false on the arguments to a function expecting a
1643// format string, we will usually need to emit a warning.
1644// True string literals are then checked by CheckFormatString.
1645Sema::StringLiteralCheckType
1646Sema::checkFormatStringExpr(const Expr *E, Expr **Args,
1647 unsigned NumArgs, bool HasVAListArg,
1648 unsigned format_idx, unsigned firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001649 FormatStringType Type, VariadicCallType CallType,
1650 bool inFunctionCall) {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001651 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +00001652 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith831421f2012-06-25 20:30:08 +00001653 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001654
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001655 E = E->IgnoreParenCasts();
Peter Collingbournef111d932011-04-15 00:35:48 +00001656
David Blaikiea73cdcb2012-02-10 21:07:25 +00001657 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
1658 // Technically -Wformat-nonliteral does not warn about this case.
1659 // The behavior of printf and friends in this case is implementation
1660 // dependent. Ideally if the format string cannot be null then
1661 // it should have a 'nonnull' attribute in the function prototype.
Richard Smith831421f2012-06-25 20:30:08 +00001662 return SLCT_CheckedLiteral;
David Blaikiea73cdcb2012-02-10 21:07:25 +00001663
Ted Kremenekd30ef872009-01-12 23:09:09 +00001664 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +00001665 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +00001666 case Stmt::ConditionalOperatorClass: {
Richard Smith831421f2012-06-25 20:30:08 +00001667 // The expression is a literal if both sub-expressions were, and it was
1668 // completely checked only if both sub-expressions were checked.
1669 const AbstractConditionalOperator *C =
1670 cast<AbstractConditionalOperator>(E);
1671 StringLiteralCheckType Left =
1672 checkFormatStringExpr(C->getTrueExpr(), Args, NumArgs,
1673 HasVAListArg, format_idx, firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001674 Type, CallType, inFunctionCall);
Richard Smith831421f2012-06-25 20:30:08 +00001675 if (Left == SLCT_NotALiteral)
1676 return SLCT_NotALiteral;
1677 StringLiteralCheckType Right =
1678 checkFormatStringExpr(C->getFalseExpr(), Args, NumArgs,
1679 HasVAListArg, format_idx, firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001680 Type, CallType, inFunctionCall);
Richard Smith831421f2012-06-25 20:30:08 +00001681 return Left < Right ? Left : Right;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001682 }
1683
1684 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001685 E = cast<ImplicitCastExpr>(E)->getSubExpr();
1686 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001687 }
1688
John McCall56ca35d2011-02-17 10:25:35 +00001689 case Stmt::OpaqueValueExprClass:
1690 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
1691 E = src;
1692 goto tryAgain;
1693 }
Richard Smith831421f2012-06-25 20:30:08 +00001694 return SLCT_NotALiteral;
John McCall56ca35d2011-02-17 10:25:35 +00001695
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001696 case Stmt::PredefinedExprClass:
1697 // While __func__, etc., are technically not string literals, they
1698 // cannot contain format specifiers and thus are not a security
1699 // liability.
Richard Smith831421f2012-06-25 20:30:08 +00001700 return SLCT_UncheckedLiteral;
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001701
Ted Kremenek082d9362009-03-20 21:35:28 +00001702 case Stmt::DeclRefExprClass: {
1703 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001704
Ted Kremenek082d9362009-03-20 21:35:28 +00001705 // As an exception, do not flag errors for variables binding to
1706 // const string literals.
1707 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1708 bool isConstant = false;
1709 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001710
Ted Kremenek082d9362009-03-20 21:35:28 +00001711 if (const ArrayType *AT = Context.getAsArrayType(T)) {
1712 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001713 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001714 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +00001715 PT->getPointeeType().isConstant(Context);
Jean-Daniel Dupase98e5b52012-01-25 10:35:33 +00001716 } else if (T->isObjCObjectPointerType()) {
1717 // In ObjC, there is usually no "const ObjectPointer" type,
1718 // so don't check if the pointee type is constant.
1719 isConstant = T.isConstant(Context);
Ted Kremenek082d9362009-03-20 21:35:28 +00001720 }
Mike Stump1eb44332009-09-09 15:08:12 +00001721
Ted Kremenek082d9362009-03-20 21:35:28 +00001722 if (isConstant) {
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00001723 if (const Expr *Init = VD->getAnyInitializer()) {
1724 // Look through initializers like const char c[] = { "foo" }
1725 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
1726 if (InitList->isStringLiteralInit())
1727 Init = InitList->getInit(0)->IgnoreParenImpCasts();
1728 }
Richard Smith831421f2012-06-25 20:30:08 +00001729 return checkFormatStringExpr(Init, Args, NumArgs,
1730 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001731 firstDataArg, Type, CallType,
Richard Smith831421f2012-06-25 20:30:08 +00001732 /*inFunctionCall*/false);
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00001733 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001734 }
Mike Stump1eb44332009-09-09 15:08:12 +00001735
Anders Carlssond966a552009-06-28 19:55:58 +00001736 // For vprintf* functions (i.e., HasVAListArg==true), we add a
1737 // special check to see if the format string is a function parameter
1738 // of the function calling the printf function. If the function
1739 // has an attribute indicating it is a printf-like function, then we
1740 // should suppress warnings concerning non-literals being used in a call
1741 // to a vprintf function. For example:
1742 //
1743 // void
1744 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1745 // va_list ap;
1746 // va_start(ap, fmt);
1747 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
1748 // ...
1749 //
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00001750 if (HasVAListArg) {
1751 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
1752 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
1753 int PVIndex = PV->getFunctionScopeIndex() + 1;
1754 for (specific_attr_iterator<FormatAttr>
1755 i = ND->specific_attr_begin<FormatAttr>(),
1756 e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) {
1757 FormatAttr *PVFormat = *i;
1758 // adjust for implicit parameter
1759 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1760 if (MD->isInstance())
1761 ++PVIndex;
1762 // We also check if the formats are compatible.
1763 // We can't pass a 'scanf' string to a 'printf' function.
1764 if (PVIndex == PVFormat->getFormatIdx() &&
1765 Type == GetFormatStringType(PVFormat))
Richard Smith831421f2012-06-25 20:30:08 +00001766 return SLCT_UncheckedLiteral;
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00001767 }
1768 }
1769 }
1770 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001771 }
Mike Stump1eb44332009-09-09 15:08:12 +00001772
Richard Smith831421f2012-06-25 20:30:08 +00001773 return SLCT_NotALiteral;
Ted Kremenek082d9362009-03-20 21:35:28 +00001774 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00001775
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001776 case Stmt::CallExprClass:
1777 case Stmt::CXXMemberCallExprClass: {
Anders Carlsson8f031b32009-06-27 04:05:33 +00001778 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001779 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
1780 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
1781 unsigned ArgIndex = FA->getFormatIdx();
1782 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1783 if (MD->isInstance())
1784 --ArgIndex;
1785 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001786
Richard Smith831421f2012-06-25 20:30:08 +00001787 return checkFormatStringExpr(Arg, Args, NumArgs,
1788 HasVAListArg, format_idx, firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001789 Type, CallType, inFunctionCall);
Jordan Rose50687312012-06-04 23:52:23 +00001790 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
1791 unsigned BuiltinID = FD->getBuiltinID();
1792 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
1793 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
1794 const Expr *Arg = CE->getArg(0);
Richard Smith831421f2012-06-25 20:30:08 +00001795 return checkFormatStringExpr(Arg, Args, NumArgs,
1796 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001797 firstDataArg, Type, CallType,
1798 inFunctionCall);
Jordan Rose50687312012-06-04 23:52:23 +00001799 }
Anders Carlsson8f031b32009-06-27 04:05:33 +00001800 }
1801 }
Mike Stump1eb44332009-09-09 15:08:12 +00001802
Richard Smith831421f2012-06-25 20:30:08 +00001803 return SLCT_NotALiteral;
Anders Carlsson8f031b32009-06-27 04:05:33 +00001804 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001805 case Stmt::ObjCStringLiteralClass:
1806 case Stmt::StringLiteralClass: {
1807 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001808
Ted Kremenek082d9362009-03-20 21:35:28 +00001809 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00001810 StrE = ObjCFExpr->getString();
1811 else
Ted Kremenek082d9362009-03-20 21:35:28 +00001812 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001813
Ted Kremenekd30ef872009-01-12 23:09:09 +00001814 if (StrE) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001815 CheckFormatString(StrE, E, Args, NumArgs, HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001816 firstDataArg, Type, inFunctionCall, CallType);
Richard Smith831421f2012-06-25 20:30:08 +00001817 return SLCT_CheckedLiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001818 }
Mike Stump1eb44332009-09-09 15:08:12 +00001819
Richard Smith831421f2012-06-25 20:30:08 +00001820 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001821 }
Mike Stump1eb44332009-09-09 15:08:12 +00001822
Ted Kremenek082d9362009-03-20 21:35:28 +00001823 default:
Richard Smith831421f2012-06-25 20:30:08 +00001824 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001825 }
1826}
1827
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001828void
Mike Stump1eb44332009-09-09 15:08:12 +00001829Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewycky909a70d2011-03-25 01:44:32 +00001830 const Expr * const *ExprArgs,
1831 SourceLocation CallSiteLoc) {
Sean Huntcf807c42010-08-18 23:23:40 +00001832 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1833 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001834 i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +00001835 const Expr *ArgExpr = ExprArgs[*i];
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001836 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00001837 Expr::NPC_ValueDependentIsNotNull))
Nick Lewycky909a70d2011-03-25 01:44:32 +00001838 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001839 }
1840}
Ted Kremenekd30ef872009-01-12 23:09:09 +00001841
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001842Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
1843 return llvm::StringSwitch<FormatStringType>(Format->getType())
1844 .Case("scanf", FST_Scanf)
1845 .Cases("printf", "printf0", FST_Printf)
1846 .Cases("NSString", "CFString", FST_NSString)
1847 .Case("strftime", FST_Strftime)
1848 .Case("strfmon", FST_Strfmon)
1849 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
1850 .Default(FST_Unknown);
1851}
1852
Jordan Roseddcfbc92012-07-19 18:10:23 +00001853/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek826a3452010-07-16 02:11:22 +00001854/// functions) for correct use of format strings.
Richard Smith831421f2012-06-25 20:30:08 +00001855/// Returns true if a format string has been fully checked.
Richard Smith831421f2012-06-25 20:30:08 +00001856bool Sema::CheckFormatArguments(const FormatAttr *Format, Expr **Args,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001857 unsigned NumArgs, bool IsCXXMember,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001858 VariadicCallType CallType,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001859 SourceLocation Loc, SourceRange Range) {
Richard Smith831421f2012-06-25 20:30:08 +00001860 FormatStringInfo FSI;
1861 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
1862 return CheckFormatArguments(Args, NumArgs, FSI.HasVAListArg, FSI.FormatIdx,
1863 FSI.FirstDataArg, GetFormatStringType(Format),
Jordan Roseddcfbc92012-07-19 18:10:23 +00001864 CallType, Loc, Range);
Richard Smith831421f2012-06-25 20:30:08 +00001865 return false;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001866}
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001867
Richard Smith831421f2012-06-25 20:30:08 +00001868bool Sema::CheckFormatArguments(Expr **Args, unsigned NumArgs,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001869 bool HasVAListArg, unsigned format_idx,
1870 unsigned firstDataArg, FormatStringType Type,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001871 VariadicCallType CallType,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001872 SourceLocation Loc, SourceRange Range) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001873 // CHECK: printf/scanf-like function is called with no format string.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001874 if (format_idx >= NumArgs) {
1875 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith831421f2012-06-25 20:30:08 +00001876 return false;
Ted Kremenek71895b92007-08-14 17:39:48 +00001877 }
Mike Stump1eb44332009-09-09 15:08:12 +00001878
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001879 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001880
Chris Lattner59907c42007-08-10 20:18:51 +00001881 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001882 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001883 // Dynamically generated format strings are difficult to
1884 // automatically vet at compile time. Requiring that format strings
1885 // are string literals: (1) permits the checking of format strings by
1886 // the compiler and thereby (2) can practically remove the source of
1887 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001888
Mike Stump1eb44332009-09-09 15:08:12 +00001889 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001890 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001891 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001892 // the same format string checking logic for both ObjC and C strings.
Richard Smith831421f2012-06-25 20:30:08 +00001893 StringLiteralCheckType CT =
1894 checkFormatStringExpr(OrigFormatExpr, Args, NumArgs, HasVAListArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001895 format_idx, firstDataArg, Type, CallType);
Richard Smith831421f2012-06-25 20:30:08 +00001896 if (CT != SLCT_NotALiteral)
1897 // Literal format string found, check done!
1898 return CT == SLCT_CheckedLiteral;
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001899
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00001900 // Strftime is particular as it always uses a single 'time' argument,
1901 // so it is safe to pass a non-literal string.
1902 if (Type == FST_Strftime)
Richard Smith831421f2012-06-25 20:30:08 +00001903 return false;
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00001904
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00001905 // Do not emit diag when the string param is a macro expansion and the
1906 // format is either NSString or CFString. This is a hack to prevent
1907 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
1908 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupasdc170202012-05-04 21:08:08 +00001909 if (Type == FST_NSString &&
1910 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith831421f2012-06-25 20:30:08 +00001911 return false;
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00001912
Chris Lattner655f1412009-04-29 04:59:47 +00001913 // If there are no arguments specified, warn with -Wformat-security, otherwise
1914 // warn only with -Wformat-nonliteral.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001915 if (NumArgs == format_idx+1)
1916 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001917 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00001918 << OrigFormatExpr->getSourceRange();
1919 else
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001920 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001921 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00001922 << OrigFormatExpr->getSourceRange();
Richard Smith831421f2012-06-25 20:30:08 +00001923 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001924}
Ted Kremenek71895b92007-08-14 17:39:48 +00001925
Ted Kremeneke0e53132010-01-28 23:39:18 +00001926namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00001927class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1928protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001929 Sema &S;
1930 const StringLiteral *FExpr;
1931 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001932 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001933 const unsigned NumDataArgs;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001934 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001935 const bool HasVAListArg;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001936 const Expr * const *Args;
1937 const unsigned NumArgs;
Ted Kremenek0d277352010-01-29 01:06:55 +00001938 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001939 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00001940 bool usesPositionalArgs;
1941 bool atFirstArg;
Richard Trieu55733de2011-10-28 00:41:25 +00001942 bool inFunctionCall;
Jordan Roseddcfbc92012-07-19 18:10:23 +00001943 Sema::VariadicCallType CallType;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001944public:
Ted Kremenek826a3452010-07-16 02:11:22 +00001945 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00001946 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00001947 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001948 Expr **args, unsigned numArgs,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001949 unsigned formatIdx, bool inFunctionCall,
1950 Sema::VariadicCallType callType)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001951 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose50687312012-06-04 23:52:23 +00001952 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
1953 Beg(beg), HasVAListArg(hasVAListArg),
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001954 Args(args), NumArgs(numArgs), FormatIdx(formatIdx),
Richard Trieu55733de2011-10-28 00:41:25 +00001955 usesPositionalArgs(false), atFirstArg(true),
Jordan Roseddcfbc92012-07-19 18:10:23 +00001956 inFunctionCall(inFunctionCall), CallType(callType) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001957 CoveredArgs.resize(numDataArgs);
1958 CoveredArgs.reset();
1959 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001960
Ted Kremenek07d161f2010-01-29 01:50:07 +00001961 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001962
Ted Kremenek826a3452010-07-16 02:11:22 +00001963 void HandleIncompleteSpecifier(const char *startSpecifier,
1964 unsigned specifierLen);
Hans Wennborg76517422012-02-22 10:17:01 +00001965
Jordan Rosebbb6bb42012-09-08 04:00:03 +00001966 void HandleInvalidLengthModifier(
1967 const analyze_format_string::FormatSpecifier &FS,
1968 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose8be066e2012-09-08 04:00:12 +00001969 const char *startSpecifier, unsigned specifierLen, unsigned DiagID);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00001970
Hans Wennborg76517422012-02-22 10:17:01 +00001971 void HandleNonStandardLengthModifier(
Jordan Rose8be066e2012-09-08 04:00:12 +00001972 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborg76517422012-02-22 10:17:01 +00001973 const char *startSpecifier, unsigned specifierLen);
1974
1975 void HandleNonStandardConversionSpecifier(
1976 const analyze_format_string::ConversionSpecifier &CS,
1977 const char *startSpecifier, unsigned specifierLen);
1978
Hans Wennborgf8562642012-03-09 10:10:54 +00001979 virtual void HandlePosition(const char *startPos, unsigned posLen);
1980
Ted Kremenekefaff192010-02-27 01:41:03 +00001981 virtual void HandleInvalidPosition(const char *startSpecifier,
1982 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00001983 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00001984
1985 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1986
Ted Kremeneke0e53132010-01-28 23:39:18 +00001987 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001988
Richard Trieu55733de2011-10-28 00:41:25 +00001989 template <typename Range>
1990 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
1991 const Expr *ArgumentExpr,
1992 PartialDiagnostic PDiag,
1993 SourceLocation StringLoc,
1994 bool IsStringLocation, Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00001995 ArrayRef<FixItHint> Fixit = ArrayRef<FixItHint>());
Richard Trieu55733de2011-10-28 00:41:25 +00001996
Ted Kremenek826a3452010-07-16 02:11:22 +00001997protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001998 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1999 const char *startSpec,
2000 unsigned specifierLen,
2001 const char *csStart, unsigned csLen);
Richard Trieu55733de2011-10-28 00:41:25 +00002002
2003 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2004 const char *startSpec,
2005 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002006
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002007 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00002008 CharSourceRange getSpecifierRange(const char *startSpecifier,
2009 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002010 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002011
Ted Kremenek0d277352010-01-29 01:06:55 +00002012 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00002013
2014 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2015 const analyze_format_string::ConversionSpecifier &CS,
2016 const char *startSpecifier, unsigned specifierLen,
2017 unsigned argIndex);
Richard Trieu55733de2011-10-28 00:41:25 +00002018
2019 template <typename Range>
2020 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2021 bool IsStringLocation, Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002022 ArrayRef<FixItHint> Fixit = ArrayRef<FixItHint>());
Richard Trieu55733de2011-10-28 00:41:25 +00002023
2024 void CheckPositionalAndNonpositionalArgs(
2025 const analyze_format_string::FormatSpecifier *FS);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002026};
2027}
2028
Ted Kremenek826a3452010-07-16 02:11:22 +00002029SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00002030 return OrigFormatExpr->getSourceRange();
2031}
2032
Ted Kremenek826a3452010-07-16 02:11:22 +00002033CharSourceRange CheckFormatHandler::
2034getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002035 SourceLocation Start = getLocationOfByte(startSpecifier);
2036 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2037
2038 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002039 End = End.getLocWithOffset(1);
Tom Care45f9b7e2010-06-21 21:21:01 +00002040
2041 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002042}
2043
Ted Kremenek826a3452010-07-16 02:11:22 +00002044SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002045 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002046}
2047
Ted Kremenek826a3452010-07-16 02:11:22 +00002048void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2049 unsigned specifierLen){
Richard Trieu55733de2011-10-28 00:41:25 +00002050 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2051 getLocationOfByte(startSpecifier),
2052 /*IsStringLocation*/true,
2053 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek808015a2010-01-29 03:16:21 +00002054}
2055
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002056void CheckFormatHandler::HandleInvalidLengthModifier(
2057 const analyze_format_string::FormatSpecifier &FS,
2058 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose8be066e2012-09-08 04:00:12 +00002059 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002060 using namespace analyze_format_string;
2061
2062 const LengthModifier &LM = FS.getLengthModifier();
2063 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2064
2065 // See if we know how to fix this length modifier.
2066 llvm::Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
2067 if (FixedLM) {
Jordan Rose8be066e2012-09-08 04:00:12 +00002068 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002069 getLocationOfByte(LM.getStart()),
2070 /*IsStringLocation*/true,
2071 getSpecifierRange(startSpecifier, specifierLen));
2072
2073 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2074 << FixedLM->toString()
2075 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2076
2077 } else {
Jordan Rose8be066e2012-09-08 04:00:12 +00002078 FixItHint Hint;
2079 if (DiagID == diag::warn_format_nonsensical_length)
2080 Hint = FixItHint::CreateRemoval(LMRange);
2081
2082 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002083 getLocationOfByte(LM.getStart()),
2084 /*IsStringLocation*/true,
2085 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose8be066e2012-09-08 04:00:12 +00002086 Hint);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002087 }
2088}
2089
Hans Wennborg76517422012-02-22 10:17:01 +00002090void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose8be066e2012-09-08 04:00:12 +00002091 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborg76517422012-02-22 10:17:01 +00002092 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose8be066e2012-09-08 04:00:12 +00002093 using namespace analyze_format_string;
2094
2095 const LengthModifier &LM = FS.getLengthModifier();
2096 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2097
2098 // See if we know how to fix this length modifier.
2099 llvm::Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
2100 if (FixedLM) {
2101 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2102 << LM.toString() << 0,
2103 getLocationOfByte(LM.getStart()),
2104 /*IsStringLocation*/true,
2105 getSpecifierRange(startSpecifier, specifierLen));
2106
2107 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2108 << FixedLM->toString()
2109 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2110
2111 } else {
2112 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2113 << LM.toString() << 0,
2114 getLocationOfByte(LM.getStart()),
2115 /*IsStringLocation*/true,
2116 getSpecifierRange(startSpecifier, specifierLen));
2117 }
Hans Wennborg76517422012-02-22 10:17:01 +00002118}
2119
2120void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2121 const analyze_format_string::ConversionSpecifier &CS,
2122 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose670941c2012-09-13 02:11:15 +00002123 using namespace analyze_format_string;
2124
2125 // See if we know how to fix this conversion specifier.
2126 llvm::Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
2127 if (FixedCS) {
2128 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2129 << CS.toString() << /*conversion specifier*/1,
2130 getLocationOfByte(CS.getStart()),
2131 /*IsStringLocation*/true,
2132 getSpecifierRange(startSpecifier, specifierLen));
2133
2134 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2135 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2136 << FixedCS->toString()
2137 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2138 } else {
2139 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2140 << CS.toString() << /*conversion specifier*/1,
2141 getLocationOfByte(CS.getStart()),
2142 /*IsStringLocation*/true,
2143 getSpecifierRange(startSpecifier, specifierLen));
2144 }
Hans Wennborg76517422012-02-22 10:17:01 +00002145}
2146
Hans Wennborgf8562642012-03-09 10:10:54 +00002147void CheckFormatHandler::HandlePosition(const char *startPos,
2148 unsigned posLen) {
2149 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2150 getLocationOfByte(startPos),
2151 /*IsStringLocation*/true,
2152 getSpecifierRange(startPos, posLen));
2153}
2154
Ted Kremenekefaff192010-02-27 01:41:03 +00002155void
Ted Kremenek826a3452010-07-16 02:11:22 +00002156CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2157 analyze_format_string::PositionContext p) {
Richard Trieu55733de2011-10-28 00:41:25 +00002158 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2159 << (unsigned) p,
2160 getLocationOfByte(startPos), /*IsStringLocation*/true,
2161 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002162}
2163
Ted Kremenek826a3452010-07-16 02:11:22 +00002164void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00002165 unsigned posLen) {
Richard Trieu55733de2011-10-28 00:41:25 +00002166 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2167 getLocationOfByte(startPos),
2168 /*IsStringLocation*/true,
2169 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002170}
2171
Ted Kremenek826a3452010-07-16 02:11:22 +00002172void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose50687312012-06-04 23:52:23 +00002173 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0c069442011-03-15 21:18:48 +00002174 // The presence of a null character is likely an error.
Richard Trieu55733de2011-10-28 00:41:25 +00002175 EmitFormatDiagnostic(
2176 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2177 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2178 getFormatStringRange());
Ted Kremenek0c069442011-03-15 21:18:48 +00002179 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002180}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002181
Jordan Rose48716662012-07-19 18:10:08 +00002182// Note that this may return NULL if there was an error parsing or building
2183// one of the argument expressions.
Ted Kremenek826a3452010-07-16 02:11:22 +00002184const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002185 return Args[FirstDataArg + i];
Ted Kremenek826a3452010-07-16 02:11:22 +00002186}
2187
2188void CheckFormatHandler::DoneProcessing() {
2189 // Does the number of data arguments exceed the number of
2190 // format conversions in the format string?
2191 if (!HasVAListArg) {
2192 // Find any arguments that weren't covered.
2193 CoveredArgs.flip();
2194 signed notCoveredArg = CoveredArgs.find_first();
2195 if (notCoveredArg >= 0) {
2196 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose48716662012-07-19 18:10:08 +00002197 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2198 SourceLocation Loc = E->getLocStart();
2199 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2200 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2201 Loc, /*IsStringLocation*/false,
2202 getFormatStringRange());
2203 }
Bob Wilsonc03f2df2012-05-03 19:47:19 +00002204 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002205 }
2206 }
2207}
2208
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002209bool
2210CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2211 SourceLocation Loc,
2212 const char *startSpec,
2213 unsigned specifierLen,
2214 const char *csStart,
2215 unsigned csLen) {
2216
2217 bool keepGoing = true;
2218 if (argIndex < NumDataArgs) {
2219 // Consider the argument coverered, even though the specifier doesn't
2220 // make sense.
2221 CoveredArgs.set(argIndex);
2222 }
2223 else {
2224 // If argIndex exceeds the number of data arguments we
2225 // don't issue a warning because that is just a cascade of warnings (and
2226 // they may have intended '%%' anyway). We don't want to continue processing
2227 // the format string after this point, however, as we will like just get
2228 // gibberish when trying to match arguments.
2229 keepGoing = false;
2230 }
2231
Richard Trieu55733de2011-10-28 00:41:25 +00002232 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2233 << StringRef(csStart, csLen),
2234 Loc, /*IsStringLocation*/true,
2235 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002236
2237 return keepGoing;
2238}
2239
Richard Trieu55733de2011-10-28 00:41:25 +00002240void
2241CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2242 const char *startSpec,
2243 unsigned specifierLen) {
2244 EmitFormatDiagnostic(
2245 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2246 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2247}
2248
Ted Kremenek666a1972010-07-26 19:45:42 +00002249bool
2250CheckFormatHandler::CheckNumArgs(
2251 const analyze_format_string::FormatSpecifier &FS,
2252 const analyze_format_string::ConversionSpecifier &CS,
2253 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2254
2255 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002256 PartialDiagnostic PDiag = FS.usesPositionalArg()
2257 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2258 << (argIndex+1) << NumDataArgs)
2259 : S.PDiag(diag::warn_printf_insufficient_data_args);
2260 EmitFormatDiagnostic(
2261 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2262 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek666a1972010-07-26 19:45:42 +00002263 return false;
2264 }
2265 return true;
2266}
2267
Richard Trieu55733de2011-10-28 00:41:25 +00002268template<typename Range>
2269void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2270 SourceLocation Loc,
2271 bool IsStringLocation,
2272 Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002273 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002274 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu55733de2011-10-28 00:41:25 +00002275 Loc, IsStringLocation, StringRange, FixIt);
2276}
2277
2278/// \brief If the format string is not within the funcion call, emit a note
2279/// so that the function call and string are in diagnostic messages.
2280///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00002281/// \param InFunctionCall if true, the format string is within the function
Richard Trieu55733de2011-10-28 00:41:25 +00002282/// call and only one diagnostic message will be produced. Otherwise, an
2283/// extra note will be emitted pointing to location of the format string.
2284///
2285/// \param ArgumentExpr the expression that is passed as the format string
2286/// argument in the function call. Used for getting locations when two
2287/// diagnostics are emitted.
2288///
2289/// \param PDiag the callee should already have provided any strings for the
2290/// diagnostic message. This function only adds locations and fixits
2291/// to diagnostics.
2292///
2293/// \param Loc primary location for diagnostic. If two diagnostics are
2294/// required, one will be at Loc and a new SourceLocation will be created for
2295/// the other one.
2296///
2297/// \param IsStringLocation if true, Loc points to the format string should be
2298/// used for the note. Otherwise, Loc points to the argument list and will
2299/// be used with PDiag.
2300///
2301/// \param StringRange some or all of the string to highlight. This is
2302/// templated so it can accept either a CharSourceRange or a SourceRange.
2303///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00002304/// \param FixIt optional fix it hint for the format string.
Richard Trieu55733de2011-10-28 00:41:25 +00002305template<typename Range>
2306void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2307 const Expr *ArgumentExpr,
2308 PartialDiagnostic PDiag,
2309 SourceLocation Loc,
2310 bool IsStringLocation,
2311 Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002312 ArrayRef<FixItHint> FixIt) {
2313 if (InFunctionCall) {
2314 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2315 D << StringRange;
2316 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2317 I != E; ++I) {
2318 D << *I;
2319 }
2320 } else {
Richard Trieu55733de2011-10-28 00:41:25 +00002321 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2322 << ArgumentExpr->getSourceRange();
Jordan Roseec087352012-09-05 22:56:26 +00002323
2324 const Sema::SemaDiagnosticBuilder &Note =
2325 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2326 diag::note_format_string_defined);
2327
2328 Note << StringRange;
2329 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2330 I != E; ++I) {
2331 Note << *I;
2332 }
Richard Trieu55733de2011-10-28 00:41:25 +00002333 }
2334}
2335
Ted Kremenek826a3452010-07-16 02:11:22 +00002336//===--- CHECK: Printf format string checking ------------------------------===//
2337
2338namespace {
2339class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose50687312012-06-04 23:52:23 +00002340 bool ObjCContext;
Ted Kremenek826a3452010-07-16 02:11:22 +00002341public:
2342 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2343 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002344 unsigned numDataArgs, bool isObjC,
Ted Kremenek826a3452010-07-16 02:11:22 +00002345 const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002346 Expr **Args, unsigned NumArgs,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002347 unsigned formatIdx, bool inFunctionCall,
2348 Sema::VariadicCallType CallType)
Ted Kremenek826a3452010-07-16 02:11:22 +00002349 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002350 numDataArgs, beg, hasVAListArg, Args, NumArgs,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002351 formatIdx, inFunctionCall, CallType), ObjCContext(isObjC)
2352 {}
2353
Ted Kremenek826a3452010-07-16 02:11:22 +00002354
2355 bool HandleInvalidPrintfConversionSpecifier(
2356 const analyze_printf::PrintfSpecifier &FS,
2357 const char *startSpecifier,
2358 unsigned specifierLen);
2359
2360 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2361 const char *startSpecifier,
2362 unsigned specifierLen);
Richard Smith831421f2012-06-25 20:30:08 +00002363 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2364 const char *StartSpecifier,
2365 unsigned SpecifierLen,
2366 const Expr *E);
2367
Ted Kremenek826a3452010-07-16 02:11:22 +00002368 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2369 const char *startSpecifier, unsigned specifierLen);
2370 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2371 const analyze_printf::OptionalAmount &Amt,
2372 unsigned type,
2373 const char *startSpecifier, unsigned specifierLen);
2374 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2375 const analyze_printf::OptionalFlag &flag,
2376 const char *startSpecifier, unsigned specifierLen);
2377 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2378 const analyze_printf::OptionalFlag &ignoredFlag,
2379 const analyze_printf::OptionalFlag &flag,
2380 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgf3749f42012-08-07 08:11:26 +00002381 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith831421f2012-06-25 20:30:08 +00002382 const Expr *E, const CharSourceRange &CSR);
2383
Ted Kremenek826a3452010-07-16 02:11:22 +00002384};
2385}
2386
2387bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2388 const analyze_printf::PrintfSpecifier &FS,
2389 const char *startSpecifier,
2390 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002391 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002392 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002393
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002394 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2395 getLocationOfByte(CS.getStart()),
2396 startSpecifier, specifierLen,
2397 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00002398}
2399
Ted Kremenek826a3452010-07-16 02:11:22 +00002400bool CheckPrintfHandler::HandleAmount(
2401 const analyze_format_string::OptionalAmount &Amt,
2402 unsigned k, const char *startSpecifier,
2403 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002404
2405 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002406 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002407 unsigned argIndex = Amt.getArgIndex();
2408 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002409 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2410 << k,
2411 getLocationOfByte(Amt.getStart()),
2412 /*IsStringLocation*/true,
2413 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002414 // Don't do any more checking. We will just emit
2415 // spurious errors.
2416 return false;
2417 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002418
Ted Kremenek0d277352010-01-29 01:06:55 +00002419 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00002420 // Although not in conformance with C99, we also allow the argument to be
2421 // an 'unsigned int' as that is a reasonably safe case. GCC also
2422 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002423 CoveredArgs.set(argIndex);
2424 const Expr *Arg = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00002425 if (!Arg)
2426 return false;
2427
Ted Kremenek0d277352010-01-29 01:06:55 +00002428 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002429
Hans Wennborgf3749f42012-08-07 08:11:26 +00002430 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
2431 assert(AT.isValid());
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002432
Hans Wennborgf3749f42012-08-07 08:11:26 +00002433 if (!AT.matchesType(S.Context, T)) {
Richard Trieu55733de2011-10-28 00:41:25 +00002434 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgf3749f42012-08-07 08:11:26 +00002435 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu55733de2011-10-28 00:41:25 +00002436 << T << Arg->getSourceRange(),
2437 getLocationOfByte(Amt.getStart()),
2438 /*IsStringLocation*/true,
2439 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002440 // Don't do any more checking. We will just emit
2441 // spurious errors.
2442 return false;
2443 }
2444 }
2445 }
2446 return true;
2447}
Ted Kremenek0d277352010-01-29 01:06:55 +00002448
Tom Caree4ee9662010-06-17 19:00:27 +00002449void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00002450 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002451 const analyze_printf::OptionalAmount &Amt,
2452 unsigned type,
2453 const char *startSpecifier,
2454 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002455 const analyze_printf::PrintfConversionSpecifier &CS =
2456 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00002457
Richard Trieu55733de2011-10-28 00:41:25 +00002458 FixItHint fixit =
2459 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2460 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2461 Amt.getConstantLength()))
2462 : FixItHint();
2463
2464 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2465 << type << CS.toString(),
2466 getLocationOfByte(Amt.getStart()),
2467 /*IsStringLocation*/true,
2468 getSpecifierRange(startSpecifier, specifierLen),
2469 fixit);
Tom Caree4ee9662010-06-17 19:00:27 +00002470}
2471
Ted Kremenek826a3452010-07-16 02:11:22 +00002472void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002473 const analyze_printf::OptionalFlag &flag,
2474 const char *startSpecifier,
2475 unsigned specifierLen) {
2476 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002477 const analyze_printf::PrintfConversionSpecifier &CS =
2478 FS.getConversionSpecifier();
Richard Trieu55733de2011-10-28 00:41:25 +00002479 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2480 << flag.toString() << CS.toString(),
2481 getLocationOfByte(flag.getPosition()),
2482 /*IsStringLocation*/true,
2483 getSpecifierRange(startSpecifier, specifierLen),
2484 FixItHint::CreateRemoval(
2485 getSpecifierRange(flag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002486}
2487
2488void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00002489 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002490 const analyze_printf::OptionalFlag &ignoredFlag,
2491 const analyze_printf::OptionalFlag &flag,
2492 const char *startSpecifier,
2493 unsigned specifierLen) {
2494 // Warn about ignored flag with a fixit removal.
Richard Trieu55733de2011-10-28 00:41:25 +00002495 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2496 << ignoredFlag.toString() << flag.toString(),
2497 getLocationOfByte(ignoredFlag.getPosition()),
2498 /*IsStringLocation*/true,
2499 getSpecifierRange(startSpecifier, specifierLen),
2500 FixItHint::CreateRemoval(
2501 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002502}
2503
Richard Smith831421f2012-06-25 20:30:08 +00002504// Determines if the specified is a C++ class or struct containing
2505// a member with the specified name and kind (e.g. a CXXMethodDecl named
2506// "c_str()").
2507template<typename MemberKind>
2508static llvm::SmallPtrSet<MemberKind*, 1>
2509CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2510 const RecordType *RT = Ty->getAs<RecordType>();
2511 llvm::SmallPtrSet<MemberKind*, 1> Results;
2512
2513 if (!RT)
2514 return Results;
2515 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
2516 if (!RD)
2517 return Results;
2518
2519 LookupResult R(S, &S.PP.getIdentifierTable().get(Name), SourceLocation(),
2520 Sema::LookupMemberName);
2521
2522 // We just need to include all members of the right kind turned up by the
2523 // filter, at this point.
2524 if (S.LookupQualifiedName(R, RT->getDecl()))
2525 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2526 NamedDecl *decl = (*I)->getUnderlyingDecl();
2527 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
2528 Results.insert(FK);
2529 }
2530 return Results;
2531}
2532
2533// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgf3749f42012-08-07 08:11:26 +00002534// better diagnostic if so. AT is assumed to be valid.
Richard Smith831421f2012-06-25 20:30:08 +00002535// Returns true when a c_str() conversion method is found.
2536bool CheckPrintfHandler::checkForCStrMembers(
Hans Wennborgf3749f42012-08-07 08:11:26 +00002537 const analyze_printf::ArgType &AT, const Expr *E,
Richard Smith831421f2012-06-25 20:30:08 +00002538 const CharSourceRange &CSR) {
2539 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2540
2541 MethodSet Results =
2542 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
2543
2544 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2545 MI != ME; ++MI) {
2546 const CXXMethodDecl *Method = *MI;
2547 if (Method->getNumParams() == 0 &&
Hans Wennborgf3749f42012-08-07 08:11:26 +00002548 AT.matchesType(S.Context, Method->getResultType())) {
Richard Smith831421f2012-06-25 20:30:08 +00002549 // FIXME: Suggest parens if the expression needs them.
2550 SourceLocation EndLoc =
2551 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd());
2552 S.Diag(E->getLocStart(), diag::note_printf_c_str)
2553 << "c_str()"
2554 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
2555 return true;
2556 }
2557 }
2558
2559 return false;
2560}
2561
Ted Kremeneke0e53132010-01-28 23:39:18 +00002562bool
Ted Kremenek826a3452010-07-16 02:11:22 +00002563CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002564 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00002565 const char *startSpecifier,
2566 unsigned specifierLen) {
2567
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002568 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00002569 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002570 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00002571
Ted Kremenekbaa40062010-07-19 22:01:06 +00002572 if (FS.consumesDataArgument()) {
2573 if (atFirstArg) {
2574 atFirstArg = false;
2575 usesPositionalArgs = FS.usesPositionalArg();
2576 }
2577 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002578 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2579 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002580 return false;
2581 }
Ted Kremenek0d277352010-01-29 01:06:55 +00002582 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002583
Ted Kremenekefaff192010-02-27 01:41:03 +00002584 // First check if the field width, precision, and conversion specifier
2585 // have matching data arguments.
2586 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2587 startSpecifier, specifierLen)) {
2588 return false;
2589 }
2590
2591 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2592 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002593 return false;
2594 }
2595
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002596 if (!CS.consumesDataArgument()) {
2597 // FIXME: Technically specifying a precision or field width here
2598 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002599 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002600 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002601
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002602 // Consume the argument.
2603 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00002604 if (argIndex < NumDataArgs) {
2605 // The check to see if the argIndex is valid will come later.
2606 // We set the bit here because we may exit early from this
2607 // function if we encounter some other error.
2608 CoveredArgs.set(argIndex);
2609 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002610
2611 // Check for using an Objective-C specific conversion specifier
2612 // in a non-ObjC literal.
Jordan Rose50687312012-06-04 23:52:23 +00002613 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002614 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2615 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002616 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002617
Tom Caree4ee9662010-06-17 19:00:27 +00002618 // Check for invalid use of field width
2619 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002620 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00002621 startSpecifier, specifierLen);
2622 }
2623
2624 // Check for invalid use of precision
2625 if (!FS.hasValidPrecision()) {
2626 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
2627 startSpecifier, specifierLen);
2628 }
2629
2630 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00002631 if (!FS.hasValidThousandsGroupingPrefix())
2632 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002633 if (!FS.hasValidLeadingZeros())
2634 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
2635 if (!FS.hasValidPlusPrefix())
2636 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00002637 if (!FS.hasValidSpacePrefix())
2638 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002639 if (!FS.hasValidAlternativeForm())
2640 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
2641 if (!FS.hasValidLeftJustified())
2642 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
2643
2644 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00002645 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
2646 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
2647 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002648 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
2649 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
2650 startSpecifier, specifierLen);
2651
2652 // Check the length modifier is valid with the given conversion specifier.
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002653 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose8be066e2012-09-08 04:00:12 +00002654 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
2655 diag::warn_format_nonsensical_length);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002656 else if (!FS.hasStandardLengthModifier())
Jordan Rose8be066e2012-09-08 04:00:12 +00002657 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002658 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose8be066e2012-09-08 04:00:12 +00002659 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
2660 diag::warn_format_non_standard_conversion_spec);
Tom Caree4ee9662010-06-17 19:00:27 +00002661
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002662 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
2663 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
2664
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002665 // The remaining checks depend on the data arguments.
2666 if (HasVAListArg)
2667 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002668
Ted Kremenek666a1972010-07-26 19:45:42 +00002669 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002670 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002671
Jordan Rose48716662012-07-19 18:10:08 +00002672 const Expr *Arg = getDataArg(argIndex);
2673 if (!Arg)
2674 return true;
2675
2676 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith831421f2012-06-25 20:30:08 +00002677}
2678
Jordan Roseec087352012-09-05 22:56:26 +00002679static bool requiresParensToAddCast(const Expr *E) {
2680 // FIXME: We should have a general way to reason about operator
2681 // precedence and whether parens are actually needed here.
2682 // Take care of a few common cases where they aren't.
2683 const Expr *Inside = E->IgnoreImpCasts();
2684 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
2685 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
2686
2687 switch (Inside->getStmtClass()) {
2688 case Stmt::ArraySubscriptExprClass:
2689 case Stmt::CallExprClass:
2690 case Stmt::DeclRefExprClass:
2691 case Stmt::MemberExprClass:
2692 case Stmt::ObjCIvarRefExprClass:
2693 case Stmt::ObjCMessageExprClass:
2694 case Stmt::ObjCPropertyRefExprClass:
2695 case Stmt::ParenExprClass:
2696 case Stmt::UnaryOperatorClass:
2697 return false;
2698 default:
2699 return true;
2700 }
2701}
2702
Richard Smith831421f2012-06-25 20:30:08 +00002703bool
2704CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2705 const char *StartSpecifier,
2706 unsigned SpecifierLen,
2707 const Expr *E) {
2708 using namespace analyze_format_string;
2709 using namespace analyze_printf;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002710 // Now type check the data expression that matches the
2711 // format specifier.
Hans Wennborgf3749f42012-08-07 08:11:26 +00002712 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
2713 ObjCContext);
Jordan Rose614a8652012-09-05 22:56:19 +00002714 if (!AT.isValid())
2715 return true;
Jordan Roseec087352012-09-05 22:56:26 +00002716
2717 QualType IntendedTy = E->getType();
2718 if (AT.matchesType(S.Context, IntendedTy))
Jordan Rose614a8652012-09-05 22:56:19 +00002719 return true;
Jordan Roseee0259d2012-06-04 22:48:57 +00002720
Jordan Rose614a8652012-09-05 22:56:19 +00002721 // Look through argument promotions for our error message's reported type.
2722 // This includes the integral and floating promotions, but excludes array
2723 // and function pointer decay; seeing that an argument intended to be a
2724 // string has type 'char [6]' is probably more confusing than 'char *'.
2725 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2726 if (ICE->getCastKind() == CK_IntegralCast ||
2727 ICE->getCastKind() == CK_FloatingCast) {
2728 E = ICE->getSubExpr();
Jordan Roseec087352012-09-05 22:56:26 +00002729 IntendedTy = E->getType();
Jordan Rose614a8652012-09-05 22:56:19 +00002730
2731 // Check if we didn't match because of an implicit cast from a 'char'
2732 // or 'short' to an 'int'. This is done because printf is a varargs
2733 // function.
2734 if (ICE->getType() == S.Context.IntTy ||
2735 ICE->getType() == S.Context.UnsignedIntTy) {
2736 // All further checking is done on the subexpression.
Jordan Roseec087352012-09-05 22:56:26 +00002737 if (AT.matchesType(S.Context, IntendedTy))
Jordan Rose614a8652012-09-05 22:56:19 +00002738 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00002739 }
Jordan Roseee0259d2012-06-04 22:48:57 +00002740 }
Jordan Rose614a8652012-09-05 22:56:19 +00002741 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002742
Jordan Roseec087352012-09-05 22:56:26 +00002743 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
2744 // Special-case some of Darwin's platform-independence types.
2745 if (const TypedefType *UserTy = IntendedTy->getAs<TypedefType>()) {
2746 StringRef Name = UserTy->getDecl()->getName();
2747 IntendedTy = llvm::StringSwitch<QualType>(Name)
2748 .Case("NSInteger", S.Context.LongTy)
2749 .Case("NSUInteger", S.Context.UnsignedLongTy)
2750 .Case("SInt32", S.Context.IntTy)
2751 .Case("UInt32", S.Context.UnsignedIntTy)
2752 .Default(IntendedTy);
2753 }
2754 }
2755
Jordan Rose614a8652012-09-05 22:56:19 +00002756 // We may be able to offer a FixItHint if it is a supported type.
2757 PrintfSpecifier fixedFS = FS;
Jordan Roseec087352012-09-05 22:56:26 +00002758 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose614a8652012-09-05 22:56:19 +00002759 S.Context, ObjCContext);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002760
Jordan Rose614a8652012-09-05 22:56:19 +00002761 if (success) {
2762 // Get the fix string from the fixed format specifier
2763 SmallString<16> buf;
2764 llvm::raw_svector_ostream os(buf);
2765 fixedFS.toString(os);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002766
Jordan Roseec087352012-09-05 22:56:26 +00002767 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
2768
2769 if (IntendedTy != E->getType()) {
2770 // The canonical type for formatting this value is different from the
2771 // actual type of the expression. (This occurs, for example, with Darwin's
2772 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
2773 // should be printed as 'long' for 64-bit compatibility.)
2774 // Rather than emitting a normal format/argument mismatch, we want to
2775 // add a cast to the recommended type (and correct the format string
2776 // if necessary).
2777 SmallString<16> CastBuf;
2778 llvm::raw_svector_ostream CastFix(CastBuf);
2779 CastFix << "(";
2780 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
2781 CastFix << ")";
2782
2783 SmallVector<FixItHint,4> Hints;
2784 if (!AT.matchesType(S.Context, IntendedTy))
2785 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
2786
2787 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
2788 // If there's already a cast present, just replace it.
2789 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
2790 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
2791
2792 } else if (!requiresParensToAddCast(E)) {
2793 // If the expression has high enough precedence,
2794 // just write the C-style cast.
2795 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
2796 CastFix.str()));
2797 } else {
2798 // Otherwise, add parens around the expression as well as the cast.
2799 CastFix << "(";
2800 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
2801 CastFix.str()));
2802
2803 SourceLocation After = S.PP.getLocForEndOfToken(E->getLocEnd());
2804 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
2805 }
2806
2807 // We extract the name from the typedef because we don't want to show
2808 // the underlying type in the diagnostic.
2809 const TypedefType *UserTy = cast<TypedefType>(E->getType());
2810 StringRef Name = UserTy->getDecl()->getName();
2811
2812 // Finally, emit the diagnostic.
2813 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
2814 << Name << IntendedTy
2815 << E->getSourceRange(),
2816 E->getLocStart(), /*IsStringLocation=*/false,
2817 SpecRange, Hints);
2818 } else {
2819 EmitFormatDiagnostic(
2820 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2821 << AT.getRepresentativeTypeName(S.Context) << IntendedTy
2822 << E->getSourceRange(),
2823 E->getLocStart(),
2824 /*IsStringLocation*/false,
2825 SpecRange,
2826 FixItHint::CreateReplacement(SpecRange, os.str()));
2827 }
Jordan Rose614a8652012-09-05 22:56:19 +00002828 } else {
2829 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
2830 SpecifierLen);
2831 // Since the warning for passing non-POD types to variadic functions
2832 // was deferred until now, we emit a warning for non-POD
2833 // arguments here.
2834 if (S.isValidVarArgType(E->getType()) == Sema::VAK_Invalid) {
2835 unsigned DiagKind;
2836 if (E->getType()->isObjCObjectType())
2837 DiagKind = diag::err_cannot_pass_objc_interface_to_vararg_format;
2838 else
2839 DiagKind = diag::warn_non_pod_vararg_with_format_string;
2840
2841 EmitFormatDiagnostic(
2842 S.PDiag(DiagKind)
2843 << S.getLangOpts().CPlusPlus0x
2844 << E->getType()
2845 << CallType
2846 << AT.getRepresentativeTypeName(S.Context)
2847 << CSR
2848 << E->getSourceRange(),
2849 E->getLocStart(), /*IsStringLocation*/false, CSR);
2850
2851 checkForCStrMembers(AT, E, CSR);
2852 } else
Richard Trieu55733de2011-10-28 00:41:25 +00002853 EmitFormatDiagnostic(
2854 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborgf3749f42012-08-07 08:11:26 +00002855 << AT.getRepresentativeTypeName(S.Context) << E->getType()
Jordan Rose614a8652012-09-05 22:56:19 +00002856 << CSR
Richard Smith831421f2012-06-25 20:30:08 +00002857 << E->getSourceRange(),
Jordan Rose614a8652012-09-05 22:56:19 +00002858 E->getLocStart(), /*IsStringLocation*/false, CSR);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002859 }
2860
Ted Kremeneke0e53132010-01-28 23:39:18 +00002861 return true;
2862}
2863
Ted Kremenek826a3452010-07-16 02:11:22 +00002864//===--- CHECK: Scanf format string checking ------------------------------===//
2865
2866namespace {
2867class CheckScanfHandler : public CheckFormatHandler {
2868public:
2869 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
2870 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002871 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002872 Expr **Args, unsigned NumArgs,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002873 unsigned formatIdx, bool inFunctionCall,
2874 Sema::VariadicCallType CallType)
Ted Kremenek826a3452010-07-16 02:11:22 +00002875 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002876 numDataArgs, beg, hasVAListArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002877 Args, NumArgs, formatIdx, inFunctionCall, CallType)
2878 {}
Ted Kremenek826a3452010-07-16 02:11:22 +00002879
2880 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
2881 const char *startSpecifier,
2882 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002883
2884 bool HandleInvalidScanfConversionSpecifier(
2885 const analyze_scanf::ScanfSpecifier &FS,
2886 const char *startSpecifier,
2887 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00002888
2889 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00002890};
Ted Kremenek07d161f2010-01-29 01:50:07 +00002891}
Ted Kremeneke0e53132010-01-28 23:39:18 +00002892
Ted Kremenekb7c21012010-07-16 18:28:03 +00002893void CheckScanfHandler::HandleIncompleteScanList(const char *start,
2894 const char *end) {
Richard Trieu55733de2011-10-28 00:41:25 +00002895 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
2896 getLocationOfByte(end), /*IsStringLocation*/true,
2897 getSpecifierRange(start, end - start));
Ted Kremenekb7c21012010-07-16 18:28:03 +00002898}
2899
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002900bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
2901 const analyze_scanf::ScanfSpecifier &FS,
2902 const char *startSpecifier,
2903 unsigned specifierLen) {
2904
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002905 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002906 FS.getConversionSpecifier();
2907
2908 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2909 getLocationOfByte(CS.getStart()),
2910 startSpecifier, specifierLen,
2911 CS.getStart(), CS.getLength());
2912}
2913
Ted Kremenek826a3452010-07-16 02:11:22 +00002914bool CheckScanfHandler::HandleScanfSpecifier(
2915 const analyze_scanf::ScanfSpecifier &FS,
2916 const char *startSpecifier,
2917 unsigned specifierLen) {
2918
2919 using namespace analyze_scanf;
2920 using namespace analyze_format_string;
2921
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002922 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002923
Ted Kremenekbaa40062010-07-19 22:01:06 +00002924 // Handle case where '%' and '*' don't consume an argument. These shouldn't
2925 // be used to decide if we are using positional arguments consistently.
2926 if (FS.consumesDataArgument()) {
2927 if (atFirstArg) {
2928 atFirstArg = false;
2929 usesPositionalArgs = FS.usesPositionalArg();
2930 }
2931 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002932 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2933 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002934 return false;
2935 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002936 }
2937
2938 // Check if the field with is non-zero.
2939 const OptionalAmount &Amt = FS.getFieldWidth();
2940 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
2941 if (Amt.getConstantAmount() == 0) {
2942 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
2943 Amt.getConstantLength());
Richard Trieu55733de2011-10-28 00:41:25 +00002944 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
2945 getLocationOfByte(Amt.getStart()),
2946 /*IsStringLocation*/true, R,
2947 FixItHint::CreateRemoval(R));
Ted Kremenek826a3452010-07-16 02:11:22 +00002948 }
2949 }
2950
2951 if (!FS.consumesDataArgument()) {
2952 // FIXME: Technically specifying a precision or field width here
2953 // makes no sense. Worth issuing a warning at some point.
2954 return true;
2955 }
2956
2957 // Consume the argument.
2958 unsigned argIndex = FS.getArgIndex();
2959 if (argIndex < NumDataArgs) {
2960 // The check to see if the argIndex is valid will come later.
2961 // We set the bit here because we may exit early from this
2962 // function if we encounter some other error.
2963 CoveredArgs.set(argIndex);
2964 }
2965
Ted Kremenek1e51c202010-07-20 20:04:47 +00002966 // Check the length modifier is valid with the given conversion specifier.
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002967 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose8be066e2012-09-08 04:00:12 +00002968 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
2969 diag::warn_format_nonsensical_length);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002970 else if (!FS.hasStandardLengthModifier())
Jordan Rose8be066e2012-09-08 04:00:12 +00002971 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002972 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose8be066e2012-09-08 04:00:12 +00002973 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
2974 diag::warn_format_non_standard_conversion_spec);
Hans Wennborg76517422012-02-22 10:17:01 +00002975
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002976 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
2977 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
2978
Ted Kremenek826a3452010-07-16 02:11:22 +00002979 // The remaining checks depend on the data arguments.
2980 if (HasVAListArg)
2981 return true;
2982
Ted Kremenek666a1972010-07-26 19:45:42 +00002983 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00002984 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00002985
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002986 // Check that the argument type matches the format specifier.
2987 const Expr *Ex = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00002988 if (!Ex)
2989 return true;
2990
Hans Wennborg58e1e542012-08-07 08:59:46 +00002991 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
2992 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002993 ScanfSpecifier fixedFS = FS;
David Blaikie4e4d0842012-03-11 07:00:24 +00002994 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
Hans Wennborgbe6126a2012-02-15 09:59:46 +00002995 S.Context);
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002996
2997 if (success) {
2998 // Get the fix string from the fixed format specifier.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002999 SmallString<128> buf;
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003000 llvm::raw_svector_ostream os(buf);
3001 fixedFS.toString(os);
3002
3003 EmitFormatDiagnostic(
3004 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg58e1e542012-08-07 08:59:46 +00003005 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003006 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00003007 Ex->getLocStart(),
3008 /*IsStringLocation*/false,
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003009 getSpecifierRange(startSpecifier, specifierLen),
3010 FixItHint::CreateReplacement(
3011 getSpecifierRange(startSpecifier, specifierLen),
3012 os.str()));
3013 } else {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003014 EmitFormatDiagnostic(
3015 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg58e1e542012-08-07 08:59:46 +00003016 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003017 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00003018 Ex->getLocStart(),
3019 /*IsStringLocation*/false,
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003020 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003021 }
3022 }
3023
Ted Kremenek826a3452010-07-16 02:11:22 +00003024 return true;
3025}
3026
3027void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00003028 const Expr *OrigFormatExpr,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003029 Expr **Args, unsigned NumArgs,
3030 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003031 unsigned firstDataArg, FormatStringType Type,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003032 bool inFunctionCall, VariadicCallType CallType) {
Ted Kremenek826a3452010-07-16 02:11:22 +00003033
Ted Kremeneke0e53132010-01-28 23:39:18 +00003034 // CHECK: is the format string a wide literal?
Richard Smithdf9ef1b2012-06-13 05:37:23 +00003035 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu55733de2011-10-28 00:41:25 +00003036 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003037 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00003038 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3039 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00003040 return;
3041 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003042
Ted Kremeneke0e53132010-01-28 23:39:18 +00003043 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner5f9e2722011-07-23 10:55:15 +00003044 StringRef StrRef = FExpr->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00003045 const char *Str = StrRef.data();
3046 unsigned StrLen = StrRef.size();
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003047 const unsigned numDataArgs = NumArgs - firstDataArg;
Ted Kremenek826a3452010-07-16 02:11:22 +00003048
Ted Kremeneke0e53132010-01-28 23:39:18 +00003049 // CHECK: empty format string?
Ted Kremenek4cd57912011-09-29 05:52:16 +00003050 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu55733de2011-10-28 00:41:25 +00003051 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003052 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00003053 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3054 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00003055 return;
3056 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003057
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003058 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek826a3452010-07-16 02:11:22 +00003059 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00003060 numDataArgs, (Type == FST_NSString),
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003061 Str, HasVAListArg, Args, NumArgs, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003062 inFunctionCall, CallType);
Ted Kremenek826a3452010-07-16 02:11:22 +00003063
Hans Wennborgd02deeb2011-12-15 10:25:47 +00003064 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose275b6f52012-09-13 02:11:03 +00003065 getLangOpts(),
3066 Context.getTargetInfo()))
Ted Kremenek826a3452010-07-16 02:11:22 +00003067 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003068 } else if (Type == FST_Scanf) {
Jordan Rose50687312012-06-04 23:52:23 +00003069 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003070 Str, HasVAListArg, Args, NumArgs, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003071 inFunctionCall, CallType);
Ted Kremenek826a3452010-07-16 02:11:22 +00003072
Hans Wennborgd02deeb2011-12-15 10:25:47 +00003073 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose275b6f52012-09-13 02:11:03 +00003074 getLangOpts(),
3075 Context.getTargetInfo()))
Ted Kremenek826a3452010-07-16 02:11:22 +00003076 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003077 } // TODO: handle other formats
Ted Kremenekce7024e2010-01-28 01:18:22 +00003078}
3079
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003080//===--- CHECK: Standard memory functions ---------------------------------===//
3081
Douglas Gregor2a053a32011-05-03 20:05:22 +00003082/// \brief Determine whether the given type is a dynamic class type (e.g.,
3083/// whether it has a vtable).
3084static bool isDynamicClassType(QualType T) {
3085 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3086 if (CXXRecordDecl *Definition = Record->getDefinition())
3087 if (Definition->isDynamicClass())
3088 return true;
3089
3090 return false;
3091}
3092
Chandler Carrutha72a12f2011-06-21 23:04:20 +00003093/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth000d4282011-06-16 09:09:40 +00003094/// otherwise returns NULL.
3095static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Webere4a1c642011-06-14 16:14:58 +00003096 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth000d4282011-06-16 09:09:40 +00003097 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3098 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
3099 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00003100
Chandler Carruth000d4282011-06-16 09:09:40 +00003101 return 0;
3102}
3103
Chandler Carrutha72a12f2011-06-21 23:04:20 +00003104/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth000d4282011-06-16 09:09:40 +00003105static QualType getSizeOfArgType(const Expr* E) {
3106 if (const UnaryExprOrTypeTraitExpr *SizeOf =
3107 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3108 if (SizeOf->getKind() == clang::UETT_SizeOf)
3109 return SizeOf->getTypeOfArgument();
3110
3111 return QualType();
Nico Webere4a1c642011-06-14 16:14:58 +00003112}
3113
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003114/// \brief Check for dangerous or invalid arguments to memset().
3115///
Chandler Carruth929f0132011-06-03 06:23:57 +00003116/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003117/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
3118/// function calls.
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003119///
3120/// \param Call The call expression to diagnose.
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003121void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks0a151a12012-01-17 00:37:07 +00003122 unsigned BId,
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003123 IdentifierInfo *FnName) {
Anna Zaks0a151a12012-01-17 00:37:07 +00003124 assert(BId != 0);
3125
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00003126 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor707a23e2011-06-16 17:56:04 +00003127 // we have enough arguments, and if not, abort further checking.
Anna Zaks0a151a12012-01-17 00:37:07 +00003128 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Webercda57822011-10-13 22:30:23 +00003129 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00003130 return;
3131
Anna Zaks0a151a12012-01-17 00:37:07 +00003132 unsigned LastArg = (BId == Builtin::BImemset ||
3133 BId == Builtin::BIstrndup ? 1 : 2);
3134 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Webercda57822011-10-13 22:30:23 +00003135 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth000d4282011-06-16 09:09:40 +00003136
3137 // We have special checking when the length is a sizeof expression.
3138 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
3139 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
3140 llvm::FoldingSetNodeID SizeOfArgID;
3141
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003142 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
3143 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00003144 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003145
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003146 QualType DestTy = Dest->getType();
3147 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
3148 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00003149
Chandler Carruth000d4282011-06-16 09:09:40 +00003150 // Never warn about void type pointers. This can be used to suppress
3151 // false positives.
3152 if (PointeeTy->isVoidType())
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003153 continue;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003154
Chandler Carruth000d4282011-06-16 09:09:40 +00003155 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
3156 // actually comparing the expressions for equality. Because computing the
3157 // expression IDs can be expensive, we only do this if the diagnostic is
3158 // enabled.
3159 if (SizeOfArg &&
3160 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
3161 SizeOfArg->getExprLoc())) {
3162 // We only compute IDs for expressions if the warning is enabled, and
3163 // cache the sizeof arg's ID.
3164 if (SizeOfArgID == llvm::FoldingSetNodeID())
3165 SizeOfArg->Profile(SizeOfArgID, Context, true);
3166 llvm::FoldingSetNodeID DestID;
3167 Dest->Profile(DestID, Context, true);
3168 if (DestID == SizeOfArgID) {
Nico Webercda57822011-10-13 22:30:23 +00003169 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
3170 // over sizeof(src) as well.
Chandler Carruth000d4282011-06-16 09:09:40 +00003171 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks6fcb3722012-05-30 00:34:21 +00003172 StringRef ReadableName = FnName->getName();
3173
Chandler Carruth000d4282011-06-16 09:09:40 +00003174 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaks90c78322012-05-30 23:14:52 +00003175 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth000d4282011-06-16 09:09:40 +00003176 ActionIdx = 1; // If its an address-of operator, just remove it.
3177 if (Context.getTypeSize(PointeeTy) == Context.getCharWidth())
3178 ActionIdx = 2; // If the pointee's size is sizeof(char),
3179 // suggest an explicit length.
Anna Zaks6fcb3722012-05-30 00:34:21 +00003180
3181 // If the function is defined as a builtin macro, do not show macro
3182 // expansion.
3183 SourceLocation SL = SizeOfArg->getExprLoc();
3184 SourceRange DSR = Dest->getSourceRange();
3185 SourceRange SSR = SizeOfArg->getSourceRange();
3186 SourceManager &SM = PP.getSourceManager();
3187
3188 if (SM.isMacroArgExpansion(SL)) {
3189 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
3190 SL = SM.getSpellingLoc(SL);
3191 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
3192 SM.getSpellingLoc(DSR.getEnd()));
3193 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
3194 SM.getSpellingLoc(SSR.getEnd()));
3195 }
3196
Anna Zaks90c78322012-05-30 23:14:52 +00003197 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth000d4282011-06-16 09:09:40 +00003198 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks6fcb3722012-05-30 00:34:21 +00003199 << ReadableName
Anna Zaks90c78322012-05-30 23:14:52 +00003200 << PointeeTy
3201 << DestTy
Anna Zaks6fcb3722012-05-30 00:34:21 +00003202 << DSR
Anna Zaks90c78322012-05-30 23:14:52 +00003203 << SSR);
3204 DiagRuntimeBehavior(SL, SizeOfArg,
3205 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
3206 << ActionIdx
3207 << SSR);
3208
Chandler Carruth000d4282011-06-16 09:09:40 +00003209 break;
3210 }
3211 }
3212
3213 // Also check for cases where the sizeof argument is the exact same
3214 // type as the memory argument, and where it points to a user-defined
3215 // record type.
3216 if (SizeOfArgTy != QualType()) {
3217 if (PointeeTy->isRecordType() &&
3218 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
3219 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
3220 PDiag(diag::warn_sizeof_pointer_type_memaccess)
3221 << FnName << SizeOfArgTy << ArgIdx
3222 << PointeeTy << Dest->getSourceRange()
3223 << LenExpr->getSourceRange());
3224 break;
3225 }
Nico Webere4a1c642011-06-14 16:14:58 +00003226 }
3227
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003228 // Always complain about dynamic classes.
Anna Zaks0a151a12012-01-17 00:37:07 +00003229 if (isDynamicClassType(PointeeTy)) {
3230
3231 unsigned OperationType = 0;
3232 // "overwritten" if we're warning about the destination for any call
3233 // but memcmp; otherwise a verb appropriate to the call.
3234 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
3235 if (BId == Builtin::BImemcpy)
3236 OperationType = 1;
3237 else if(BId == Builtin::BImemmove)
3238 OperationType = 2;
3239 else if (BId == Builtin::BImemcmp)
3240 OperationType = 3;
3241 }
3242
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003243 DiagRuntimeBehavior(
3244 Dest->getExprLoc(), Dest,
3245 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks0a151a12012-01-17 00:37:07 +00003246 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Anna Zaksd9b859a2012-01-13 21:52:01 +00003247 << FnName << PointeeTy
Anna Zaks0a151a12012-01-17 00:37:07 +00003248 << OperationType
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003249 << Call->getCallee()->getSourceRange());
Anna Zaks0a151a12012-01-17 00:37:07 +00003250 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
3251 BId != Builtin::BImemset)
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003252 DiagRuntimeBehavior(
3253 Dest->getExprLoc(), Dest,
3254 PDiag(diag::warn_arc_object_memaccess)
3255 << ArgIdx << FnName << PointeeTy
3256 << Call->getCallee()->getSourceRange());
John McCallf85e1932011-06-15 23:02:42 +00003257 else
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003258 continue;
John McCallf85e1932011-06-15 23:02:42 +00003259
3260 DiagRuntimeBehavior(
3261 Dest->getExprLoc(), Dest,
Chandler Carruth929f0132011-06-03 06:23:57 +00003262 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003263 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
3264 break;
3265 }
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003266 }
3267}
3268
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003269// A little helper routine: ignore addition and subtraction of integer literals.
3270// This intentionally does not ignore all integer constant expressions because
3271// we don't want to remove sizeof().
3272static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
3273 Ex = Ex->IgnoreParenCasts();
3274
3275 for (;;) {
3276 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
3277 if (!BO || !BO->isAdditiveOp())
3278 break;
3279
3280 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
3281 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
3282
3283 if (isa<IntegerLiteral>(RHS))
3284 Ex = LHS;
3285 else if (isa<IntegerLiteral>(LHS))
3286 Ex = RHS;
3287 else
3288 break;
3289 }
3290
3291 return Ex;
3292}
3293
Anna Zaks0f38ace2012-08-08 21:42:23 +00003294static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
3295 ASTContext &Context) {
3296 // Only handle constant-sized or VLAs, but not flexible members.
3297 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
3298 // Only issue the FIXIT for arrays of size > 1.
3299 if (CAT->getSize().getSExtValue() <= 1)
3300 return false;
3301 } else if (!Ty->isVariableArrayType()) {
3302 return false;
3303 }
3304 return true;
3305}
3306
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003307// Warn if the user has made the 'size' argument to strlcpy or strlcat
3308// be the size of the source, instead of the destination.
3309void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
3310 IdentifierInfo *FnName) {
3311
3312 // Don't crash if the user has the wrong number of arguments
3313 if (Call->getNumArgs() != 3)
3314 return;
3315
3316 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
3317 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
3318 const Expr *CompareWithSrc = NULL;
3319
3320 // Look for 'strlcpy(dst, x, sizeof(x))'
3321 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
3322 CompareWithSrc = Ex;
3323 else {
3324 // Look for 'strlcpy(dst, x, strlen(x))'
3325 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Richard Smith180f4792011-11-10 06:34:14 +00003326 if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003327 && SizeCall->getNumArgs() == 1)
3328 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
3329 }
3330 }
3331
3332 if (!CompareWithSrc)
3333 return;
3334
3335 // Determine if the argument to sizeof/strlen is equal to the source
3336 // argument. In principle there's all kinds of things you could do
3337 // here, for instance creating an == expression and evaluating it with
3338 // EvaluateAsBooleanCondition, but this uses a more direct technique:
3339 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
3340 if (!SrcArgDRE)
3341 return;
3342
3343 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
3344 if (!CompareWithSrcDRE ||
3345 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
3346 return;
3347
3348 const Expr *OriginalSizeArg = Call->getArg(2);
3349 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
3350 << OriginalSizeArg->getSourceRange() << FnName;
3351
3352 // Output a FIXIT hint if the destination is an array (rather than a
3353 // pointer to an array). This could be enhanced to handle some
3354 // pointers if we know the actual size, like if DstArg is 'array+2'
3355 // we could say 'sizeof(array)-2'.
3356 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks0f38ace2012-08-08 21:42:23 +00003357 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek8f746222011-08-18 22:48:41 +00003358 return;
Ted Kremenek8f746222011-08-18 22:48:41 +00003359
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003360 SmallString<128> sizeString;
Ted Kremenek8f746222011-08-18 22:48:41 +00003361 llvm::raw_svector_ostream OS(sizeString);
3362 OS << "sizeof(";
Richard Smithd1420c62012-08-16 03:56:14 +00003363 DstArg->printPretty(OS, 0, getPrintingPolicy());
Ted Kremenek8f746222011-08-18 22:48:41 +00003364 OS << ")";
3365
3366 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
3367 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
3368 OS.str());
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003369}
3370
Anna Zaksc36bedc2012-02-01 19:08:57 +00003371/// Check if two expressions refer to the same declaration.
3372static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
3373 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
3374 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
3375 return D1->getDecl() == D2->getDecl();
3376 return false;
3377}
3378
3379static const Expr *getStrlenExprArg(const Expr *E) {
3380 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
3381 const FunctionDecl *FD = CE->getDirectCallee();
3382 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
3383 return 0;
3384 return CE->getArg(0)->IgnoreParenCasts();
3385 }
3386 return 0;
3387}
3388
3389// Warn on anti-patterns as the 'size' argument to strncat.
3390// The correct size argument should look like following:
3391// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
3392void Sema::CheckStrncatArguments(const CallExpr *CE,
3393 IdentifierInfo *FnName) {
3394 // Don't crash if the user has the wrong number of arguments.
3395 if (CE->getNumArgs() < 3)
3396 return;
3397 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
3398 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
3399 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
3400
3401 // Identify common expressions, which are wrongly used as the size argument
3402 // to strncat and may lead to buffer overflows.
3403 unsigned PatternType = 0;
3404 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
3405 // - sizeof(dst)
3406 if (referToTheSameDecl(SizeOfArg, DstArg))
3407 PatternType = 1;
3408 // - sizeof(src)
3409 else if (referToTheSameDecl(SizeOfArg, SrcArg))
3410 PatternType = 2;
3411 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
3412 if (BE->getOpcode() == BO_Sub) {
3413 const Expr *L = BE->getLHS()->IgnoreParenCasts();
3414 const Expr *R = BE->getRHS()->IgnoreParenCasts();
3415 // - sizeof(dst) - strlen(dst)
3416 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
3417 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
3418 PatternType = 1;
3419 // - sizeof(src) - (anything)
3420 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
3421 PatternType = 2;
3422 }
3423 }
3424
3425 if (PatternType == 0)
3426 return;
3427
Anna Zaksafdb0412012-02-03 01:27:37 +00003428 // Generate the diagnostic.
3429 SourceLocation SL = LenArg->getLocStart();
3430 SourceRange SR = LenArg->getSourceRange();
3431 SourceManager &SM = PP.getSourceManager();
3432
3433 // If the function is defined as a builtin macro, do not show macro expansion.
3434 if (SM.isMacroArgExpansion(SL)) {
3435 SL = SM.getSpellingLoc(SL);
3436 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
3437 SM.getSpellingLoc(SR.getEnd()));
3438 }
3439
Anna Zaks0f38ace2012-08-08 21:42:23 +00003440 // Check if the destination is an array (rather than a pointer to an array).
3441 QualType DstTy = DstArg->getType();
3442 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
3443 Context);
3444 if (!isKnownSizeArray) {
3445 if (PatternType == 1)
3446 Diag(SL, diag::warn_strncat_wrong_size) << SR;
3447 else
3448 Diag(SL, diag::warn_strncat_src_size) << SR;
3449 return;
3450 }
3451
Anna Zaksc36bedc2012-02-01 19:08:57 +00003452 if (PatternType == 1)
Anna Zaksafdb0412012-02-03 01:27:37 +00003453 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003454 else
Anna Zaksafdb0412012-02-03 01:27:37 +00003455 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003456
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003457 SmallString<128> sizeString;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003458 llvm::raw_svector_ostream OS(sizeString);
3459 OS << "sizeof(";
Richard Smithd1420c62012-08-16 03:56:14 +00003460 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003461 OS << ") - ";
3462 OS << "strlen(";
Richard Smithd1420c62012-08-16 03:56:14 +00003463 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003464 OS << ") - 1";
3465
Anna Zaksafdb0412012-02-03 01:27:37 +00003466 Diag(SL, diag::note_strncat_wrong_size)
3467 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003468}
3469
Ted Kremenek06de2762007-08-17 16:46:58 +00003470//===--- CHECK: Return Address of Stack Variable --------------------------===//
3471
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003472static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3473 Decl *ParentDecl);
3474static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
3475 Decl *ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003476
3477/// CheckReturnStackAddr - Check if a return statement returns the address
3478/// of a stack variable.
3479void
3480Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
3481 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00003482
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003483 Expr *stackE = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003484 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003485
3486 // Perform checking for returned stack addresses, local blocks,
3487 // label addresses or references to temporaries.
John McCallf85e1932011-06-15 23:02:42 +00003488 if (lhsType->isPointerType() ||
David Blaikie4e4d0842012-03-11 07:00:24 +00003489 (!getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003490 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003491 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003492 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003493 }
3494
3495 if (stackE == 0)
3496 return; // Nothing suspicious was found.
3497
3498 SourceLocation diagLoc;
3499 SourceRange diagRange;
3500 if (refVars.empty()) {
3501 diagLoc = stackE->getLocStart();
3502 diagRange = stackE->getSourceRange();
3503 } else {
3504 // We followed through a reference variable. 'stackE' contains the
3505 // problematic expression but we will warn at the return statement pointing
3506 // at the reference variable. We will later display the "trail" of
3507 // reference variables using notes.
3508 diagLoc = refVars[0]->getLocStart();
3509 diagRange = refVars[0]->getSourceRange();
3510 }
3511
3512 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
3513 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
3514 : diag::warn_ret_stack_addr)
3515 << DR->getDecl()->getDeclName() << diagRange;
3516 } else if (isa<BlockExpr>(stackE)) { // local block.
3517 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
3518 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
3519 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
3520 } else { // local temporary.
3521 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
3522 : diag::warn_ret_local_temp_addr)
3523 << diagRange;
3524 }
3525
3526 // Display the "trail" of reference variables that we followed until we
3527 // found the problematic expression using notes.
3528 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
3529 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
3530 // If this var binds to another reference var, show the range of the next
3531 // var, otherwise the var binds to the problematic expression, in which case
3532 // show the range of the expression.
3533 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
3534 : stackE->getSourceRange();
3535 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
3536 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00003537 }
3538}
3539
3540/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
3541/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003542/// to a location on the stack, a local block, an address of a label, or a
3543/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00003544/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003545/// encounter a subexpression that (1) clearly does not lead to one of the
3546/// above problematic expressions (2) is something we cannot determine leads to
3547/// a problematic expression based on such local checking.
3548///
3549/// Both EvalAddr and EvalVal follow through reference variables to evaluate
3550/// the expression that they point to. Such variables are added to the
3551/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00003552///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00003553/// EvalAddr processes expressions that are pointers that are used as
3554/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003555/// At the base case of the recursion is a check for the above problematic
3556/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00003557///
3558/// This implementation handles:
3559///
3560/// * pointer-to-pointer casts
3561/// * implicit conversions from array references to pointers
3562/// * taking the address of fields
3563/// * arbitrary interplay between "&" and "*" operators
3564/// * pointer arithmetic from an address of a stack variable
3565/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003566static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3567 Decl *ParentDecl) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003568 if (E->isTypeDependent())
3569 return NULL;
3570
Ted Kremenek06de2762007-08-17 16:46:58 +00003571 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00003572 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00003573 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003574 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003575 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00003576
Peter Collingbournef111d932011-04-15 00:35:48 +00003577 E = E->IgnoreParens();
3578
Ted Kremenek06de2762007-08-17 16:46:58 +00003579 // Our "symbolic interpreter" is just a dispatch off the currently
3580 // viewed AST node. We then recursively traverse the AST by calling
3581 // EvalAddr and EvalVal appropriately.
3582 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003583 case Stmt::DeclRefExprClass: {
3584 DeclRefExpr *DR = cast<DeclRefExpr>(E);
3585
3586 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
3587 // If this is a reference variable, follow through to the expression that
3588 // it points to.
3589 if (V->hasLocalStorage() &&
3590 V->getType()->isReferenceType() && V->hasInit()) {
3591 // Add the reference variable to the "trail".
3592 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003593 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003594 }
3595
3596 return NULL;
3597 }
Ted Kremenek06de2762007-08-17 16:46:58 +00003598
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003599 case Stmt::UnaryOperatorClass: {
3600 // The only unary operator that make sense to handle here
3601 // is AddrOf. All others don't make sense as pointers.
3602 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003603
John McCall2de56d12010-08-25 11:45:40 +00003604 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003605 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003606 else
Ted Kremenek06de2762007-08-17 16:46:58 +00003607 return NULL;
3608 }
Mike Stump1eb44332009-09-09 15:08:12 +00003609
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003610 case Stmt::BinaryOperatorClass: {
3611 // Handle pointer arithmetic. All other binary operators are not valid
3612 // in this context.
3613 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00003614 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00003615
John McCall2de56d12010-08-25 11:45:40 +00003616 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003617 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00003618
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003619 Expr *Base = B->getLHS();
3620
3621 // Determine which argument is the real pointer base. It could be
3622 // the RHS argument instead of the LHS.
3623 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00003624
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003625 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003626 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003627 }
Steve Naroff61f40a22008-09-10 19:17:48 +00003628
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003629 // For conditional operators we need to see if either the LHS or RHS are
3630 // valid DeclRefExpr*s. If one of them is valid, we return it.
3631 case Stmt::ConditionalOperatorClass: {
3632 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003633
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003634 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003635 if (Expr *lhsExpr = C->getLHS()) {
3636 // In C++, we can have a throw-expression, which has 'void' type.
3637 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003638 if (Expr* LHS = EvalAddr(lhsExpr, refVars, ParentDecl))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003639 return LHS;
3640 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003641
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003642 // In C++, we can have a throw-expression, which has 'void' type.
3643 if (C->getRHS()->getType()->isVoidType())
3644 return NULL;
3645
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003646 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003647 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003648
3649 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00003650 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003651 return E; // local block.
3652 return NULL;
3653
3654 case Stmt::AddrLabelExprClass:
3655 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00003656
John McCall80ee6e82011-11-10 05:35:25 +00003657 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003658 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
3659 ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00003660
Ted Kremenek54b52742008-08-07 00:49:01 +00003661 // For casts, we need to handle conversions from arrays to
3662 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00003663 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00003664 case Stmt::CStyleCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00003665 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8b9414e2012-02-23 23:04:32 +00003666 case Stmt::ObjCBridgedCastExprClass:
Mike Stump1eb44332009-09-09 15:08:12 +00003667 case Stmt::CXXStaticCastExprClass:
3668 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00003669 case Stmt::CXXConstCastExprClass:
3670 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8b9414e2012-02-23 23:04:32 +00003671 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
3672 switch (cast<CastExpr>(E)->getCastKind()) {
3673 case CK_BitCast:
3674 case CK_LValueToRValue:
3675 case CK_NoOp:
3676 case CK_BaseToDerived:
3677 case CK_DerivedToBase:
3678 case CK_UncheckedDerivedToBase:
3679 case CK_Dynamic:
3680 case CK_CPointerToObjCPointerCast:
3681 case CK_BlockPointerToObjCPointerCast:
3682 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003683 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00003684
3685 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003686 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00003687
3688 default:
3689 return 0;
3690 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003691 }
Mike Stump1eb44332009-09-09 15:08:12 +00003692
Douglas Gregor03e80032011-06-21 17:03:29 +00003693 case Stmt::MaterializeTemporaryExprClass:
3694 if (Expr *Result = EvalAddr(
3695 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003696 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00003697 return Result;
3698
3699 return E;
3700
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003701 // Everything else: we simply don't reason about them.
3702 default:
3703 return NULL;
3704 }
Ted Kremenek06de2762007-08-17 16:46:58 +00003705}
Mike Stump1eb44332009-09-09 15:08:12 +00003706
Ted Kremenek06de2762007-08-17 16:46:58 +00003707
3708/// EvalVal - This function is complements EvalAddr in the mutual recursion.
3709/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003710static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3711 Decl *ParentDecl) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003712do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00003713 // We should only be called for evaluating non-pointer expressions, or
3714 // expressions with a pointer type that are not used as references but instead
3715 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00003716
Ted Kremenek06de2762007-08-17 16:46:58 +00003717 // Our "symbolic interpreter" is just a dispatch off the currently
3718 // viewed AST node. We then recursively traverse the AST by calling
3719 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00003720
3721 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00003722 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003723 case Stmt::ImplicitCastExprClass: {
3724 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00003725 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003726 E = IE->getSubExpr();
3727 continue;
3728 }
3729 return NULL;
3730 }
3731
John McCall80ee6e82011-11-10 05:35:25 +00003732 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003733 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00003734
Douglas Gregora2813ce2009-10-23 18:54:35 +00003735 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003736 // When we hit a DeclRefExpr we are looking at code that refers to a
3737 // variable's name. If it's not a reference variable we check if it has
3738 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00003739 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003740
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003741 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
3742 // Check if it refers to itself, e.g. "int& i = i;".
3743 if (V == ParentDecl)
3744 return DR;
3745
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003746 if (V->hasLocalStorage()) {
3747 if (!V->getType()->isReferenceType())
3748 return DR;
3749
3750 // Reference variable, follow through to the expression that
3751 // it points to.
3752 if (V->hasInit()) {
3753 // Add the reference variable to the "trail".
3754 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003755 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003756 }
3757 }
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003758 }
Mike Stump1eb44332009-09-09 15:08:12 +00003759
Ted Kremenek06de2762007-08-17 16:46:58 +00003760 return NULL;
3761 }
Mike Stump1eb44332009-09-09 15:08:12 +00003762
Ted Kremenek06de2762007-08-17 16:46:58 +00003763 case Stmt::UnaryOperatorClass: {
3764 // The only unary operator that make sense to handle here
3765 // is Deref. All others don't resolve to a "name." This includes
3766 // handling all sorts of rvalues passed to a unary operator.
3767 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003768
John McCall2de56d12010-08-25 11:45:40 +00003769 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003770 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003771
3772 return NULL;
3773 }
Mike Stump1eb44332009-09-09 15:08:12 +00003774
Ted Kremenek06de2762007-08-17 16:46:58 +00003775 case Stmt::ArraySubscriptExprClass: {
3776 // Array subscripts are potential references to data on the stack. We
3777 // retrieve the DeclRefExpr* for the array variable if it indeed
3778 // has local storage.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003779 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003780 }
Mike Stump1eb44332009-09-09 15:08:12 +00003781
Ted Kremenek06de2762007-08-17 16:46:58 +00003782 case Stmt::ConditionalOperatorClass: {
3783 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003784 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00003785 ConditionalOperator *C = cast<ConditionalOperator>(E);
3786
Anders Carlsson39073232007-11-30 19:04:31 +00003787 // Handle the GNU extension for missing LHS.
3788 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003789 if (Expr *LHS = EvalVal(lhsExpr, refVars, ParentDecl))
Anders Carlsson39073232007-11-30 19:04:31 +00003790 return LHS;
3791
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003792 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003793 }
Mike Stump1eb44332009-09-09 15:08:12 +00003794
Ted Kremenek06de2762007-08-17 16:46:58 +00003795 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00003796 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00003797 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003798
Ted Kremenek06de2762007-08-17 16:46:58 +00003799 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00003800 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00003801 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00003802
3803 // Check whether the member type is itself a reference, in which case
3804 // we're not going to refer to the member, but to what the member refers to.
3805 if (M->getMemberDecl()->getType()->isReferenceType())
3806 return NULL;
3807
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003808 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003809 }
Mike Stump1eb44332009-09-09 15:08:12 +00003810
Douglas Gregor03e80032011-06-21 17:03:29 +00003811 case Stmt::MaterializeTemporaryExprClass:
3812 if (Expr *Result = EvalVal(
3813 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003814 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00003815 return Result;
3816
3817 return E;
3818
Ted Kremenek06de2762007-08-17 16:46:58 +00003819 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003820 // Check that we don't return or take the address of a reference to a
3821 // temporary. This is only useful in C++.
3822 if (!E->isTypeDependent() && E->isRValue())
3823 return E;
3824
3825 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00003826 return NULL;
3827 }
Ted Kremenek68957a92010-08-04 20:01:07 +00003828} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00003829}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003830
3831//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
3832
3833/// Check for comparisons of floating point operands using != and ==.
3834/// Issue a warning if these are no self-comparisons, as they are not likely
3835/// to do what the programmer intended.
Richard Trieudd225092011-09-15 21:56:47 +00003836void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieudd225092011-09-15 21:56:47 +00003837 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
3838 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003839
3840 // Special case: check for x == x (which is OK).
3841 // Do not emit warnings for such cases.
3842 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
3843 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
3844 if (DRL->getDecl() == DRR->getDecl())
David Blaikie980343b2012-07-16 20:47:22 +00003845 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003846
3847
Ted Kremenek1b500bb2007-11-29 00:59:04 +00003848 // Special case: check for comparisons against literals that can be exactly
3849 // represented by APFloat. In such cases, do not emit a warning. This
3850 // is a heuristic: often comparison against such literals are used to
3851 // detect if a value in a variable has not changed. This clearly can
3852 // lead to false negatives.
David Blaikie980343b2012-07-16 20:47:22 +00003853 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
3854 if (FLL->isExact())
3855 return;
3856 } else
3857 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
3858 if (FLR->isExact())
3859 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003860
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003861 // Check for comparisons with builtin types.
David Blaikie980343b2012-07-16 20:47:22 +00003862 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
3863 if (CL->isBuiltinCall())
3864 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003865
David Blaikie980343b2012-07-16 20:47:22 +00003866 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
3867 if (CR->isBuiltinCall())
3868 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003869
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003870 // Emit the diagnostic.
David Blaikie980343b2012-07-16 20:47:22 +00003871 Diag(Loc, diag::warn_floatingpoint_eq)
3872 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003873}
John McCallba26e582010-01-04 23:21:16 +00003874
John McCallf2370c92010-01-06 05:24:50 +00003875//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
3876//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00003877
John McCallf2370c92010-01-06 05:24:50 +00003878namespace {
John McCallba26e582010-01-04 23:21:16 +00003879
John McCallf2370c92010-01-06 05:24:50 +00003880/// Structure recording the 'active' range of an integer-valued
3881/// expression.
3882struct IntRange {
3883 /// The number of bits active in the int.
3884 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00003885
John McCallf2370c92010-01-06 05:24:50 +00003886 /// True if the int is known not to have negative values.
3887 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00003888
John McCallf2370c92010-01-06 05:24:50 +00003889 IntRange(unsigned Width, bool NonNegative)
3890 : Width(Width), NonNegative(NonNegative)
3891 {}
John McCallba26e582010-01-04 23:21:16 +00003892
John McCall1844a6e2010-11-10 23:38:19 +00003893 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00003894 static IntRange forBoolType() {
3895 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00003896 }
3897
John McCall1844a6e2010-11-10 23:38:19 +00003898 /// Returns the range of an opaque value of the given integral type.
3899 static IntRange forValueOfType(ASTContext &C, QualType T) {
3900 return forValueOfCanonicalType(C,
3901 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00003902 }
3903
John McCall1844a6e2010-11-10 23:38:19 +00003904 /// Returns the range of an opaque value of a canonical integral type.
3905 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00003906 assert(T->isCanonicalUnqualified());
3907
3908 if (const VectorType *VT = dyn_cast<VectorType>(T))
3909 T = VT->getElementType().getTypePtr();
3910 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
3911 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00003912
John McCall091f23f2010-11-09 22:22:12 +00003913 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00003914 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
3915 EnumDecl *Enum = ET->getDecl();
John McCall5e1cdac2011-10-07 06:10:15 +00003916 if (!Enum->isCompleteDefinition())
John McCall091f23f2010-11-09 22:22:12 +00003917 return IntRange(C.getIntWidth(QualType(T, 0)), false);
3918
John McCall323ed742010-05-06 08:58:33 +00003919 unsigned NumPositive = Enum->getNumPositiveBits();
3920 unsigned NumNegative = Enum->getNumNegativeBits();
3921
3922 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
3923 }
John McCallf2370c92010-01-06 05:24:50 +00003924
3925 const BuiltinType *BT = cast<BuiltinType>(T);
3926 assert(BT->isInteger());
3927
3928 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
3929 }
3930
John McCall1844a6e2010-11-10 23:38:19 +00003931 /// Returns the "target" range of a canonical integral type, i.e.
3932 /// the range of values expressible in the type.
3933 ///
3934 /// This matches forValueOfCanonicalType except that enums have the
3935 /// full range of their type, not the range of their enumerators.
3936 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
3937 assert(T->isCanonicalUnqualified());
3938
3939 if (const VectorType *VT = dyn_cast<VectorType>(T))
3940 T = VT->getElementType().getTypePtr();
3941 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
3942 T = CT->getElementType().getTypePtr();
3943 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor69ff26b2011-09-08 23:29:05 +00003944 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall1844a6e2010-11-10 23:38:19 +00003945
3946 const BuiltinType *BT = cast<BuiltinType>(T);
3947 assert(BT->isInteger());
3948
3949 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
3950 }
3951
3952 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00003953 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00003954 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00003955 L.NonNegative && R.NonNegative);
3956 }
3957
John McCall1844a6e2010-11-10 23:38:19 +00003958 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00003959 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00003960 return IntRange(std::min(L.Width, R.Width),
3961 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00003962 }
3963};
3964
Ted Kremenek0692a192012-01-31 05:37:37 +00003965static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
3966 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00003967 if (value.isSigned() && value.isNegative())
3968 return IntRange(value.getMinSignedBits(), false);
3969
3970 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00003971 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00003972
3973 // isNonNegative() just checks the sign bit without considering
3974 // signedness.
3975 return IntRange(value.getActiveBits(), true);
3976}
3977
Ted Kremenek0692a192012-01-31 05:37:37 +00003978static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
3979 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00003980 if (result.isInt())
3981 return GetValueRange(C, result.getInt(), MaxWidth);
3982
3983 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00003984 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
3985 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
3986 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
3987 R = IntRange::join(R, El);
3988 }
John McCallf2370c92010-01-06 05:24:50 +00003989 return R;
3990 }
3991
3992 if (result.isComplexInt()) {
3993 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
3994 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
3995 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00003996 }
3997
3998 // This can happen with lossless casts to intptr_t of "based" lvalues.
3999 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00004000 // FIXME: The only reason we need to pass the type in here is to get
4001 // the sign right on this one case. It would be nice if APValue
4002 // preserved this.
Eli Friedman65639282012-01-04 23:13:47 +00004003 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00004004 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall51313c32010-01-04 23:31:57 +00004005}
John McCallf2370c92010-01-06 05:24:50 +00004006
4007/// Pseudo-evaluate the given integer expression, estimating the
4008/// range of values it might take.
4009///
4010/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek0692a192012-01-31 05:37:37 +00004011static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004012 E = E->IgnoreParens();
4013
4014 // Try a full evaluation first.
4015 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00004016 if (E->EvaluateAsRValue(result, C))
John McCall0acc3112010-01-06 22:57:21 +00004017 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00004018
4019 // I think we only want to look through implicit casts here; if the
4020 // user has an explicit widening cast, we should treat the value as
4021 // being of the new, wider type.
4022 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedmanb17ee5b2011-12-15 02:41:52 +00004023 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCallf2370c92010-01-06 05:24:50 +00004024 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
4025
John McCall1844a6e2010-11-10 23:38:19 +00004026 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCallf2370c92010-01-06 05:24:50 +00004027
John McCall2de56d12010-08-25 11:45:40 +00004028 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00004029
John McCallf2370c92010-01-06 05:24:50 +00004030 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00004031 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00004032 return OutputTypeRange;
4033
4034 IntRange SubRange
4035 = GetExprRange(C, CE->getSubExpr(),
4036 std::min(MaxWidth, OutputTypeRange.Width));
4037
4038 // Bail out if the subexpr's range is as wide as the cast type.
4039 if (SubRange.Width >= OutputTypeRange.Width)
4040 return OutputTypeRange;
4041
4042 // Otherwise, we take the smaller width, and we're non-negative if
4043 // either the output type or the subexpr is.
4044 return IntRange(SubRange.Width,
4045 SubRange.NonNegative || OutputTypeRange.NonNegative);
4046 }
4047
4048 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4049 // If we can fold the condition, just take that operand.
4050 bool CondResult;
4051 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
4052 return GetExprRange(C, CondResult ? CO->getTrueExpr()
4053 : CO->getFalseExpr(),
4054 MaxWidth);
4055
4056 // Otherwise, conservatively merge.
4057 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
4058 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
4059 return IntRange::join(L, R);
4060 }
4061
4062 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4063 switch (BO->getOpcode()) {
4064
4065 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00004066 case BO_LAnd:
4067 case BO_LOr:
4068 case BO_LT:
4069 case BO_GT:
4070 case BO_LE:
4071 case BO_GE:
4072 case BO_EQ:
4073 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00004074 return IntRange::forBoolType();
4075
John McCall862ff872011-07-13 06:35:24 +00004076 // The type of the assignments is the type of the LHS, so the RHS
4077 // is not necessarily the same type.
John McCall2de56d12010-08-25 11:45:40 +00004078 case BO_MulAssign:
4079 case BO_DivAssign:
4080 case BO_RemAssign:
4081 case BO_AddAssign:
4082 case BO_SubAssign:
John McCall862ff872011-07-13 06:35:24 +00004083 case BO_XorAssign:
4084 case BO_OrAssign:
4085 // TODO: bitfields?
John McCall1844a6e2010-11-10 23:38:19 +00004086 return IntRange::forValueOfType(C, E->getType());
John McCallc0cd21d2010-02-23 19:22:29 +00004087
John McCall862ff872011-07-13 06:35:24 +00004088 // Simple assignments just pass through the RHS, which will have
4089 // been coerced to the LHS type.
4090 case BO_Assign:
4091 // TODO: bitfields?
4092 return GetExprRange(C, BO->getRHS(), MaxWidth);
4093
John McCallf2370c92010-01-06 05:24:50 +00004094 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00004095 case BO_PtrMemD:
4096 case BO_PtrMemI:
John McCall1844a6e2010-11-10 23:38:19 +00004097 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00004098
John McCall60fad452010-01-06 22:07:33 +00004099 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00004100 case BO_And:
4101 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00004102 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
4103 GetExprRange(C, BO->getRHS(), MaxWidth));
4104
John McCallf2370c92010-01-06 05:24:50 +00004105 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00004106 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00004107 // ...except that we want to treat '1 << (blah)' as logically
4108 // positive. It's an important idiom.
4109 if (IntegerLiteral *I
4110 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
4111 if (I->getValue() == 1) {
John McCall1844a6e2010-11-10 23:38:19 +00004112 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall3aae6092010-04-07 01:14:35 +00004113 return IntRange(R.Width, /*NonNegative*/ true);
4114 }
4115 }
4116 // fallthrough
4117
John McCall2de56d12010-08-25 11:45:40 +00004118 case BO_ShlAssign:
John McCall1844a6e2010-11-10 23:38:19 +00004119 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00004120
John McCall60fad452010-01-06 22:07:33 +00004121 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00004122 case BO_Shr:
4123 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00004124 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4125
4126 // If the shift amount is a positive constant, drop the width by
4127 // that much.
4128 llvm::APSInt shift;
4129 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
4130 shift.isNonNegative()) {
4131 unsigned zext = shift.getZExtValue();
4132 if (zext >= L.Width)
4133 L.Width = (L.NonNegative ? 0 : 1);
4134 else
4135 L.Width -= zext;
4136 }
4137
4138 return L;
4139 }
4140
4141 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00004142 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00004143 return GetExprRange(C, BO->getRHS(), MaxWidth);
4144
John McCall60fad452010-01-06 22:07:33 +00004145 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00004146 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00004147 if (BO->getLHS()->getType()->isPointerType())
John McCall1844a6e2010-11-10 23:38:19 +00004148 return IntRange::forValueOfType(C, E->getType());
John McCall00fe7612011-07-14 22:39:48 +00004149 break;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00004150
John McCall00fe7612011-07-14 22:39:48 +00004151 // The width of a division result is mostly determined by the size
4152 // of the LHS.
4153 case BO_Div: {
4154 // Don't 'pre-truncate' the operands.
4155 unsigned opWidth = C.getIntWidth(E->getType());
4156 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4157
4158 // If the divisor is constant, use that.
4159 llvm::APSInt divisor;
4160 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
4161 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
4162 if (log2 >= L.Width)
4163 L.Width = (L.NonNegative ? 0 : 1);
4164 else
4165 L.Width = std::min(L.Width - log2, MaxWidth);
4166 return L;
4167 }
4168
4169 // Otherwise, just use the LHS's width.
4170 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4171 return IntRange(L.Width, L.NonNegative && R.NonNegative);
4172 }
4173
4174 // The result of a remainder can't be larger than the result of
4175 // either side.
4176 case BO_Rem: {
4177 // Don't 'pre-truncate' the operands.
4178 unsigned opWidth = C.getIntWidth(E->getType());
4179 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4180 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4181
4182 IntRange meet = IntRange::meet(L, R);
4183 meet.Width = std::min(meet.Width, MaxWidth);
4184 return meet;
4185 }
4186
4187 // The default behavior is okay for these.
4188 case BO_Mul:
4189 case BO_Add:
4190 case BO_Xor:
4191 case BO_Or:
John McCallf2370c92010-01-06 05:24:50 +00004192 break;
4193 }
4194
John McCall00fe7612011-07-14 22:39:48 +00004195 // The default case is to treat the operation as if it were closed
4196 // on the narrowest type that encompasses both operands.
John McCallf2370c92010-01-06 05:24:50 +00004197 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4198 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
4199 return IntRange::join(L, R);
4200 }
4201
4202 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
4203 switch (UO->getOpcode()) {
4204 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00004205 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00004206 return IntRange::forBoolType();
4207
4208 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00004209 case UO_Deref:
4210 case UO_AddrOf: // should be impossible
John McCall1844a6e2010-11-10 23:38:19 +00004211 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00004212
4213 default:
4214 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
4215 }
4216 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004217
4218 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall1844a6e2010-11-10 23:38:19 +00004219 IntRange::forValueOfType(C, E->getType());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004220 }
John McCallf2370c92010-01-06 05:24:50 +00004221
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004222 if (FieldDecl *BitField = E->getBitField())
4223 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00004224 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00004225
John McCall1844a6e2010-11-10 23:38:19 +00004226 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00004227}
John McCall51313c32010-01-04 23:31:57 +00004228
Ted Kremenek0692a192012-01-31 05:37:37 +00004229static IntRange GetExprRange(ASTContext &C, Expr *E) {
John McCall323ed742010-05-06 08:58:33 +00004230 return GetExprRange(C, E, C.getIntWidth(E->getType()));
4231}
4232
John McCall51313c32010-01-04 23:31:57 +00004233/// Checks whether the given value, which currently has the given
4234/// source semantics, has the same value when coerced through the
4235/// target semantics.
Ted Kremenek0692a192012-01-31 05:37:37 +00004236static bool IsSameFloatAfterCast(const llvm::APFloat &value,
4237 const llvm::fltSemantics &Src,
4238 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00004239 llvm::APFloat truncated = value;
4240
4241 bool ignored;
4242 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
4243 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
4244
4245 return truncated.bitwiseIsEqual(value);
4246}
4247
4248/// Checks whether the given value, which currently has the given
4249/// source semantics, has the same value when coerced through the
4250/// target semantics.
4251///
4252/// The value might be a vector of floats (or a complex number).
Ted Kremenek0692a192012-01-31 05:37:37 +00004253static bool IsSameFloatAfterCast(const APValue &value,
4254 const llvm::fltSemantics &Src,
4255 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00004256 if (value.isFloat())
4257 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
4258
4259 if (value.isVector()) {
4260 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
4261 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
4262 return false;
4263 return true;
4264 }
4265
4266 assert(value.isComplexFloat());
4267 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
4268 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
4269}
4270
Ted Kremenek0692a192012-01-31 05:37:37 +00004271static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00004272
Ted Kremeneke3b159c2010-09-23 21:43:44 +00004273static bool IsZero(Sema &S, Expr *E) {
4274 // Suppress cases where we are comparing against an enum constant.
4275 if (const DeclRefExpr *DR =
4276 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
4277 if (isa<EnumConstantDecl>(DR->getDecl()))
4278 return false;
4279
4280 // Suppress cases where the '0' value is expanded from a macro.
4281 if (E->getLocStart().isMacroID())
4282 return false;
4283
John McCall323ed742010-05-06 08:58:33 +00004284 llvm::APSInt Value;
4285 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
4286}
4287
John McCall372e1032010-10-06 00:25:24 +00004288static bool HasEnumType(Expr *E) {
4289 // Strip off implicit integral promotions.
4290 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00004291 if (ICE->getCastKind() != CK_IntegralCast &&
4292 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00004293 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00004294 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00004295 }
4296
4297 return E->getType()->isEnumeralType();
4298}
4299
Ted Kremenek0692a192012-01-31 05:37:37 +00004300static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00004301 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00004302 if (E->isValueDependent())
4303 return;
4304
John McCall2de56d12010-08-25 11:45:40 +00004305 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00004306 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004307 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00004308 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004309 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00004310 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004311 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00004312 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004313 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00004314 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004315 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00004316 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004317 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00004318 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004319 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00004320 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4321 }
4322}
4323
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004324static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004325 Expr *Constant, Expr *Other,
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004326 llvm::APSInt Value,
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004327 bool RhsConstant) {
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004328 BinaryOperatorKind op = E->getOpcode();
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004329 QualType OtherT = Other->getType();
4330 QualType ConstantT = Constant->getType();
4331 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004332 return;
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004333 assert((OtherT->isIntegerType() && ConstantT->isIntegerType())
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004334 && "comparison with non-integer type");
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004335 // FIXME. handle cases for signedness to catch (signed char)N == 200
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004336 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004337 IntRange LitRange = GetValueRange(S.Context, Value, Value.getBitWidth());
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004338 if (OtherRange.Width >= LitRange.Width)
4339 return;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004340 bool IsTrue = true;
4341 if (op == BO_EQ)
4342 IsTrue = false;
4343 else if (op == BO_NE)
4344 IsTrue = true;
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004345 else if (RhsConstant) {
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004346 if (op == BO_GT || op == BO_GE)
4347 IsTrue = !LitRange.NonNegative;
4348 else // op == BO_LT || op == BO_LE
4349 IsTrue = LitRange.NonNegative;
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004350 } else {
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004351 if (op == BO_LT || op == BO_LE)
4352 IsTrue = !LitRange.NonNegative;
4353 else // op == BO_GT || op == BO_GE
4354 IsTrue = LitRange.NonNegative;
4355 }
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004356 SmallString<16> PrettySourceValue(Value.toString(10));
4357 S.Diag(E->getOperatorLoc(), diag::warn_out_of_range_compare)
4358 << PrettySourceValue << OtherT << IsTrue
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004359 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4360}
4361
John McCall323ed742010-05-06 08:58:33 +00004362/// Analyze the operands of the given comparison. Implements the
4363/// fallback case from AnalyzeComparison.
Ted Kremenek0692a192012-01-31 05:37:37 +00004364static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00004365 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4366 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00004367}
John McCall51313c32010-01-04 23:31:57 +00004368
John McCallba26e582010-01-04 23:21:16 +00004369/// \brief Implements -Wsign-compare.
4370///
Richard Trieudd225092011-09-15 21:56:47 +00004371/// \param E the binary operator to check for warnings
Ted Kremenek0692a192012-01-31 05:37:37 +00004372static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCall323ed742010-05-06 08:58:33 +00004373 // The type the comparison is being performed in.
4374 QualType T = E->getLHS()->getType();
4375 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
4376 && "comparison with mismatched types");
Fariborz Jahanianab4702f2012-09-18 17:46:26 +00004377 if (E->isValueDependent())
4378 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004379
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004380 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
4381 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004382
4383 bool IsComparisonConstant = false;
4384
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004385 // Check whether an integer constant comparison results in a value
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004386 // of 'true' or 'false'.
4387 if (T->isIntegralType(S.Context)) {
4388 llvm::APSInt RHSValue;
4389 bool IsRHSIntegralLiteral =
4390 RHS->isIntegerConstantExpr(RHSValue, S.Context);
4391 llvm::APSInt LHSValue;
4392 bool IsLHSIntegralLiteral =
4393 LHS->isIntegerConstantExpr(LHSValue, S.Context);
4394 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
4395 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
4396 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
4397 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
4398 else
4399 IsComparisonConstant =
4400 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004401 } else if (!T->hasUnsignedIntegerRepresentation())
4402 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004403
John McCall323ed742010-05-06 08:58:33 +00004404 // We don't do anything special if this isn't an unsigned integral
4405 // comparison: we're only interested in integral comparisons, and
4406 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00004407 //
4408 // We also don't care about value-dependent expressions or expressions
4409 // whose result is a constant.
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004410 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCall323ed742010-05-06 08:58:33 +00004411 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004412
John McCall323ed742010-05-06 08:58:33 +00004413 // Check to see if one of the (unmodified) operands is of different
4414 // signedness.
4415 Expr *signedOperand, *unsignedOperand;
Richard Trieudd225092011-09-15 21:56:47 +00004416 if (LHS->getType()->hasSignedIntegerRepresentation()) {
4417 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00004418 "unsigned comparison between two signed integer expressions?");
Richard Trieudd225092011-09-15 21:56:47 +00004419 signedOperand = LHS;
4420 unsignedOperand = RHS;
4421 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
4422 signedOperand = RHS;
4423 unsignedOperand = LHS;
John McCallba26e582010-01-04 23:21:16 +00004424 } else {
John McCall323ed742010-05-06 08:58:33 +00004425 CheckTrivialUnsignedComparison(S, E);
4426 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004427 }
4428
John McCall323ed742010-05-06 08:58:33 +00004429 // Otherwise, calculate the effective range of the signed operand.
4430 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00004431
John McCall323ed742010-05-06 08:58:33 +00004432 // Go ahead and analyze implicit conversions in the operands. Note
4433 // that we skip the implicit conversions on both sides.
Richard Trieudd225092011-09-15 21:56:47 +00004434 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
4435 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00004436
John McCall323ed742010-05-06 08:58:33 +00004437 // If the signed range is non-negative, -Wsign-compare won't fire,
4438 // but we should still check for comparisons which are always true
4439 // or false.
4440 if (signedRange.NonNegative)
4441 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004442
4443 // For (in)equality comparisons, if the unsigned operand is a
4444 // constant which cannot collide with a overflowed signed operand,
4445 // then reinterpreting the signed operand as unsigned will not
4446 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00004447 if (E->isEqualityOp()) {
4448 unsigned comparisonWidth = S.Context.getIntWidth(T);
4449 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00004450
John McCall323ed742010-05-06 08:58:33 +00004451 // We should never be unable to prove that the unsigned operand is
4452 // non-negative.
4453 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
4454
4455 if (unsignedRange.Width < comparisonWidth)
4456 return;
4457 }
4458
Douglas Gregor6d3b93d2012-05-01 01:53:49 +00004459 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
4460 S.PDiag(diag::warn_mixed_sign_comparison)
4461 << LHS->getType() << RHS->getType()
4462 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallba26e582010-01-04 23:21:16 +00004463}
4464
John McCall15d7d122010-11-11 03:21:53 +00004465/// Analyzes an attempt to assign the given value to a bitfield.
4466///
4467/// Returns true if there was something fishy about the attempt.
Ted Kremenek0692a192012-01-31 05:37:37 +00004468static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
4469 SourceLocation InitLoc) {
John McCall15d7d122010-11-11 03:21:53 +00004470 assert(Bitfield->isBitField());
4471 if (Bitfield->isInvalidDecl())
4472 return false;
4473
John McCall91b60142010-11-11 05:33:51 +00004474 // White-list bool bitfields.
4475 if (Bitfield->getType()->isBooleanType())
4476 return false;
4477
Douglas Gregor46ff3032011-02-04 13:09:01 +00004478 // Ignore value- or type-dependent expressions.
4479 if (Bitfield->getBitWidth()->isValueDependent() ||
4480 Bitfield->getBitWidth()->isTypeDependent() ||
4481 Init->isValueDependent() ||
4482 Init->isTypeDependent())
4483 return false;
4484
John McCall15d7d122010-11-11 03:21:53 +00004485 Expr *OriginalInit = Init->IgnoreParenImpCasts();
4486
Richard Smith80d4b552011-12-28 19:48:30 +00004487 llvm::APSInt Value;
4488 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall15d7d122010-11-11 03:21:53 +00004489 return false;
4490
John McCall15d7d122010-11-11 03:21:53 +00004491 unsigned OriginalWidth = Value.getBitWidth();
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004492 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall15d7d122010-11-11 03:21:53 +00004493
4494 if (OriginalWidth <= FieldWidth)
4495 return false;
4496
Eli Friedman3a643af2012-01-26 23:11:39 +00004497 // Compute the value which the bitfield will contain.
Jay Foad9f71a8f2010-12-07 08:25:34 +00004498 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedman3a643af2012-01-26 23:11:39 +00004499 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall15d7d122010-11-11 03:21:53 +00004500
Eli Friedman3a643af2012-01-26 23:11:39 +00004501 // Check whether the stored value is equal to the original value.
4502 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieue1ecdc12012-07-23 20:21:35 +00004503 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall15d7d122010-11-11 03:21:53 +00004504 return false;
4505
Eli Friedman3a643af2012-01-26 23:11:39 +00004506 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedman34ff0622012-02-02 00:40:20 +00004507 // therefore don't strictly fit into a signed bitfield of width 1.
4508 if (FieldWidth == 1 && Value == 1)
Eli Friedman3a643af2012-01-26 23:11:39 +00004509 return false;
4510
John McCall15d7d122010-11-11 03:21:53 +00004511 std::string PrettyValue = Value.toString(10);
4512 std::string PrettyTrunc = TruncatedValue.toString(10);
4513
4514 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
4515 << PrettyValue << PrettyTrunc << OriginalInit->getType()
4516 << Init->getSourceRange();
4517
4518 return true;
4519}
4520
John McCallbeb22aa2010-11-09 23:24:47 +00004521/// Analyze the given simple or compound assignment for warning-worthy
4522/// operations.
Ted Kremenek0692a192012-01-31 05:37:37 +00004523static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCallbeb22aa2010-11-09 23:24:47 +00004524 // Just recurse on the LHS.
4525 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4526
4527 // We want to recurse on the RHS as normal unless we're assigning to
4528 // a bitfield.
4529 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
John McCall15d7d122010-11-11 03:21:53 +00004530 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
4531 E->getOperatorLoc())) {
4532 // Recurse, ignoring any implicit conversions on the RHS.
4533 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
4534 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00004535 }
4536 }
4537
4538 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
4539}
4540
John McCall51313c32010-01-04 23:31:57 +00004541/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00004542static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00004543 SourceLocation CContext, unsigned diag,
4544 bool pruneControlFlow = false) {
4545 if (pruneControlFlow) {
4546 S.DiagRuntimeBehavior(E->getExprLoc(), E,
4547 S.PDiag(diag)
4548 << SourceType << T << E->getSourceRange()
4549 << SourceRange(CContext));
4550 return;
4551 }
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004552 S.Diag(E->getExprLoc(), diag)
4553 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
4554}
4555
Chandler Carruthe1b02e02011-04-05 06:47:57 +00004556/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00004557static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00004558 SourceLocation CContext, unsigned diag,
4559 bool pruneControlFlow = false) {
4560 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruthe1b02e02011-04-05 06:47:57 +00004561}
4562
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004563/// Diagnose an implicit cast from a literal expression. Does not warn when the
4564/// cast wouldn't lose information.
Chandler Carruthf65076e2011-04-10 08:36:24 +00004565void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
4566 SourceLocation CContext) {
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004567 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruthf65076e2011-04-10 08:36:24 +00004568 bool isExact = false;
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004569 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00004570 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
4571 T->hasUnsignedIntegerRepresentation());
4572 if (Value.convertToInteger(IntegerValue,
Chandler Carruthf65076e2011-04-10 08:36:24 +00004573 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004574 == llvm::APFloat::opOK && isExact)
Chandler Carruthf65076e2011-04-10 08:36:24 +00004575 return;
4576
David Blaikiebe0ee872012-05-15 16:56:36 +00004577 SmallString<16> PrettySourceValue;
4578 Value.toString(PrettySourceValue);
David Blaikiede7e7b82012-05-15 17:18:27 +00004579 SmallString<16> PrettyTargetValue;
David Blaikiebe0ee872012-05-15 16:56:36 +00004580 if (T->isSpecificBuiltinType(BuiltinType::Bool))
4581 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
4582 else
David Blaikiede7e7b82012-05-15 17:18:27 +00004583 IntegerValue.toString(PrettyTargetValue);
David Blaikiebe0ee872012-05-15 16:56:36 +00004584
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004585 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikiebe0ee872012-05-15 16:56:36 +00004586 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
4587 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruthf65076e2011-04-10 08:36:24 +00004588}
4589
John McCall091f23f2010-11-09 22:22:12 +00004590std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
4591 if (!Range.Width) return "0";
4592
4593 llvm::APSInt ValueInRange = Value;
4594 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00004595 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00004596 return ValueInRange.toString(10);
4597}
4598
Hans Wennborg88617a22012-08-28 15:44:30 +00004599static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
4600 if (!isa<ImplicitCastExpr>(Ex))
4601 return false;
4602
4603 Expr *InnerE = Ex->IgnoreParenImpCasts();
4604 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
4605 const Type *Source =
4606 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
4607 if (Target->isDependentType())
4608 return false;
4609
4610 const BuiltinType *FloatCandidateBT =
4611 dyn_cast<BuiltinType>(ToBool ? Source : Target);
4612 const Type *BoolCandidateType = ToBool ? Target : Source;
4613
4614 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
4615 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
4616}
4617
4618void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
4619 SourceLocation CC) {
4620 unsigned NumArgs = TheCall->getNumArgs();
4621 for (unsigned i = 0; i < NumArgs; ++i) {
4622 Expr *CurrA = TheCall->getArg(i);
4623 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
4624 continue;
4625
4626 bool IsSwapped = ((i > 0) &&
4627 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
4628 IsSwapped |= ((i < (NumArgs - 1)) &&
4629 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
4630 if (IsSwapped) {
4631 // Warn on this floating-point to bool conversion.
4632 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
4633 CurrA->getType(), CC,
4634 diag::warn_impcast_floating_point_to_bool);
4635 }
4636 }
4637}
4638
John McCall323ed742010-05-06 08:58:33 +00004639void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00004640 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00004641 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00004642
John McCall323ed742010-05-06 08:58:33 +00004643 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
4644 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
4645 if (Source == Target) return;
4646 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00004647
Chandler Carruth108f7562011-07-26 05:40:03 +00004648 // If the conversion context location is invalid don't complain. We also
4649 // don't want to emit a warning if the issue occurs from the expansion of
4650 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
4651 // delay this check as long as possible. Once we detect we are in that
4652 // scenario, we just return.
Ted Kremenekef9ff882011-03-10 20:03:42 +00004653 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00004654 return;
4655
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004656 // Diagnose implicit casts to bool.
4657 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
4658 if (isa<StringLiteral>(E))
4659 // Warn on string literal to bool. Checks for string literals in logical
4660 // expressions, for instances, assert(0 && "error here"), is prevented
4661 // by a check in AnalyzeImplicitConversions().
4662 return DiagnoseImpCast(S, E, T, CC,
4663 diag::warn_impcast_string_literal_to_bool);
Lang Hamese14ca9f2011-12-05 20:49:50 +00004664 if (Source->isFunctionType()) {
4665 // Warn on function to bool. Checks free functions and static member
4666 // functions. Weakly imported functions are excluded from the check,
4667 // since it's common to test their value to check whether the linker
4668 // found a definition for them.
4669 ValueDecl *D = 0;
4670 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
4671 D = R->getDecl();
4672 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
4673 D = M->getMemberDecl();
4674 }
4675
4676 if (D && !D->isWeak()) {
Richard Trieu26b45d82011-12-06 04:48:01 +00004677 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
4678 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
4679 << F << E->getSourceRange() << SourceRange(CC);
David Blaikie2def7732011-12-09 21:42:37 +00004680 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
4681 << FixItHint::CreateInsertion(E->getExprLoc(), "&");
4682 QualType ReturnType;
4683 UnresolvedSet<4> NonTemplateOverloads;
4684 S.isExprCallable(*E, ReturnType, NonTemplateOverloads);
4685 if (!ReturnType.isNull()
4686 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
4687 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
4688 << FixItHint::CreateInsertion(
4689 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu26b45d82011-12-06 04:48:01 +00004690 return;
4691 }
Lang Hamese14ca9f2011-12-05 20:49:50 +00004692 }
4693 }
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004694 }
John McCall51313c32010-01-04 23:31:57 +00004695
4696 // Strip vector types.
4697 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004698 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004699 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004700 return;
John McCallb4eb64d2010-10-08 02:01:28 +00004701 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004702 }
Chris Lattnerb792b302011-06-14 04:51:15 +00004703
4704 // If the vector cast is cast between two vectors of the same size, it is
4705 // a bitcast, not a conversion.
4706 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
4707 return;
John McCall51313c32010-01-04 23:31:57 +00004708
4709 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
4710 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
4711 }
4712
4713 // Strip complex types.
4714 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004715 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004716 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004717 return;
4718
John McCallb4eb64d2010-10-08 02:01:28 +00004719 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004720 }
John McCall51313c32010-01-04 23:31:57 +00004721
4722 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
4723 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
4724 }
4725
4726 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
4727 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
4728
4729 // If the source is floating point...
4730 if (SourceBT && SourceBT->isFloatingPoint()) {
4731 // ...and the target is floating point...
4732 if (TargetBT && TargetBT->isFloatingPoint()) {
4733 // ...then warn if we're dropping FP rank.
4734
4735 // Builtin FP kinds are ordered by increasing FP rank.
4736 if (SourceBT->getKind() > TargetBT->getKind()) {
4737 // Don't warn about float constants that are precisely
4738 // representable in the target type.
4739 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00004740 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00004741 // Value might be a float, a float vector, or a float complex.
4742 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00004743 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
4744 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00004745 return;
4746 }
4747
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004748 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004749 return;
4750
John McCallb4eb64d2010-10-08 02:01:28 +00004751 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00004752 }
4753 return;
4754 }
4755
Ted Kremenekef9ff882011-03-10 20:03:42 +00004756 // If the target is integral, always warn.
David Blaikiebe0ee872012-05-15 16:56:36 +00004757 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004758 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004759 return;
4760
Chandler Carrutha5b93322011-02-17 11:05:49 +00004761 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay634c8af2011-09-08 22:30:47 +00004762 // We also want to warn on, e.g., "int i = -1.234"
4763 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
4764 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
4765 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
4766
Chandler Carruthf65076e2011-04-10 08:36:24 +00004767 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
4768 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00004769 } else {
4770 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
4771 }
4772 }
John McCall51313c32010-01-04 23:31:57 +00004773
Hans Wennborg88617a22012-08-28 15:44:30 +00004774 // If the target is bool, warn if expr is a function or method call.
4775 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
4776 isa<CallExpr>(E)) {
4777 // Check last argument of function call to see if it is an
4778 // implicit cast from a type matching the type the result
4779 // is being cast to.
4780 CallExpr *CEx = cast<CallExpr>(E);
4781 unsigned NumArgs = CEx->getNumArgs();
4782 if (NumArgs > 0) {
4783 Expr *LastA = CEx->getArg(NumArgs - 1);
4784 Expr *InnerE = LastA->IgnoreParenImpCasts();
4785 const Type *InnerType =
4786 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
4787 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
4788 // Warn on this floating-point to bool conversion
4789 DiagnoseImpCast(S, E, T, CC,
4790 diag::warn_impcast_floating_point_to_bool);
4791 }
4792 }
4793 }
John McCall51313c32010-01-04 23:31:57 +00004794 return;
4795 }
4796
Richard Trieu1838ca52011-05-29 19:59:02 +00004797 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
David Blaikieb26331b2012-06-19 21:19:06 +00004798 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
David Blaikie28a5f0c2012-06-21 18:51:10 +00004799 && !Target->isBlockPointerType() && !Target->isMemberPointerType()) {
David Blaikieb1360492012-03-16 20:30:12 +00004800 SourceLocation Loc = E->getSourceRange().getBegin();
4801 if (Loc.isMacroID())
4802 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
David Blaikie9fb1ac52012-05-15 21:57:38 +00004803 if (!Loc.isMacroID() || CC.isMacroID())
4804 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
4805 << T << clang::SourceRange(CC)
4806 << FixItHint::CreateReplacement(Loc, S.getFixItZeroLiteralForType(T));
Richard Trieu1838ca52011-05-29 19:59:02 +00004807 }
4808
David Blaikieb26331b2012-06-19 21:19:06 +00004809 if (!Source->isIntegerType() || !Target->isIntegerType())
4810 return;
4811
David Blaikiebe0ee872012-05-15 16:56:36 +00004812 // TODO: remove this early return once the false positives for constant->bool
4813 // in templates, macros, etc, are reduced or removed.
4814 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
4815 return;
4816
John McCall323ed742010-05-06 08:58:33 +00004817 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00004818 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00004819
4820 if (SourceRange.Width > TargetRange.Width) {
John McCall091f23f2010-11-09 22:22:12 +00004821 // If the source is a constant, use a default-on diagnostic.
4822 // TODO: this should happen for bitfield stores, too.
4823 llvm::APSInt Value(32);
4824 if (E->isIntegerConstantExpr(Value, S.Context)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004825 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004826 return;
4827
John McCall091f23f2010-11-09 22:22:12 +00004828 std::string PrettySourceValue = Value.toString(10);
4829 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
4830
Ted Kremenek5e745da2011-10-22 02:37:33 +00004831 S.DiagRuntimeBehavior(E->getExprLoc(), E,
4832 S.PDiag(diag::warn_impcast_integer_precision_constant)
4833 << PrettySourceValue << PrettyTargetValue
4834 << E->getType() << T << E->getSourceRange()
4835 << clang::SourceRange(CC));
John McCall091f23f2010-11-09 22:22:12 +00004836 return;
4837 }
4838
Chris Lattnerb792b302011-06-14 04:51:15 +00004839 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004840 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004841 return;
4842
David Blaikie37050842012-04-12 22:40:54 +00004843 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaksc36bedc2012-02-01 19:08:57 +00004844 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
4845 /* pruneControlFlow */ true);
John McCallb4eb64d2010-10-08 02:01:28 +00004846 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00004847 }
4848
4849 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
4850 (!TargetRange.NonNegative && SourceRange.NonNegative &&
4851 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004852
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004853 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004854 return;
4855
John McCall323ed742010-05-06 08:58:33 +00004856 unsigned DiagID = diag::warn_impcast_integer_sign;
4857
4858 // Traditionally, gcc has warned about this under -Wsign-compare.
4859 // We also want to warn about it in -Wconversion.
4860 // So if -Wconversion is off, use a completely identical diagnostic
4861 // in the sign-compare group.
4862 // The conditional-checking code will
4863 if (ICContext) {
4864 DiagID = diag::warn_impcast_integer_sign_conditional;
4865 *ICContext = true;
4866 }
4867
John McCallb4eb64d2010-10-08 02:01:28 +00004868 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00004869 }
4870
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004871 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004872 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
4873 // type, to give us better diagnostics.
4874 QualType SourceType = E->getType();
David Blaikie4e4d0842012-03-11 07:00:24 +00004875 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004876 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
4877 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
4878 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
4879 SourceType = S.Context.getTypeDeclType(Enum);
4880 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
4881 }
4882 }
4883
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004884 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
4885 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
4886 if ((SourceEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00004887 SourceEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004888 (TargetEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00004889 TargetEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00004890 SourceEnum != TargetEnum) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004891 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004892 return;
4893
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004894 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004895 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004896 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004897
John McCall51313c32010-01-04 23:31:57 +00004898 return;
4899}
4900
David Blaikie9fb1ac52012-05-15 21:57:38 +00004901void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
4902 SourceLocation CC, QualType T);
John McCall323ed742010-05-06 08:58:33 +00004903
4904void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00004905 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00004906 E = E->IgnoreParenImpCasts();
4907
4908 if (isa<ConditionalOperator>(E))
David Blaikie9fb1ac52012-05-15 21:57:38 +00004909 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCall323ed742010-05-06 08:58:33 +00004910
John McCallb4eb64d2010-10-08 02:01:28 +00004911 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00004912 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00004913 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00004914 return;
4915}
4916
David Blaikie9fb1ac52012-05-15 21:57:38 +00004917void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
4918 SourceLocation CC, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00004919 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00004920
4921 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00004922 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
4923 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00004924
4925 // If -Wconversion would have warned about either of the candidates
4926 // for a signedness conversion to the context type...
4927 if (!Suspicious) return;
4928
4929 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00004930 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
4931 CC))
John McCall323ed742010-05-06 08:58:33 +00004932 return;
4933
John McCall323ed742010-05-06 08:58:33 +00004934 // ...then check whether it would have warned about either of the
4935 // candidates for a signedness conversion to the condition type.
Richard Trieu52541612011-07-21 02:46:28 +00004936 if (E->getType() == T) return;
4937
4938 Suspicious = false;
4939 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
4940 E->getType(), CC, &Suspicious);
4941 if (!Suspicious)
4942 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00004943 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00004944}
4945
4946/// AnalyzeImplicitConversions - Find and report any interesting
4947/// implicit conversions in the given expression. There are a couple
4948/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00004949void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00004950 QualType T = OrigE->getType();
4951 Expr *E = OrigE->IgnoreParenImpCasts();
4952
Douglas Gregorf8b6e152011-10-10 17:38:18 +00004953 if (E->isTypeDependent() || E->isValueDependent())
4954 return;
4955
John McCall323ed742010-05-06 08:58:33 +00004956 // For conditional operators, we analyze the arguments as if they
4957 // were being fed directly into the output.
4958 if (isa<ConditionalOperator>(E)) {
4959 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie9fb1ac52012-05-15 21:57:38 +00004960 CheckConditionalOperator(S, CO, CC, T);
John McCall323ed742010-05-06 08:58:33 +00004961 return;
4962 }
4963
Hans Wennborg88617a22012-08-28 15:44:30 +00004964 // Check implicit argument conversions for function calls.
4965 if (CallExpr *Call = dyn_cast<CallExpr>(E))
4966 CheckImplicitArgumentConversions(S, Call, CC);
4967
John McCall323ed742010-05-06 08:58:33 +00004968 // Go ahead and check any implicit conversions we might have skipped.
4969 // The non-canonical typecheck is just an optimization;
4970 // CheckImplicitConversion will filter out dead implicit conversions.
4971 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00004972 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00004973
4974 // Now continue drilling into this expression.
4975
4976 // Skip past explicit casts.
4977 if (isa<ExplicitCastExpr>(E)) {
4978 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00004979 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00004980 }
4981
John McCallbeb22aa2010-11-09 23:24:47 +00004982 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4983 // Do a somewhat different check with comparison operators.
4984 if (BO->isComparisonOp())
4985 return AnalyzeComparison(S, BO);
4986
Eli Friedman0fa06382012-01-26 23:34:06 +00004987 // And with simple assignments.
4988 if (BO->getOpcode() == BO_Assign)
John McCallbeb22aa2010-11-09 23:24:47 +00004989 return AnalyzeAssignment(S, BO);
4990 }
John McCall323ed742010-05-06 08:58:33 +00004991
4992 // These break the otherwise-useful invariant below. Fortunately,
4993 // we don't really need to recurse into them, because any internal
4994 // expressions should have been analyzed already when they were
4995 // built into statements.
4996 if (isa<StmtExpr>(E)) return;
4997
4998 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004999 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00005000
5001 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00005002 CC = E->getExprLoc();
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005003 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
5004 bool IsLogicalOperator = BO && BO->isLogicalOp();
5005 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor54042f12012-02-09 10:18:50 +00005006 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor503384f2012-02-09 00:47:04 +00005007 if (!ChildExpr)
5008 continue;
5009
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005010 if (IsLogicalOperator &&
5011 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
5012 // Ignore checking string literals that are in logical operators.
5013 continue;
5014 AnalyzeImplicitConversions(S, ChildExpr, CC);
5015 }
John McCall323ed742010-05-06 08:58:33 +00005016}
5017
5018} // end anonymous namespace
5019
5020/// Diagnoses "dangerous" implicit conversions within the given
5021/// expression (which is a full expression). Implements -Wconversion
5022/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00005023///
5024/// \param CC the "context" location of the implicit conversion, i.e.
5025/// the most location of the syntactic entity requiring the implicit
5026/// conversion
5027void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00005028 // Don't diagnose in unevaluated contexts.
David Blaikie71f55f72012-08-06 22:47:24 +00005029 if (isUnevaluatedContext())
John McCall323ed742010-05-06 08:58:33 +00005030 return;
5031
5032 // Don't diagnose for value- or type-dependent expressions.
5033 if (E->isTypeDependent() || E->isValueDependent())
5034 return;
5035
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005036 // Check for array bounds violations in cases where the check isn't triggered
5037 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
5038 // ArraySubscriptExpr is on the RHS of a variable initialization.
5039 CheckArrayAccess(E);
5040
John McCallb4eb64d2010-10-08 02:01:28 +00005041 // This is not the right CC for (e.g.) a variable initialization.
5042 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005043}
5044
John McCall15d7d122010-11-11 03:21:53 +00005045void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
5046 FieldDecl *BitField,
5047 Expr *Init) {
5048 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
5049}
5050
Mike Stumpf8c49212010-01-21 03:59:47 +00005051/// CheckParmsForFunctionDef - Check that the parameters of the given
5052/// function are appropriate for the definition of a function. This
5053/// takes care of any checks that cannot be performed on the
5054/// declaration itself, e.g., that the types of each of the function
5055/// parameters are complete.
Douglas Gregor82aa7132010-11-01 18:37:59 +00005056bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
5057 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00005058 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00005059 for (; P != PEnd; ++P) {
5060 ParmVarDecl *Param = *P;
5061
Mike Stumpf8c49212010-01-21 03:59:47 +00005062 // C99 6.7.5.3p4: the parameters in a parameter type list in a
5063 // function declarator that is part of a function definition of
5064 // that function shall not have incomplete type.
5065 //
5066 // This is also C++ [dcl.fct]p6.
5067 if (!Param->isInvalidDecl() &&
5068 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00005069 diag::err_typecheck_decl_incomplete_type)) {
Mike Stumpf8c49212010-01-21 03:59:47 +00005070 Param->setInvalidDecl();
5071 HasInvalidParm = true;
5072 }
5073
5074 // C99 6.9.1p5: If the declarator includes a parameter type list, the
5075 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00005076 if (CheckParameterNames &&
5077 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00005078 !Param->isImplicit() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00005079 !getLangOpts().CPlusPlus)
Mike Stumpf8c49212010-01-21 03:59:47 +00005080 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00005081
5082 // C99 6.7.5.3p12:
5083 // If the function declarator is not part of a definition of that
5084 // function, parameters may have incomplete type and may use the [*]
5085 // notation in their sequences of declarator specifiers to specify
5086 // variable length array types.
5087 QualType PType = Param->getOriginalType();
5088 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
5089 if (AT->getSizeModifier() == ArrayType::Star) {
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00005090 // FIXME: This diagnosic should point the '[*]' if source-location
Sam Weinigd17e3402010-02-01 05:02:49 +00005091 // information is added for it.
5092 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
5093 }
5094 }
Mike Stumpf8c49212010-01-21 03:59:47 +00005095 }
5096
5097 return HasInvalidParm;
5098}
John McCallb7f4ffe2010-08-12 21:44:57 +00005099
5100/// CheckCastAlign - Implements -Wcast-align, which warns when a
5101/// pointer cast increases the alignment requirements.
5102void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
5103 // This is actually a lot of work to potentially be doing on every
5104 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00005105 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
5106 TRange.getBegin())
David Blaikied6471f72011-09-25 23:23:43 +00005107 == DiagnosticsEngine::Ignored)
John McCallb7f4ffe2010-08-12 21:44:57 +00005108 return;
5109
5110 // Ignore dependent types.
5111 if (T->isDependentType() || Op->getType()->isDependentType())
5112 return;
5113
5114 // Require that the destination be a pointer type.
5115 const PointerType *DestPtr = T->getAs<PointerType>();
5116 if (!DestPtr) return;
5117
5118 // If the destination has alignment 1, we're done.
5119 QualType DestPointee = DestPtr->getPointeeType();
5120 if (DestPointee->isIncompleteType()) return;
5121 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
5122 if (DestAlign.isOne()) return;
5123
5124 // Require that the source be a pointer type.
5125 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
5126 if (!SrcPtr) return;
5127 QualType SrcPointee = SrcPtr->getPointeeType();
5128
5129 // Whitelist casts from cv void*. We already implicitly
5130 // whitelisted casts to cv void*, since they have alignment 1.
5131 // Also whitelist casts involving incomplete types, which implicitly
5132 // includes 'void'.
5133 if (SrcPointee->isIncompleteType()) return;
5134
5135 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
5136 if (SrcAlign >= DestAlign) return;
5137
5138 Diag(TRange.getBegin(), diag::warn_cast_align)
5139 << Op->getType() << T
5140 << static_cast<unsigned>(SrcAlign.getQuantity())
5141 << static_cast<unsigned>(DestAlign.getQuantity())
5142 << TRange << Op->getSourceRange();
5143}
5144
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005145static const Type* getElementType(const Expr *BaseExpr) {
5146 const Type* EltType = BaseExpr->getType().getTypePtr();
5147 if (EltType->isAnyPointerType())
5148 return EltType->getPointeeType().getTypePtr();
5149 else if (EltType->isArrayType())
5150 return EltType->getBaseElementTypeUnsafe();
5151 return EltType;
5152}
5153
Chandler Carruthc2684342011-08-05 09:10:50 +00005154/// \brief Check whether this array fits the idiom of a size-one tail padded
5155/// array member of a struct.
5156///
5157/// We avoid emitting out-of-bounds access warnings for such arrays as they are
5158/// commonly used to emulate flexible arrays in C89 code.
5159static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
5160 const NamedDecl *ND) {
5161 if (Size != 1 || !ND) return false;
5162
5163 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
5164 if (!FD) return false;
5165
5166 // Don't consider sizes resulting from macro expansions or template argument
5167 // substitution to form C89 tail-padded arrays.
Sean Callanand2cf3482012-05-04 18:22:53 +00005168
5169 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00005170 while (TInfo) {
5171 TypeLoc TL = TInfo->getTypeLoc();
5172 // Look through typedefs.
5173 const TypedefTypeLoc *TTL = dyn_cast<TypedefTypeLoc>(&TL);
5174 if (TTL) {
5175 const TypedefNameDecl *TDL = TTL->getTypedefNameDecl();
5176 TInfo = TDL->getTypeSourceInfo();
5177 continue;
5178 }
5179 ConstantArrayTypeLoc CTL = cast<ConstantArrayTypeLoc>(TL);
5180 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Sean Callanand2cf3482012-05-04 18:22:53 +00005181 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
5182 return false;
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00005183 break;
Sean Callanand2cf3482012-05-04 18:22:53 +00005184 }
Chandler Carruthc2684342011-08-05 09:10:50 +00005185
5186 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gay381711c2011-11-29 22:43:53 +00005187 if (!RD) return false;
5188 if (RD->isUnion()) return false;
5189 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
5190 if (!CRD->isStandardLayout()) return false;
5191 }
Chandler Carruthc2684342011-08-05 09:10:50 +00005192
Benjamin Kramer22d4fed2011-08-06 03:04:42 +00005193 // See if this is the last field decl in the record.
5194 const Decl *D = FD;
5195 while ((D = D->getNextDeclInContext()))
5196 if (isa<FieldDecl>(D))
5197 return false;
5198 return true;
Chandler Carruthc2684342011-08-05 09:10:50 +00005199}
5200
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005201void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005202 const ArraySubscriptExpr *ASE,
Richard Smith25b009a2011-12-16 19:31:14 +00005203 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman92b670e2012-02-27 21:21:40 +00005204 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005205 if (IndexExpr->isValueDependent())
5206 return;
5207
Matt Beaumont-Gay8ef8f432011-12-12 22:35:02 +00005208 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005209 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00005210 const ConstantArrayType *ArrayTy =
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005211 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00005212 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00005213 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00005214
Chandler Carruth34064582011-02-17 20:55:08 +00005215 llvm::APSInt index;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005216 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00005217 return;
Richard Smith25b009a2011-12-16 19:31:14 +00005218 if (IndexNegated)
5219 index = -index;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00005220
Chandler Carruthba447122011-08-05 08:07:29 +00005221 const NamedDecl *ND = NULL;
Chandler Carruthba447122011-08-05 08:07:29 +00005222 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
5223 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruthc2684342011-08-05 09:10:50 +00005224 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruthba447122011-08-05 08:07:29 +00005225 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruthba447122011-08-05 08:07:29 +00005226
Ted Kremenek9e060ca2011-02-23 23:06:04 +00005227 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00005228 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00005229 if (!size.isStrictlyPositive())
5230 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005231
5232 const Type* BaseType = getElementType(BaseExpr);
Nico Weberde5998f2011-09-17 22:59:41 +00005233 if (BaseType != EffectiveType) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005234 // Make sure we're comparing apples to apples when comparing index to size
5235 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
5236 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhraind10f4bc2011-08-10 19:47:25 +00005237 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhrain18f16972011-08-10 18:49:28 +00005238 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005239 if (ptrarith_typesize != array_typesize) {
5240 // There's a cast to a different size type involved
5241 uint64_t ratio = array_typesize / ptrarith_typesize;
5242 // TODO: Be smarter about handling cases where array_typesize is not a
5243 // multiple of ptrarith_typesize
5244 if (ptrarith_typesize * ratio == array_typesize)
5245 size *= llvm::APInt(size.getBitWidth(), ratio);
5246 }
5247 }
5248
Chandler Carruth34064582011-02-17 20:55:08 +00005249 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00005250 index = index.zext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00005251 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00005252 size = size.zext(index.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00005253
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005254 // For array subscripting the index must be less than size, but for pointer
5255 // arithmetic also allow the index (offset) to be equal to size since
5256 // computing the next address after the end of the array is legal and
5257 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman92b670e2012-02-27 21:21:40 +00005258 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruthba447122011-08-05 08:07:29 +00005259 return;
5260
5261 // Also don't warn for arrays of size 1 which are members of some
5262 // structure. These are often used to approximate flexible arrays in C89
5263 // code.
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005264 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00005265 return;
Chandler Carruth34064582011-02-17 20:55:08 +00005266
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005267 // Suppress the warning if the subscript expression (as identified by the
5268 // ']' location) and the index expression are both from macro expansions
5269 // within a system header.
5270 if (ASE) {
5271 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
5272 ASE->getRBracketLoc());
5273 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
5274 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
5275 IndexExpr->getLocStart());
5276 if (SourceMgr.isFromSameFile(RBracketLoc, IndexLoc))
5277 return;
5278 }
5279 }
5280
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005281 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005282 if (ASE)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005283 DiagID = diag::warn_array_index_exceeds_bounds;
5284
5285 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
5286 PDiag(DiagID) << index.toString(10, true)
5287 << size.toString(10, true)
5288 << (unsigned)size.getLimitedValue(~0U)
5289 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00005290 } else {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005291 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005292 if (!ASE) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005293 DiagID = diag::warn_ptr_arith_precedes_bounds;
5294 if (index.isNegative()) index = -index;
5295 }
5296
5297 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
5298 PDiag(DiagID) << index.toString(10, true)
5299 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00005300 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00005301
Matt Beaumont-Gaycfbc5b52011-11-29 19:27:11 +00005302 if (!ND) {
5303 // Try harder to find a NamedDecl to point at in the note.
5304 while (const ArraySubscriptExpr *ASE =
5305 dyn_cast<ArraySubscriptExpr>(BaseExpr))
5306 BaseExpr = ASE->getBase()->IgnoreParenCasts();
5307 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
5308 ND = dyn_cast<NamedDecl>(DRE->getDecl());
5309 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
5310 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
5311 }
5312
Chandler Carruth35001ca2011-02-17 21:10:52 +00005313 if (ND)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005314 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
5315 PDiag(diag::note_array_index_out_of_bounds)
5316 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00005317}
5318
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005319void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005320 int AllowOnePastEnd = 0;
5321 while (expr) {
5322 expr = expr->IgnoreParenImpCasts();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005323 switch (expr->getStmtClass()) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005324 case Stmt::ArraySubscriptExprClass: {
5325 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005326 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005327 AllowOnePastEnd > 0);
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005328 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005329 }
5330 case Stmt::UnaryOperatorClass: {
5331 // Only unwrap the * and & unary operators
5332 const UnaryOperator *UO = cast<UnaryOperator>(expr);
5333 expr = UO->getSubExpr();
5334 switch (UO->getOpcode()) {
5335 case UO_AddrOf:
5336 AllowOnePastEnd++;
5337 break;
5338 case UO_Deref:
5339 AllowOnePastEnd--;
5340 break;
5341 default:
5342 return;
5343 }
5344 break;
5345 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005346 case Stmt::ConditionalOperatorClass: {
5347 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
5348 if (const Expr *lhs = cond->getLHS())
5349 CheckArrayAccess(lhs);
5350 if (const Expr *rhs = cond->getRHS())
5351 CheckArrayAccess(rhs);
5352 return;
5353 }
5354 default:
5355 return;
5356 }
Peter Collingbournef111d932011-04-15 00:35:48 +00005357 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005358}
John McCallf85e1932011-06-15 23:02:42 +00005359
5360//===--- CHECK: Objective-C retain cycles ----------------------------------//
5361
5362namespace {
5363 struct RetainCycleOwner {
5364 RetainCycleOwner() : Variable(0), Indirect(false) {}
5365 VarDecl *Variable;
5366 SourceRange Range;
5367 SourceLocation Loc;
5368 bool Indirect;
5369
5370 void setLocsFrom(Expr *e) {
5371 Loc = e->getExprLoc();
5372 Range = e->getSourceRange();
5373 }
5374 };
5375}
5376
5377/// Consider whether capturing the given variable can possibly lead to
5378/// a retain cycle.
5379static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledruf3477c12012-09-27 10:16:10 +00005380 // In ARC, it's captured strongly iff the variable has __strong
John McCallf85e1932011-06-15 23:02:42 +00005381 // lifetime. In MRR, it's captured strongly if the variable is
5382 // __block and has an appropriate type.
5383 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
5384 return false;
5385
5386 owner.Variable = var;
Jordan Rosee10f4d32012-09-15 02:48:31 +00005387 if (ref)
5388 owner.setLocsFrom(ref);
John McCallf85e1932011-06-15 23:02:42 +00005389 return true;
5390}
5391
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00005392static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCallf85e1932011-06-15 23:02:42 +00005393 while (true) {
5394 e = e->IgnoreParens();
5395 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
5396 switch (cast->getCastKind()) {
5397 case CK_BitCast:
5398 case CK_LValueBitCast:
5399 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00005400 case CK_ARCReclaimReturnedObject:
John McCallf85e1932011-06-15 23:02:42 +00005401 e = cast->getSubExpr();
5402 continue;
5403
John McCallf85e1932011-06-15 23:02:42 +00005404 default:
5405 return false;
5406 }
5407 }
5408
5409 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
5410 ObjCIvarDecl *ivar = ref->getDecl();
5411 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
5412 return false;
5413
5414 // Try to find a retain cycle in the base.
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00005415 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCallf85e1932011-06-15 23:02:42 +00005416 return false;
5417
5418 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
5419 owner.Indirect = true;
5420 return true;
5421 }
5422
5423 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
5424 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
5425 if (!var) return false;
5426 return considerVariable(var, ref, owner);
5427 }
5428
John McCallf85e1932011-06-15 23:02:42 +00005429 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
5430 if (member->isArrow()) return false;
5431
5432 // Don't count this as an indirect ownership.
5433 e = member->getBase();
5434 continue;
5435 }
5436
John McCall4b9c2d22011-11-06 09:01:30 +00005437 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
5438 // Only pay attention to pseudo-objects on property references.
5439 ObjCPropertyRefExpr *pre
5440 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
5441 ->IgnoreParens());
5442 if (!pre) return false;
5443 if (pre->isImplicitProperty()) return false;
5444 ObjCPropertyDecl *property = pre->getExplicitProperty();
5445 if (!property->isRetaining() &&
5446 !(property->getPropertyIvarDecl() &&
5447 property->getPropertyIvarDecl()->getType()
5448 .getObjCLifetime() == Qualifiers::OCL_Strong))
5449 return false;
5450
5451 owner.Indirect = true;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00005452 if (pre->isSuperReceiver()) {
5453 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
5454 if (!owner.Variable)
5455 return false;
5456 owner.Loc = pre->getLocation();
5457 owner.Range = pre->getSourceRange();
5458 return true;
5459 }
John McCall4b9c2d22011-11-06 09:01:30 +00005460 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
5461 ->getSourceExpr());
5462 continue;
5463 }
5464
John McCallf85e1932011-06-15 23:02:42 +00005465 // Array ivars?
5466
5467 return false;
5468 }
5469}
5470
5471namespace {
5472 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
5473 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
5474 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
5475 Variable(variable), Capturer(0) {}
5476
5477 VarDecl *Variable;
5478 Expr *Capturer;
5479
5480 void VisitDeclRefExpr(DeclRefExpr *ref) {
5481 if (ref->getDecl() == Variable && !Capturer)
5482 Capturer = ref;
5483 }
5484
John McCallf85e1932011-06-15 23:02:42 +00005485 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
5486 if (Capturer) return;
5487 Visit(ref->getBase());
5488 if (Capturer && ref->isFreeIvar())
5489 Capturer = ref;
5490 }
5491
5492 void VisitBlockExpr(BlockExpr *block) {
5493 // Look inside nested blocks
5494 if (block->getBlockDecl()->capturesVariable(Variable))
5495 Visit(block->getBlockDecl()->getBody());
5496 }
Fariborz Jahanian7e2e4c32012-08-31 20:04:47 +00005497
5498 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
5499 if (Capturer) return;
5500 if (OVE->getSourceExpr())
5501 Visit(OVE->getSourceExpr());
5502 }
John McCallf85e1932011-06-15 23:02:42 +00005503 };
5504}
5505
5506/// Check whether the given argument is a block which captures a
5507/// variable.
5508static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
5509 assert(owner.Variable && owner.Loc.isValid());
5510
5511 e = e->IgnoreParenCasts();
Jordan Rose1fac58a2012-09-17 17:54:30 +00005512
5513 // Look through [^{...} copy] and Block_copy(^{...}).
5514 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
5515 Selector Cmd = ME->getSelector();
5516 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
5517 e = ME->getInstanceReceiver();
5518 if (!e)
5519 return 0;
5520 e = e->IgnoreParenCasts();
5521 }
5522 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
5523 if (CE->getNumArgs() == 1) {
5524 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekd13eff62012-10-02 04:36:54 +00005525 if (Fn) {
5526 const IdentifierInfo *FnI = Fn->getIdentifier();
5527 if (FnI && FnI->isStr("_Block_copy")) {
5528 e = CE->getArg(0)->IgnoreParenCasts();
5529 }
5530 }
Jordan Rose1fac58a2012-09-17 17:54:30 +00005531 }
5532 }
5533
John McCallf85e1932011-06-15 23:02:42 +00005534 BlockExpr *block = dyn_cast<BlockExpr>(e);
5535 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
5536 return 0;
5537
5538 FindCaptureVisitor visitor(S.Context, owner.Variable);
5539 visitor.Visit(block->getBlockDecl()->getBody());
5540 return visitor.Capturer;
5541}
5542
5543static void diagnoseRetainCycle(Sema &S, Expr *capturer,
5544 RetainCycleOwner &owner) {
5545 assert(capturer);
5546 assert(owner.Variable && owner.Loc.isValid());
5547
5548 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
5549 << owner.Variable << capturer->getSourceRange();
5550 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
5551 << owner.Indirect << owner.Range;
5552}
5553
5554/// Check for a keyword selector that starts with the word 'add' or
5555/// 'set'.
5556static bool isSetterLikeSelector(Selector sel) {
5557 if (sel.isUnarySelector()) return false;
5558
Chris Lattner5f9e2722011-07-23 10:55:15 +00005559 StringRef str = sel.getNameForSlot(0);
John McCallf85e1932011-06-15 23:02:42 +00005560 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00005561 if (str.startswith("set"))
John McCallf85e1932011-06-15 23:02:42 +00005562 str = str.substr(3);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00005563 else if (str.startswith("add")) {
5564 // Specially whitelist 'addOperationWithBlock:'.
5565 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
5566 return false;
5567 str = str.substr(3);
5568 }
John McCallf85e1932011-06-15 23:02:42 +00005569 else
5570 return false;
5571
5572 if (str.empty()) return true;
5573 return !islower(str.front());
5574}
5575
5576/// Check a message send to see if it's likely to cause a retain cycle.
5577void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
5578 // Only check instance methods whose selector looks like a setter.
5579 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
5580 return;
5581
5582 // Try to find a variable that the receiver is strongly owned by.
5583 RetainCycleOwner owner;
5584 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00005585 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCallf85e1932011-06-15 23:02:42 +00005586 return;
5587 } else {
5588 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
5589 owner.Variable = getCurMethodDecl()->getSelfDecl();
5590 owner.Loc = msg->getSuperLoc();
5591 owner.Range = msg->getSuperLoc();
5592 }
5593
5594 // Check whether the receiver is captured by any of the arguments.
5595 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
5596 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
5597 return diagnoseRetainCycle(*this, capturer, owner);
5598}
5599
5600/// Check a property assign to see if it's likely to cause a retain cycle.
5601void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
5602 RetainCycleOwner owner;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00005603 if (!findRetainCycleOwner(*this, receiver, owner))
John McCallf85e1932011-06-15 23:02:42 +00005604 return;
5605
5606 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
5607 diagnoseRetainCycle(*this, capturer, owner);
5608}
5609
Jordan Rosee10f4d32012-09-15 02:48:31 +00005610void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
5611 RetainCycleOwner Owner;
5612 if (!considerVariable(Var, /*DeclRefExpr=*/0, Owner))
5613 return;
5614
5615 // Because we don't have an expression for the variable, we have to set the
5616 // location explicitly here.
5617 Owner.Loc = Var->getLocation();
5618 Owner.Range = Var->getSourceRange();
5619
5620 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
5621 diagnoseRetainCycle(*this, Capturer, Owner);
5622}
5623
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005624bool Sema::checkUnsafeAssigns(SourceLocation Loc,
John McCallf85e1932011-06-15 23:02:42 +00005625 QualType LHS, Expr *RHS) {
5626 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
5627 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005628 return false;
5629 // strip off any implicit cast added to get to the one arc-specific
5630 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00005631 if (cast->getCastKind() == CK_ARCConsumeObject) {
John McCallf85e1932011-06-15 23:02:42 +00005632 Diag(Loc, diag::warn_arc_retained_assign)
Fariborz Jahanianbd2e27e2012-07-06 21:09:27 +00005633 << (LT == Qualifiers::OCL_ExplicitNone) << 1
John McCallf85e1932011-06-15 23:02:42 +00005634 << RHS->getSourceRange();
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005635 return true;
5636 }
5637 RHS = cast->getSubExpr();
5638 }
5639 return false;
John McCallf85e1932011-06-15 23:02:42 +00005640}
5641
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005642void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
5643 Expr *LHS, Expr *RHS) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00005644 QualType LHSType;
5645 // PropertyRef on LHS type need be directly obtained from
5646 // its declaration as it has a PsuedoType.
5647 ObjCPropertyRefExpr *PRE
5648 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
5649 if (PRE && !PRE->isImplicitProperty()) {
5650 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
5651 if (PD)
5652 LHSType = PD->getType();
5653 }
5654
5655 if (LHSType.isNull())
5656 LHSType = LHS->getType();
Jordan Rose7a270482012-09-28 22:21:35 +00005657
5658 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
5659
5660 if (LT == Qualifiers::OCL_Weak) {
5661 DiagnosticsEngine::Level Level =
5662 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
5663 if (Level != DiagnosticsEngine::Ignored)
5664 getCurFunction()->markSafeWeakUse(LHS);
5665 }
5666
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005667 if (checkUnsafeAssigns(Loc, LHSType, RHS))
5668 return;
Jordan Rose7a270482012-09-28 22:21:35 +00005669
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005670 // FIXME. Check for other life times.
5671 if (LT != Qualifiers::OCL_None)
5672 return;
5673
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00005674 if (PRE) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005675 if (PRE->isImplicitProperty())
5676 return;
5677 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
5678 if (!PD)
5679 return;
5680
5681 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00005682 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
5683 // when 'assign' attribute was not explicitly specified
5684 // by user, ignore it and rely on property type itself
5685 // for lifetime info.
5686 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
5687 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
5688 LHSType->isObjCRetainableType())
5689 return;
5690
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005691 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00005692 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005693 Diag(Loc, diag::warn_arc_retained_property_assign)
5694 << RHS->getSourceRange();
5695 return;
5696 }
5697 RHS = cast->getSubExpr();
5698 }
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00005699 }
Fariborz Jahanianbd2e27e2012-07-06 21:09:27 +00005700 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
5701 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
5702 if (cast->getCastKind() == CK_ARCConsumeObject) {
5703 Diag(Loc, diag::warn_arc_retained_assign)
5704 << 0 << 0<< RHS->getSourceRange();
5705 return;
5706 }
5707 RHS = cast->getSubExpr();
5708 }
5709 }
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005710 }
5711}
Dmitri Gribenko625bb562012-02-14 22:14:32 +00005712
5713//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
5714
5715namespace {
5716bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
5717 SourceLocation StmtLoc,
5718 const NullStmt *Body) {
5719 // Do not warn if the body is a macro that expands to nothing, e.g:
5720 //
5721 // #define CALL(x)
5722 // if (condition)
5723 // CALL(0);
5724 //
5725 if (Body->hasLeadingEmptyMacro())
5726 return false;
5727
5728 // Get line numbers of statement and body.
5729 bool StmtLineInvalid;
5730 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
5731 &StmtLineInvalid);
5732 if (StmtLineInvalid)
5733 return false;
5734
5735 bool BodyLineInvalid;
5736 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
5737 &BodyLineInvalid);
5738 if (BodyLineInvalid)
5739 return false;
5740
5741 // Warn if null statement and body are on the same line.
5742 if (StmtLine != BodyLine)
5743 return false;
5744
5745 return true;
5746}
5747} // Unnamed namespace
5748
5749void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
5750 const Stmt *Body,
5751 unsigned DiagID) {
5752 // Since this is a syntactic check, don't emit diagnostic for template
5753 // instantiations, this just adds noise.
5754 if (CurrentInstantiationScope)
5755 return;
5756
5757 // The body should be a null statement.
5758 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
5759 if (!NBody)
5760 return;
5761
5762 // Do the usual checks.
5763 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
5764 return;
5765
5766 Diag(NBody->getSemiLoc(), DiagID);
5767 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
5768}
5769
5770void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
5771 const Stmt *PossibleBody) {
5772 assert(!CurrentInstantiationScope); // Ensured by caller
5773
5774 SourceLocation StmtLoc;
5775 const Stmt *Body;
5776 unsigned DiagID;
5777 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
5778 StmtLoc = FS->getRParenLoc();
5779 Body = FS->getBody();
5780 DiagID = diag::warn_empty_for_body;
5781 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
5782 StmtLoc = WS->getCond()->getSourceRange().getEnd();
5783 Body = WS->getBody();
5784 DiagID = diag::warn_empty_while_body;
5785 } else
5786 return; // Neither `for' nor `while'.
5787
5788 // The body should be a null statement.
5789 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
5790 if (!NBody)
5791 return;
5792
5793 // Skip expensive checks if diagnostic is disabled.
5794 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
5795 DiagnosticsEngine::Ignored)
5796 return;
5797
5798 // Do the usual checks.
5799 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
5800 return;
5801
5802 // `for(...);' and `while(...);' are popular idioms, so in order to keep
5803 // noise level low, emit diagnostics only if for/while is followed by a
5804 // CompoundStmt, e.g.:
5805 // for (int i = 0; i < n; i++);
5806 // {
5807 // a(i);
5808 // }
5809 // or if for/while is followed by a statement with more indentation
5810 // than for/while itself:
5811 // for (int i = 0; i < n; i++);
5812 // a(i);
5813 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
5814 if (!ProbableTypo) {
5815 bool BodyColInvalid;
5816 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
5817 PossibleBody->getLocStart(),
5818 &BodyColInvalid);
5819 if (BodyColInvalid)
5820 return;
5821
5822 bool StmtColInvalid;
5823 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
5824 S->getLocStart(),
5825 &StmtColInvalid);
5826 if (StmtColInvalid)
5827 return;
5828
5829 if (BodyCol > StmtCol)
5830 ProbableTypo = true;
5831 }
5832
5833 if (ProbableTypo) {
5834 Diag(NBody->getSemiLoc(), DiagID);
5835 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
5836 }
5837}
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00005838
5839//===--- Layout compatibility ----------------------------------------------//
5840
5841namespace {
5842
5843bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
5844
5845/// \brief Check if two enumeration types are layout-compatible.
5846bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
5847 // C++11 [dcl.enum] p8:
5848 // Two enumeration types are layout-compatible if they have the same
5849 // underlying type.
5850 return ED1->isComplete() && ED2->isComplete() &&
5851 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
5852}
5853
5854/// \brief Check if two fields are layout-compatible.
5855bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
5856 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
5857 return false;
5858
5859 if (Field1->isBitField() != Field2->isBitField())
5860 return false;
5861
5862 if (Field1->isBitField()) {
5863 // Make sure that the bit-fields are the same length.
5864 unsigned Bits1 = Field1->getBitWidthValue(C);
5865 unsigned Bits2 = Field2->getBitWidthValue(C);
5866
5867 if (Bits1 != Bits2)
5868 return false;
5869 }
5870
5871 return true;
5872}
5873
5874/// \brief Check if two standard-layout structs are layout-compatible.
5875/// (C++11 [class.mem] p17)
5876bool isLayoutCompatibleStruct(ASTContext &C,
5877 RecordDecl *RD1,
5878 RecordDecl *RD2) {
5879 // If both records are C++ classes, check that base classes match.
5880 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
5881 // If one of records is a CXXRecordDecl we are in C++ mode,
5882 // thus the other one is a CXXRecordDecl, too.
5883 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
5884 // Check number of base classes.
5885 if (D1CXX->getNumBases() != D2CXX->getNumBases())
5886 return false;
5887
5888 // Check the base classes.
5889 for (CXXRecordDecl::base_class_const_iterator
5890 Base1 = D1CXX->bases_begin(),
5891 BaseEnd1 = D1CXX->bases_end(),
5892 Base2 = D2CXX->bases_begin();
5893 Base1 != BaseEnd1;
5894 ++Base1, ++Base2) {
5895 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
5896 return false;
5897 }
5898 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
5899 // If only RD2 is a C++ class, it should have zero base classes.
5900 if (D2CXX->getNumBases() > 0)
5901 return false;
5902 }
5903
5904 // Check the fields.
5905 RecordDecl::field_iterator Field2 = RD2->field_begin(),
5906 Field2End = RD2->field_end(),
5907 Field1 = RD1->field_begin(),
5908 Field1End = RD1->field_end();
5909 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
5910 if (!isLayoutCompatible(C, *Field1, *Field2))
5911 return false;
5912 }
5913 if (Field1 != Field1End || Field2 != Field2End)
5914 return false;
5915
5916 return true;
5917}
5918
5919/// \brief Check if two standard-layout unions are layout-compatible.
5920/// (C++11 [class.mem] p18)
5921bool isLayoutCompatibleUnion(ASTContext &C,
5922 RecordDecl *RD1,
5923 RecordDecl *RD2) {
5924 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
5925 for (RecordDecl::field_iterator Field2 = RD2->field_begin(),
5926 Field2End = RD2->field_end();
5927 Field2 != Field2End; ++Field2) {
5928 UnmatchedFields.insert(*Field2);
5929 }
5930
5931 for (RecordDecl::field_iterator Field1 = RD1->field_begin(),
5932 Field1End = RD1->field_end();
5933 Field1 != Field1End; ++Field1) {
5934 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
5935 I = UnmatchedFields.begin(),
5936 E = UnmatchedFields.end();
5937
5938 for ( ; I != E; ++I) {
5939 if (isLayoutCompatible(C, *Field1, *I)) {
5940 bool Result = UnmatchedFields.erase(*I);
5941 (void) Result;
5942 assert(Result);
5943 break;
5944 }
5945 }
5946 if (I == E)
5947 return false;
5948 }
5949
5950 return UnmatchedFields.empty();
5951}
5952
5953bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
5954 if (RD1->isUnion() != RD2->isUnion())
5955 return false;
5956
5957 if (RD1->isUnion())
5958 return isLayoutCompatibleUnion(C, RD1, RD2);
5959 else
5960 return isLayoutCompatibleStruct(C, RD1, RD2);
5961}
5962
5963/// \brief Check if two types are layout-compatible in C++11 sense.
5964bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
5965 if (T1.isNull() || T2.isNull())
5966 return false;
5967
5968 // C++11 [basic.types] p11:
5969 // If two types T1 and T2 are the same type, then T1 and T2 are
5970 // layout-compatible types.
5971 if (C.hasSameType(T1, T2))
5972 return true;
5973
5974 T1 = T1.getCanonicalType().getUnqualifiedType();
5975 T2 = T2.getCanonicalType().getUnqualifiedType();
5976
5977 const Type::TypeClass TC1 = T1->getTypeClass();
5978 const Type::TypeClass TC2 = T2->getTypeClass();
5979
5980 if (TC1 != TC2)
5981 return false;
5982
5983 if (TC1 == Type::Enum) {
5984 return isLayoutCompatible(C,
5985 cast<EnumType>(T1)->getDecl(),
5986 cast<EnumType>(T2)->getDecl());
5987 } else if (TC1 == Type::Record) {
5988 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
5989 return false;
5990
5991 return isLayoutCompatible(C,
5992 cast<RecordType>(T1)->getDecl(),
5993 cast<RecordType>(T2)->getDecl());
5994 }
5995
5996 return false;
5997}
5998}
5999
6000//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
6001
6002namespace {
6003/// \brief Given a type tag expression find the type tag itself.
6004///
6005/// \param TypeExpr Type tag expression, as it appears in user's code.
6006///
6007/// \param VD Declaration of an identifier that appears in a type tag.
6008///
6009/// \param MagicValue Type tag magic value.
6010bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
6011 const ValueDecl **VD, uint64_t *MagicValue) {
6012 while(true) {
6013 if (!TypeExpr)
6014 return false;
6015
6016 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
6017
6018 switch (TypeExpr->getStmtClass()) {
6019 case Stmt::UnaryOperatorClass: {
6020 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
6021 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
6022 TypeExpr = UO->getSubExpr();
6023 continue;
6024 }
6025 return false;
6026 }
6027
6028 case Stmt::DeclRefExprClass: {
6029 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
6030 *VD = DRE->getDecl();
6031 return true;
6032 }
6033
6034 case Stmt::IntegerLiteralClass: {
6035 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
6036 llvm::APInt MagicValueAPInt = IL->getValue();
6037 if (MagicValueAPInt.getActiveBits() <= 64) {
6038 *MagicValue = MagicValueAPInt.getZExtValue();
6039 return true;
6040 } else
6041 return false;
6042 }
6043
6044 case Stmt::BinaryConditionalOperatorClass:
6045 case Stmt::ConditionalOperatorClass: {
6046 const AbstractConditionalOperator *ACO =
6047 cast<AbstractConditionalOperator>(TypeExpr);
6048 bool Result;
6049 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
6050 if (Result)
6051 TypeExpr = ACO->getTrueExpr();
6052 else
6053 TypeExpr = ACO->getFalseExpr();
6054 continue;
6055 }
6056 return false;
6057 }
6058
6059 case Stmt::BinaryOperatorClass: {
6060 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
6061 if (BO->getOpcode() == BO_Comma) {
6062 TypeExpr = BO->getRHS();
6063 continue;
6064 }
6065 return false;
6066 }
6067
6068 default:
6069 return false;
6070 }
6071 }
6072}
6073
6074/// \brief Retrieve the C type corresponding to type tag TypeExpr.
6075///
6076/// \param TypeExpr Expression that specifies a type tag.
6077///
6078/// \param MagicValues Registered magic values.
6079///
6080/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
6081/// kind.
6082///
6083/// \param TypeInfo Information about the corresponding C type.
6084///
6085/// \returns true if the corresponding C type was found.
6086bool GetMatchingCType(
6087 const IdentifierInfo *ArgumentKind,
6088 const Expr *TypeExpr, const ASTContext &Ctx,
6089 const llvm::DenseMap<Sema::TypeTagMagicValue,
6090 Sema::TypeTagData> *MagicValues,
6091 bool &FoundWrongKind,
6092 Sema::TypeTagData &TypeInfo) {
6093 FoundWrongKind = false;
6094
6095 // Variable declaration that has type_tag_for_datatype attribute.
6096 const ValueDecl *VD = NULL;
6097
6098 uint64_t MagicValue;
6099
6100 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
6101 return false;
6102
6103 if (VD) {
6104 for (specific_attr_iterator<TypeTagForDatatypeAttr>
6105 I = VD->specific_attr_begin<TypeTagForDatatypeAttr>(),
6106 E = VD->specific_attr_end<TypeTagForDatatypeAttr>();
6107 I != E; ++I) {
6108 if (I->getArgumentKind() != ArgumentKind) {
6109 FoundWrongKind = true;
6110 return false;
6111 }
6112 TypeInfo.Type = I->getMatchingCType();
6113 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
6114 TypeInfo.MustBeNull = I->getMustBeNull();
6115 return true;
6116 }
6117 return false;
6118 }
6119
6120 if (!MagicValues)
6121 return false;
6122
6123 llvm::DenseMap<Sema::TypeTagMagicValue,
6124 Sema::TypeTagData>::const_iterator I =
6125 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
6126 if (I == MagicValues->end())
6127 return false;
6128
6129 TypeInfo = I->second;
6130 return true;
6131}
6132} // unnamed namespace
6133
6134void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
6135 uint64_t MagicValue, QualType Type,
6136 bool LayoutCompatible,
6137 bool MustBeNull) {
6138 if (!TypeTagForDatatypeMagicValues)
6139 TypeTagForDatatypeMagicValues.reset(
6140 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
6141
6142 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
6143 (*TypeTagForDatatypeMagicValues)[Magic] =
6144 TypeTagData(Type, LayoutCompatible, MustBeNull);
6145}
6146
6147namespace {
6148bool IsSameCharType(QualType T1, QualType T2) {
6149 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
6150 if (!BT1)
6151 return false;
6152
6153 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
6154 if (!BT2)
6155 return false;
6156
6157 BuiltinType::Kind T1Kind = BT1->getKind();
6158 BuiltinType::Kind T2Kind = BT2->getKind();
6159
6160 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
6161 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
6162 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
6163 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
6164}
6165} // unnamed namespace
6166
6167void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
6168 const Expr * const *ExprArgs) {
6169 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
6170 bool IsPointerAttr = Attr->getIsPointer();
6171
6172 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
6173 bool FoundWrongKind;
6174 TypeTagData TypeInfo;
6175 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
6176 TypeTagForDatatypeMagicValues.get(),
6177 FoundWrongKind, TypeInfo)) {
6178 if (FoundWrongKind)
6179 Diag(TypeTagExpr->getExprLoc(),
6180 diag::warn_type_tag_for_datatype_wrong_kind)
6181 << TypeTagExpr->getSourceRange();
6182 return;
6183 }
6184
6185 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
6186 if (IsPointerAttr) {
6187 // Skip implicit cast of pointer to `void *' (as a function argument).
6188 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
6189 if (ICE->getType()->isVoidPointerType())
6190 ArgumentExpr = ICE->getSubExpr();
6191 }
6192 QualType ArgumentType = ArgumentExpr->getType();
6193
6194 // Passing a `void*' pointer shouldn't trigger a warning.
6195 if (IsPointerAttr && ArgumentType->isVoidPointerType())
6196 return;
6197
6198 if (TypeInfo.MustBeNull) {
6199 // Type tag with matching void type requires a null pointer.
6200 if (!ArgumentExpr->isNullPointerConstant(Context,
6201 Expr::NPC_ValueDependentIsNotNull)) {
6202 Diag(ArgumentExpr->getExprLoc(),
6203 diag::warn_type_safety_null_pointer_required)
6204 << ArgumentKind->getName()
6205 << ArgumentExpr->getSourceRange()
6206 << TypeTagExpr->getSourceRange();
6207 }
6208 return;
6209 }
6210
6211 QualType RequiredType = TypeInfo.Type;
6212 if (IsPointerAttr)
6213 RequiredType = Context.getPointerType(RequiredType);
6214
6215 bool mismatch = false;
6216 if (!TypeInfo.LayoutCompatible) {
6217 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
6218
6219 // C++11 [basic.fundamental] p1:
6220 // Plain char, signed char, and unsigned char are three distinct types.
6221 //
6222 // But we treat plain `char' as equivalent to `signed char' or `unsigned
6223 // char' depending on the current char signedness mode.
6224 if (mismatch)
6225 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
6226 RequiredType->getPointeeType())) ||
6227 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
6228 mismatch = false;
6229 } else
6230 if (IsPointerAttr)
6231 mismatch = !isLayoutCompatible(Context,
6232 ArgumentType->getPointeeType(),
6233 RequiredType->getPointeeType());
6234 else
6235 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
6236
6237 if (mismatch)
6238 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
6239 << ArgumentType << ArgumentKind->getName()
6240 << TypeInfo.LayoutCompatible << RequiredType
6241 << ArgumentExpr->getSourceRange()
6242 << TypeTagExpr->getSourceRange();
6243}