blob: 1664d3084700d3e6576844afe238db60b4d83feb [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 McCall2d887082010-08-25 22:03:47 +000015#include "clang/Sema/SemaInternal.h"
Chris Lattner59907c42007-08-10 20:18:51 +000016#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000017#include "clang/AST/CharUnits.h"
John McCall384aff82010-08-25 07:42:41 +000018#include "clang/AST/DeclCXX.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000019#include "clang/AST/DeclObjC.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000020#include "clang/AST/EvaluatedExprVisitor.h"
David Blaikiebe0ee872012-05-15 16:56:36 +000021#include "clang/AST/Expr.h"
Ted Kremenek23245122007-08-20 16:18:38 +000022#include "clang/AST/ExprCXX.h"
Ted Kremenek7ff22b22008-06-16 18:00:42 +000023#include "clang/AST/ExprObjC.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000024#include "clang/AST/StmtCXX.h"
25#include "clang/AST/StmtObjC.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000026#include "clang/Analysis/Analyses/FormatString.h"
27#include "clang/Basic/ConvertUTF.h"
Eric Christopher691ebc32010-04-17 02:26:23 +000028#include "clang/Basic/TargetBuiltins.h"
Nate Begeman26a31422010-06-08 02:47:44 +000029#include "clang/Basic/TargetInfo.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000030#include "clang/Lex/Preprocessor.h"
31#include "clang/Sema/Initialization.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000032#include "clang/Sema/Lookup.h"
33#include "clang/Sema/ScopeInfo.h"
34#include "clang/Sema/Sema.h"
35#include "llvm/ADT/BitVector.h"
36#include "llvm/ADT/STLExtras.h"
37#include "llvm/ADT/SmallString.h"
38#include "llvm/Support/raw_ostream.h"
Zhongxing Xua1f3dba2009-05-20 01:55:10 +000039#include <limits>
Chris Lattner59907c42007-08-10 20:18:51 +000040using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000041using namespace sema;
Chris Lattner59907c42007-08-10 20:18:51 +000042
Chris Lattner60800082009-02-18 17:49:48 +000043SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
44 unsigned ByteNo) const {
Chris Lattner08f92e32010-11-17 07:37:15 +000045 return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +000046 PP.getLangOpts(), PP.getTargetInfo());
Chris Lattner60800082009-02-18 17:49:48 +000047}
48
John McCall8e10f3b2011-02-26 05:39:39 +000049/// Checks that a call expression's argument count is the desired number.
50/// This is useful when doing custom type-checking. Returns true on error.
51static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
52 unsigned argCount = call->getNumArgs();
53 if (argCount == desiredArgCount) return false;
54
55 if (argCount < desiredArgCount)
56 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
57 << 0 /*function call*/ << desiredArgCount << argCount
58 << call->getSourceRange();
59
60 // Highlight all the excess arguments.
61 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
62 call->getArg(argCount - 1)->getLocEnd());
63
64 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
65 << 0 /*function call*/ << desiredArgCount << argCount
66 << call->getArg(1)->getSourceRange();
67}
68
Julien Lerougee5939212012-04-28 17:39:16 +000069/// Check that the first argument to __builtin_annotation is an integer
70/// and the second argument is a non-wide string literal.
71static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
72 if (checkArgCount(S, TheCall, 2))
73 return true;
74
75 // First argument should be an integer.
76 Expr *ValArg = TheCall->getArg(0);
77 QualType Ty = ValArg->getType();
78 if (!Ty->isIntegerType()) {
79 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
80 << ValArg->getSourceRange();
Julien Lerouge77f68bb2011-09-09 22:41:49 +000081 return true;
82 }
Julien Lerougee5939212012-04-28 17:39:16 +000083
84 // Second argument should be a constant string.
85 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
86 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
87 if (!Literal || !Literal->isAscii()) {
88 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
89 << StrArg->getSourceRange();
90 return true;
91 }
92
93 TheCall->setType(Ty);
Julien Lerouge77f68bb2011-09-09 22:41:49 +000094 return false;
95}
96
John McCall60d7b3a2010-08-24 06:29:42 +000097ExprResult
Anders Carlssond406bf02009-08-16 01:56:34 +000098Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
John McCall60d7b3a2010-08-24 06:29:42 +000099 ExprResult TheCallResult(Owned(TheCall));
Douglas Gregor2def4832008-11-17 20:34:05 +0000100
Chris Lattner946928f2010-10-01 23:23:24 +0000101 // Find out if any arguments are required to be integer constant expressions.
102 unsigned ICEArguments = 0;
103 ASTContext::GetBuiltinTypeError Error;
104 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
105 if (Error != ASTContext::GE_None)
106 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
107
108 // If any arguments are required to be ICE's, check and diagnose.
109 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
110 // Skip arguments not required to be ICE's.
111 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
112
113 llvm::APSInt Result;
114 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
115 return true;
116 ICEArguments &= ~(1 << ArgNo);
117 }
118
Anders Carlssond406bf02009-08-16 01:56:34 +0000119 switch (BuiltinID) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000120 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000121 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000122 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000123 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000124 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000125 break;
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000126 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000127 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000128 if (SemaBuiltinVAStart(TheCall))
129 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000130 break;
Chris Lattner1b9a0792007-12-20 00:26:33 +0000131 case Builtin::BI__builtin_isgreater:
132 case Builtin::BI__builtin_isgreaterequal:
133 case Builtin::BI__builtin_isless:
134 case Builtin::BI__builtin_islessequal:
135 case Builtin::BI__builtin_islessgreater:
136 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000137 if (SemaBuiltinUnorderedCompare(TheCall))
138 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000139 break;
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000140 case Builtin::BI__builtin_fpclassify:
141 if (SemaBuiltinFPClassification(TheCall, 6))
142 return ExprError();
143 break;
Eli Friedman9ac6f622009-08-31 20:06:00 +0000144 case Builtin::BI__builtin_isfinite:
145 case Builtin::BI__builtin_isinf:
146 case Builtin::BI__builtin_isinf_sign:
147 case Builtin::BI__builtin_isnan:
148 case Builtin::BI__builtin_isnormal:
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000149 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman9ac6f622009-08-31 20:06:00 +0000150 return ExprError();
151 break;
Eli Friedmand38617c2008-05-14 19:38:39 +0000152 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000153 return SemaBuiltinShuffleVector(TheCall);
154 // TheCall will be freed by the smart pointer here, but that's fine, since
155 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000156 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000157 if (SemaBuiltinPrefetch(TheCall))
158 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000159 break;
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000160 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000161 if (SemaBuiltinObjectSize(TheCall))
162 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000163 break;
Eli Friedmand875fed2009-05-03 04:46:36 +0000164 case Builtin::BI__builtin_longjmp:
165 if (SemaBuiltinLongjmp(TheCall))
166 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000167 break;
John McCall8e10f3b2011-02-26 05:39:39 +0000168
169 case Builtin::BI__builtin_classify_type:
170 if (checkArgCount(*this, TheCall, 1)) return true;
171 TheCall->setType(Context.IntTy);
172 break;
Chris Lattner75c29a02010-10-12 17:47:42 +0000173 case Builtin::BI__builtin_constant_p:
John McCall8e10f3b2011-02-26 05:39:39 +0000174 if (checkArgCount(*this, TheCall, 1)) return true;
175 TheCall->setType(Context.IntTy);
Chris Lattner75c29a02010-10-12 17:47:42 +0000176 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000177 case Builtin::BI__sync_fetch_and_add:
Douglas Gregora9766412011-11-28 16:30:08 +0000178 case Builtin::BI__sync_fetch_and_add_1:
179 case Builtin::BI__sync_fetch_and_add_2:
180 case Builtin::BI__sync_fetch_and_add_4:
181 case Builtin::BI__sync_fetch_and_add_8:
182 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000183 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregora9766412011-11-28 16:30:08 +0000184 case Builtin::BI__sync_fetch_and_sub_1:
185 case Builtin::BI__sync_fetch_and_sub_2:
186 case Builtin::BI__sync_fetch_and_sub_4:
187 case Builtin::BI__sync_fetch_and_sub_8:
188 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000189 case Builtin::BI__sync_fetch_and_or:
Douglas Gregora9766412011-11-28 16:30:08 +0000190 case Builtin::BI__sync_fetch_and_or_1:
191 case Builtin::BI__sync_fetch_and_or_2:
192 case Builtin::BI__sync_fetch_and_or_4:
193 case Builtin::BI__sync_fetch_and_or_8:
194 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000195 case Builtin::BI__sync_fetch_and_and:
Douglas Gregora9766412011-11-28 16:30:08 +0000196 case Builtin::BI__sync_fetch_and_and_1:
197 case Builtin::BI__sync_fetch_and_and_2:
198 case Builtin::BI__sync_fetch_and_and_4:
199 case Builtin::BI__sync_fetch_and_and_8:
200 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000201 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregora9766412011-11-28 16:30:08 +0000202 case Builtin::BI__sync_fetch_and_xor_1:
203 case Builtin::BI__sync_fetch_and_xor_2:
204 case Builtin::BI__sync_fetch_and_xor_4:
205 case Builtin::BI__sync_fetch_and_xor_8:
206 case Builtin::BI__sync_fetch_and_xor_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000207 case Builtin::BI__sync_add_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000208 case Builtin::BI__sync_add_and_fetch_1:
209 case Builtin::BI__sync_add_and_fetch_2:
210 case Builtin::BI__sync_add_and_fetch_4:
211 case Builtin::BI__sync_add_and_fetch_8:
212 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000213 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000214 case Builtin::BI__sync_sub_and_fetch_1:
215 case Builtin::BI__sync_sub_and_fetch_2:
216 case Builtin::BI__sync_sub_and_fetch_4:
217 case Builtin::BI__sync_sub_and_fetch_8:
218 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000219 case Builtin::BI__sync_and_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000220 case Builtin::BI__sync_and_and_fetch_1:
221 case Builtin::BI__sync_and_and_fetch_2:
222 case Builtin::BI__sync_and_and_fetch_4:
223 case Builtin::BI__sync_and_and_fetch_8:
224 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000225 case Builtin::BI__sync_or_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000226 case Builtin::BI__sync_or_and_fetch_1:
227 case Builtin::BI__sync_or_and_fetch_2:
228 case Builtin::BI__sync_or_and_fetch_4:
229 case Builtin::BI__sync_or_and_fetch_8:
230 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000231 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000232 case Builtin::BI__sync_xor_and_fetch_1:
233 case Builtin::BI__sync_xor_and_fetch_2:
234 case Builtin::BI__sync_xor_and_fetch_4:
235 case Builtin::BI__sync_xor_and_fetch_8:
236 case Builtin::BI__sync_xor_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000237 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000238 case Builtin::BI__sync_val_compare_and_swap_1:
239 case Builtin::BI__sync_val_compare_and_swap_2:
240 case Builtin::BI__sync_val_compare_and_swap_4:
241 case Builtin::BI__sync_val_compare_and_swap_8:
242 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000243 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000244 case Builtin::BI__sync_bool_compare_and_swap_1:
245 case Builtin::BI__sync_bool_compare_and_swap_2:
246 case Builtin::BI__sync_bool_compare_and_swap_4:
247 case Builtin::BI__sync_bool_compare_and_swap_8:
248 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000249 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregora9766412011-11-28 16:30:08 +0000250 case Builtin::BI__sync_lock_test_and_set_1:
251 case Builtin::BI__sync_lock_test_and_set_2:
252 case Builtin::BI__sync_lock_test_and_set_4:
253 case Builtin::BI__sync_lock_test_and_set_8:
254 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000255 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +0000256 case Builtin::BI__sync_lock_release_1:
257 case Builtin::BI__sync_lock_release_2:
258 case Builtin::BI__sync_lock_release_4:
259 case Builtin::BI__sync_lock_release_8:
260 case Builtin::BI__sync_lock_release_16:
Chris Lattner23aa9c82011-04-09 03:57:26 +0000261 case Builtin::BI__sync_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000262 case Builtin::BI__sync_swap_1:
263 case Builtin::BI__sync_swap_2:
264 case Builtin::BI__sync_swap_4:
265 case Builtin::BI__sync_swap_8:
266 case Builtin::BI__sync_swap_16:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000267 return SemaBuiltinAtomicOverloaded(TheCallResult);
Richard Smithff34d402012-04-12 05:08:17 +0000268#define BUILTIN(ID, TYPE, ATTRS)
269#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
270 case Builtin::BI##ID: \
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000271 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithff34d402012-04-12 05:08:17 +0000272#include "clang/Basic/Builtins.def"
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000273 case Builtin::BI__builtin_annotation:
Julien Lerougee5939212012-04-28 17:39:16 +0000274 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000275 return ExprError();
276 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000277 }
278
279 // Since the target specific builtins for each arch overlap, only check those
280 // of the arch we are compiling for.
281 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000282 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman26a31422010-06-08 02:47:44 +0000283 case llvm::Triple::arm:
284 case llvm::Triple::thumb:
285 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
286 return ExprError();
287 break;
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000288 case llvm::Triple::mips:
289 case llvm::Triple::mipsel:
290 case llvm::Triple::mips64:
291 case llvm::Triple::mips64el:
292 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
293 return ExprError();
294 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000295 default:
296 break;
297 }
298 }
299
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000300 return TheCallResult;
Nate Begeman26a31422010-06-08 02:47:44 +0000301}
302
Nate Begeman61eecf52010-06-14 05:21:25 +0000303// Get the valid immediate range for the specified NEON type code.
304static unsigned RFT(unsigned t, bool shift = false) {
Bob Wilsonda95f732011-11-08 01:16:11 +0000305 NeonTypeFlags Type(t);
306 int IsQuad = Type.isQuad();
307 switch (Type.getEltType()) {
308 case NeonTypeFlags::Int8:
309 case NeonTypeFlags::Poly8:
310 return shift ? 7 : (8 << IsQuad) - 1;
311 case NeonTypeFlags::Int16:
312 case NeonTypeFlags::Poly16:
313 return shift ? 15 : (4 << IsQuad) - 1;
314 case NeonTypeFlags::Int32:
315 return shift ? 31 : (2 << IsQuad) - 1;
316 case NeonTypeFlags::Int64:
317 return shift ? 63 : (1 << IsQuad) - 1;
318 case NeonTypeFlags::Float16:
319 assert(!shift && "cannot shift float types!");
320 return (4 << IsQuad) - 1;
321 case NeonTypeFlags::Float32:
322 assert(!shift && "cannot shift float types!");
323 return (2 << IsQuad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000324 }
David Blaikie7530c032012-01-17 06:56:22 +0000325 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman61eecf52010-06-14 05:21:25 +0000326}
327
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000328/// getNeonEltType - Return the QualType corresponding to the elements of
329/// the vector type specified by the NeonTypeFlags. This is used to check
330/// the pointer arguments for Neon load/store intrinsics.
331static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context) {
332 switch (Flags.getEltType()) {
333 case NeonTypeFlags::Int8:
334 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
335 case NeonTypeFlags::Int16:
336 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
337 case NeonTypeFlags::Int32:
338 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
339 case NeonTypeFlags::Int64:
340 return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy;
341 case NeonTypeFlags::Poly8:
342 return Context.SignedCharTy;
343 case NeonTypeFlags::Poly16:
344 return Context.ShortTy;
345 case NeonTypeFlags::Float16:
346 return Context.UnsignedShortTy;
347 case NeonTypeFlags::Float32:
348 return Context.FloatTy;
349 }
David Blaikie7530c032012-01-17 06:56:22 +0000350 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000351}
352
Nate Begeman26a31422010-06-08 02:47:44 +0000353bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000354 llvm::APSInt Result;
355
Richard Smithf8ee6bc2012-08-14 01:28:02 +0000356 uint64_t mask = 0;
Nate Begeman61eecf52010-06-14 05:21:25 +0000357 unsigned TV = 0;
Bob Wilson46482552011-11-16 21:32:23 +0000358 int PtrArgNum = -1;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000359 bool HasConstPtr = false;
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000360 switch (BuiltinID) {
Nate Begemana23326b2010-06-17 04:17:01 +0000361#define GET_NEON_OVERLOAD_CHECK
362#include "clang/Basic/arm_neon.inc"
363#undef GET_NEON_OVERLOAD_CHECK
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000364 }
365
Nate Begeman0d15c532010-06-13 04:47:52 +0000366 // For NEON intrinsics which are overloaded on vector element type, validate
367 // the immediate which specifies which variant to emit.
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000368 unsigned ImmArg = TheCall->getNumArgs()-1;
Nate Begeman0d15c532010-06-13 04:47:52 +0000369 if (mask) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000370 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
Nate Begeman0d15c532010-06-13 04:47:52 +0000371 return true;
372
Bob Wilsonda95f732011-11-08 01:16:11 +0000373 TV = Result.getLimitedValue(64);
Richard Smithf8ee6bc2012-08-14 01:28:02 +0000374 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
Nate Begeman0d15c532010-06-13 04:47:52 +0000375 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000376 << TheCall->getArg(ImmArg)->getSourceRange();
377 }
378
Bob Wilson46482552011-11-16 21:32:23 +0000379 if (PtrArgNum >= 0) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000380 // Check that pointer arguments have the specified type.
Bob Wilson46482552011-11-16 21:32:23 +0000381 Expr *Arg = TheCall->getArg(PtrArgNum);
382 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
383 Arg = ICE->getSubExpr();
384 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
385 QualType RHSTy = RHS.get()->getType();
386 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context);
387 if (HasConstPtr)
388 EltTy = EltTy.withConst();
389 QualType LHSTy = Context.getPointerType(EltTy);
390 AssignConvertType ConvTy;
391 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
392 if (RHS.isInvalid())
393 return true;
394 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
395 RHS.get(), AA_Assigning))
396 return true;
Nate Begeman0d15c532010-06-13 04:47:52 +0000397 }
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000398
Nate Begeman0d15c532010-06-13 04:47:52 +0000399 // For NEON intrinsics which take an immediate value as part of the
400 // instruction, range check them here.
Nate Begeman61eecf52010-06-14 05:21:25 +0000401 unsigned i = 0, l = 0, u = 0;
Nate Begeman0d15c532010-06-13 04:47:52 +0000402 switch (BuiltinID) {
403 default: return false;
Nate Begemanbb37f502010-07-29 22:48:34 +0000404 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
405 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begeman99c40bb2010-08-03 21:32:34 +0000406 case ARM::BI__builtin_arm_vcvtr_f:
407 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Nate Begemana23326b2010-06-17 04:17:01 +0000408#define GET_NEON_IMMEDIATE_CHECK
409#include "clang/Basic/arm_neon.inc"
410#undef GET_NEON_IMMEDIATE_CHECK
Nate Begeman0d15c532010-06-13 04:47:52 +0000411 };
412
Douglas Gregor592a4232012-06-29 01:05:22 +0000413 // We can't check the value of a dependent argument.
414 if (TheCall->getArg(i)->isTypeDependent() ||
415 TheCall->getArg(i)->isValueDependent())
416 return false;
417
Nate Begeman61eecf52010-06-14 05:21:25 +0000418 // Check that the immediate argument is actually a constant.
Nate Begeman0d15c532010-06-13 04:47:52 +0000419 if (SemaBuiltinConstantArg(TheCall, i, Result))
420 return true;
421
Nate Begeman61eecf52010-06-14 05:21:25 +0000422 // Range check against the upper/lower values for this isntruction.
Nate Begeman0d15c532010-06-13 04:47:52 +0000423 unsigned Val = Result.getZExtValue();
Nate Begeman61eecf52010-06-14 05:21:25 +0000424 if (Val < l || Val > (u + l))
Nate Begeman0d15c532010-06-13 04:47:52 +0000425 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramer476d8b82010-08-11 14:47:12 +0000426 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begeman0d15c532010-06-13 04:47:52 +0000427
Nate Begeman99c40bb2010-08-03 21:32:34 +0000428 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman26a31422010-06-08 02:47:44 +0000429 return false;
Anders Carlssond406bf02009-08-16 01:56:34 +0000430}
Daniel Dunbarde454282008-10-02 18:44:07 +0000431
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000432bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
433 unsigned i = 0, l = 0, u = 0;
434 switch (BuiltinID) {
435 default: return false;
436 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
437 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyanbe22cb82012-08-27 12:29:20 +0000438 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
439 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
440 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
441 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
442 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000443 };
444
445 // We can't check the value of a dependent argument.
446 if (TheCall->getArg(i)->isTypeDependent() ||
447 TheCall->getArg(i)->isValueDependent())
448 return false;
449
450 // Check that the immediate argument is actually a constant.
451 llvm::APSInt Result;
452 if (SemaBuiltinConstantArg(TheCall, i, Result))
453 return true;
454
455 // Range check against the upper/lower values for this instruction.
456 unsigned Val = Result.getZExtValue();
457 if (Val < l || Val > u)
458 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
459 << l << u << TheCall->getArg(i)->getSourceRange();
460
461 return false;
462}
463
Richard Smith831421f2012-06-25 20:30:08 +0000464/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
465/// parameter with the FormatAttr's correct format_idx and firstDataArg.
466/// Returns true when the format fits the function and the FormatStringInfo has
467/// been populated.
468bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
469 FormatStringInfo *FSI) {
470 FSI->HasVAListArg = Format->getFirstArg() == 0;
471 FSI->FormatIdx = Format->getFormatIdx() - 1;
472 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssond406bf02009-08-16 01:56:34 +0000473
Richard Smith831421f2012-06-25 20:30:08 +0000474 // The way the format attribute works in GCC, the implicit this argument
475 // of member functions is counted. However, it doesn't appear in our own
476 // lists, so decrement format_idx in that case.
477 if (IsCXXMember) {
478 if(FSI->FormatIdx == 0)
479 return false;
480 --FSI->FormatIdx;
481 if (FSI->FirstDataArg != 0)
482 --FSI->FirstDataArg;
483 }
484 return true;
485}
Mike Stump1eb44332009-09-09 15:08:12 +0000486
Richard Smith831421f2012-06-25 20:30:08 +0000487/// Handles the checks for format strings, non-POD arguments to vararg
488/// functions, and NULL arguments passed to non-NULL parameters.
489void Sema::checkCall(NamedDecl *FDecl, Expr **Args,
490 unsigned NumArgs,
491 unsigned NumProtoArgs,
492 bool IsMemberFunction,
493 SourceLocation Loc,
494 SourceRange Range,
495 VariadicCallType CallType) {
Jordan Rose66360e22012-10-02 01:49:54 +0000496 if (CurContext->isDependentContext())
497 return;
Daniel Dunbarde454282008-10-02 18:44:07 +0000498
Ted Kremenekc82faca2010-09-09 04:33:05 +0000499 // Printf and scanf checking.
Richard Smith831421f2012-06-25 20:30:08 +0000500 bool HandledFormatString = false;
Ted Kremenekc82faca2010-09-09 04:33:05 +0000501 for (specific_attr_iterator<FormatAttr>
Richard Smith831421f2012-06-25 20:30:08 +0000502 I = FDecl->specific_attr_begin<FormatAttr>(),
503 E = FDecl->specific_attr_end<FormatAttr>(); I != E ; ++I)
Jordan Roseddcfbc92012-07-19 18:10:23 +0000504 if (CheckFormatArguments(*I, Args, NumArgs, IsMemberFunction, CallType,
505 Loc, Range))
Richard Smith831421f2012-06-25 20:30:08 +0000506 HandledFormatString = true;
507
508 // Refuse POD arguments that weren't caught by the format string
509 // checks above.
510 if (!HandledFormatString && CallType != VariadicDoesNotApply)
Ted Kremenek0234bfa2012-10-11 19:06:43 +0000511 for (unsigned ArgIdx = NumProtoArgs; ArgIdx < NumArgs; ++ArgIdx) {
512 // Args[ArgIdx] can be null in malformed code.
513 if (Expr *Arg = Args[ArgIdx])
514 variadicArgumentPODCheck(Arg, CallType);
515 }
Mike Stump1eb44332009-09-09 15:08:12 +0000516
Ted Kremenekc82faca2010-09-09 04:33:05 +0000517 for (specific_attr_iterator<NonNullAttr>
Richard Smith831421f2012-06-25 20:30:08 +0000518 I = FDecl->specific_attr_begin<NonNullAttr>(),
519 E = FDecl->specific_attr_end<NonNullAttr>(); I != E; ++I)
520 CheckNonNullArguments(*I, Args, Loc);
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +0000521
522 // Type safety checking.
523 for (specific_attr_iterator<ArgumentWithTypeTagAttr>
524 i = FDecl->specific_attr_begin<ArgumentWithTypeTagAttr>(),
525 e = FDecl->specific_attr_end<ArgumentWithTypeTagAttr>(); i != e; ++i) {
526 CheckArgumentWithTypeTag(*i, Args);
527 }
Richard Smith831421f2012-06-25 20:30:08 +0000528}
529
530/// CheckConstructorCall - Check a constructor call for correctness and safety
531/// properties not enforced by the C type system.
532void Sema::CheckConstructorCall(FunctionDecl *FDecl, Expr **Args,
533 unsigned NumArgs,
534 const FunctionProtoType *Proto,
535 SourceLocation Loc) {
536 VariadicCallType CallType =
537 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
538 checkCall(FDecl, Args, NumArgs, Proto->getNumArgs(),
539 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
540}
541
542/// CheckFunctionCall - Check a direct function call for various correctness
543/// and safety properties not strictly enforced by the C type system.
544bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
545 const FunctionProtoType *Proto) {
Eli Friedman2edcde82012-10-11 00:30:58 +0000546 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
547 isa<CXXMethodDecl>(FDecl);
548 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
549 IsMemberOperatorCall;
Richard Smith831421f2012-06-25 20:30:08 +0000550 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
551 TheCall->getCallee());
552 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
Eli Friedman2edcde82012-10-11 00:30:58 +0000553 Expr** Args = TheCall->getArgs();
554 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmandf75b0c2012-10-11 00:34:15 +0000555 if (IsMemberOperatorCall) {
Eli Friedman2edcde82012-10-11 00:30:58 +0000556 // If this is a call to a member operator, hide the first argument
557 // from checkCall.
558 // FIXME: Our choice of AST representation here is less than ideal.
559 ++Args;
560 --NumArgs;
561 }
562 checkCall(FDecl, Args, NumArgs, NumProtoArgs,
Richard Smith831421f2012-06-25 20:30:08 +0000563 IsMemberFunction, TheCall->getRParenLoc(),
564 TheCall->getCallee()->getSourceRange(), CallType);
565
566 IdentifierInfo *FnInfo = FDecl->getIdentifier();
567 // None of the checks below are needed for functions that don't have
568 // simple names (e.g., C++ conversion functions).
569 if (!FnInfo)
570 return false;
Sebastian Redl0eb23302009-01-19 00:08:26 +0000571
Anna Zaks0a151a12012-01-17 00:37:07 +0000572 unsigned CMId = FDecl->getMemoryFunctionKind();
573 if (CMId == 0)
Anna Zaksd9b859a2012-01-13 21:52:01 +0000574 return false;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000575
Anna Zaksd9b859a2012-01-13 21:52:01 +0000576 // Handle memory setting and copying functions.
Anna Zaks0a151a12012-01-17 00:37:07 +0000577 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000578 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaksc36bedc2012-02-01 19:08:57 +0000579 else if (CMId == Builtin::BIstrncat)
580 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaksd9b859a2012-01-13 21:52:01 +0000581 else
Anna Zaks0a151a12012-01-17 00:37:07 +0000582 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth7ccc95b2011-04-27 07:05:31 +0000583
Anders Carlssond406bf02009-08-16 01:56:34 +0000584 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000585}
586
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000587bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
588 Expr **Args, unsigned NumArgs) {
Richard Smith831421f2012-06-25 20:30:08 +0000589 VariadicCallType CallType =
590 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000591
Richard Smith831421f2012-06-25 20:30:08 +0000592 checkCall(Method, Args, NumArgs, Method->param_size(),
593 /*IsMemberFunction=*/false,
594 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000595
596 return false;
597}
598
Richard Smith831421f2012-06-25 20:30:08 +0000599bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall,
600 const FunctionProtoType *Proto) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000601 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
602 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000603 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000604
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000605 QualType Ty = V->getType();
606 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000607 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000608
Richard Smith831421f2012-06-25 20:30:08 +0000609 VariadicCallType CallType =
610 Proto && Proto->isVariadic() ? VariadicBlock : VariadicDoesNotApply ;
611 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
Anders Carlssond406bf02009-08-16 01:56:34 +0000612
Richard Smith831421f2012-06-25 20:30:08 +0000613 checkCall(NDecl, TheCall->getArgs(), TheCall->getNumArgs(),
614 NumProtoArgs, /*IsMemberFunction=*/false,
615 TheCall->getRParenLoc(),
616 TheCall->getCallee()->getSourceRange(), CallType);
617
Anders Carlssond406bf02009-08-16 01:56:34 +0000618 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000619}
620
Richard Smithff34d402012-04-12 05:08:17 +0000621ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
622 AtomicExpr::AtomicOp Op) {
Eli Friedman276b0612011-10-11 02:20:01 +0000623 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
624 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedman276b0612011-10-11 02:20:01 +0000625
Richard Smithff34d402012-04-12 05:08:17 +0000626 // All these operations take one of the following forms:
627 enum {
628 // C __c11_atomic_init(A *, C)
629 Init,
630 // C __c11_atomic_load(A *, int)
631 Load,
632 // void __atomic_load(A *, CP, int)
633 Copy,
634 // C __c11_atomic_add(A *, M, int)
635 Arithmetic,
636 // C __atomic_exchange_n(A *, CP, int)
637 Xchg,
638 // void __atomic_exchange(A *, C *, CP, int)
639 GNUXchg,
640 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
641 C11CmpXchg,
642 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
643 GNUCmpXchg
644 } Form = Init;
645 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
646 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
647 // where:
648 // C is an appropriate type,
649 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
650 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
651 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
652 // the int parameters are for orderings.
Eli Friedman276b0612011-10-11 02:20:01 +0000653
Richard Smithff34d402012-04-12 05:08:17 +0000654 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
655 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
656 && "need to update code for modified C11 atomics");
657 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
658 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
659 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
660 Op == AtomicExpr::AO__atomic_store_n ||
661 Op == AtomicExpr::AO__atomic_exchange_n ||
662 Op == AtomicExpr::AO__atomic_compare_exchange_n;
663 bool IsAddSub = false;
664
665 switch (Op) {
666 case AtomicExpr::AO__c11_atomic_init:
667 Form = Init;
668 break;
669
670 case AtomicExpr::AO__c11_atomic_load:
671 case AtomicExpr::AO__atomic_load_n:
672 Form = Load;
673 break;
674
675 case AtomicExpr::AO__c11_atomic_store:
676 case AtomicExpr::AO__atomic_load:
677 case AtomicExpr::AO__atomic_store:
678 case AtomicExpr::AO__atomic_store_n:
679 Form = Copy;
680 break;
681
682 case AtomicExpr::AO__c11_atomic_fetch_add:
683 case AtomicExpr::AO__c11_atomic_fetch_sub:
684 case AtomicExpr::AO__atomic_fetch_add:
685 case AtomicExpr::AO__atomic_fetch_sub:
686 case AtomicExpr::AO__atomic_add_fetch:
687 case AtomicExpr::AO__atomic_sub_fetch:
688 IsAddSub = true;
689 // Fall through.
690 case AtomicExpr::AO__c11_atomic_fetch_and:
691 case AtomicExpr::AO__c11_atomic_fetch_or:
692 case AtomicExpr::AO__c11_atomic_fetch_xor:
693 case AtomicExpr::AO__atomic_fetch_and:
694 case AtomicExpr::AO__atomic_fetch_or:
695 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smith51b92402012-04-13 06:31:38 +0000696 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithff34d402012-04-12 05:08:17 +0000697 case AtomicExpr::AO__atomic_and_fetch:
698 case AtomicExpr::AO__atomic_or_fetch:
699 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smith51b92402012-04-13 06:31:38 +0000700 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithff34d402012-04-12 05:08:17 +0000701 Form = Arithmetic;
702 break;
703
704 case AtomicExpr::AO__c11_atomic_exchange:
705 case AtomicExpr::AO__atomic_exchange_n:
706 Form = Xchg;
707 break;
708
709 case AtomicExpr::AO__atomic_exchange:
710 Form = GNUXchg;
711 break;
712
713 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
714 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
715 Form = C11CmpXchg;
716 break;
717
718 case AtomicExpr::AO__atomic_compare_exchange:
719 case AtomicExpr::AO__atomic_compare_exchange_n:
720 Form = GNUCmpXchg;
721 break;
722 }
723
724 // Check we have the right number of arguments.
725 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedman276b0612011-10-11 02:20:01 +0000726 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithff34d402012-04-12 05:08:17 +0000727 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +0000728 << TheCall->getCallee()->getSourceRange();
729 return ExprError();
Richard Smithff34d402012-04-12 05:08:17 +0000730 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
731 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedman276b0612011-10-11 02:20:01 +0000732 diag::err_typecheck_call_too_many_args)
Richard Smithff34d402012-04-12 05:08:17 +0000733 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +0000734 << TheCall->getCallee()->getSourceRange();
735 return ExprError();
736 }
737
Richard Smithff34d402012-04-12 05:08:17 +0000738 // Inspect the first argument of the atomic operation.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000739 Expr *Ptr = TheCall->getArg(0);
Eli Friedman276b0612011-10-11 02:20:01 +0000740 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
741 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
742 if (!pointerType) {
Richard Smithff34d402012-04-12 05:08:17 +0000743 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedman276b0612011-10-11 02:20:01 +0000744 << Ptr->getType() << Ptr->getSourceRange();
745 return ExprError();
746 }
747
Richard Smithff34d402012-04-12 05:08:17 +0000748 // For a __c11 builtin, this should be a pointer to an _Atomic type.
749 QualType AtomTy = pointerType->getPointeeType(); // 'A'
750 QualType ValType = AtomTy; // 'C'
751 if (IsC11) {
752 if (!AtomTy->isAtomicType()) {
753 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
754 << Ptr->getType() << Ptr->getSourceRange();
755 return ExprError();
756 }
Richard Smithbc57b102012-09-15 06:09:58 +0000757 if (AtomTy.isConstQualified()) {
758 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
759 << Ptr->getType() << Ptr->getSourceRange();
760 return ExprError();
761 }
Richard Smithff34d402012-04-12 05:08:17 +0000762 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedman276b0612011-10-11 02:20:01 +0000763 }
Eli Friedman276b0612011-10-11 02:20:01 +0000764
Richard Smithff34d402012-04-12 05:08:17 +0000765 // For an arithmetic operation, the implied arithmetic must be well-formed.
766 if (Form == Arithmetic) {
767 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
768 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
769 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
770 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
771 return ExprError();
772 }
773 if (!IsAddSub && !ValType->isIntegerType()) {
774 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
775 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
776 return ExprError();
777 }
778 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
779 // For __atomic_*_n operations, the value type must be a scalar integral or
780 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedman276b0612011-10-11 02:20:01 +0000781 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithff34d402012-04-12 05:08:17 +0000782 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
783 return ExprError();
784 }
785
786 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context)) {
787 // For GNU atomics, require a trivially-copyable type. This is not part of
788 // the GNU atomics specification, but we enforce it for sanity.
789 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedman276b0612011-10-11 02:20:01 +0000790 << Ptr->getType() << Ptr->getSourceRange();
791 return ExprError();
792 }
793
Richard Smithff34d402012-04-12 05:08:17 +0000794 // FIXME: For any builtin other than a load, the ValType must not be
795 // const-qualified.
Eli Friedman276b0612011-10-11 02:20:01 +0000796
797 switch (ValType.getObjCLifetime()) {
798 case Qualifiers::OCL_None:
799 case Qualifiers::OCL_ExplicitNone:
800 // okay
801 break;
802
803 case Qualifiers::OCL_Weak:
804 case Qualifiers::OCL_Strong:
805 case Qualifiers::OCL_Autoreleasing:
Richard Smithff34d402012-04-12 05:08:17 +0000806 // FIXME: Can this happen? By this point, ValType should be known
807 // to be trivially copyable.
Eli Friedman276b0612011-10-11 02:20:01 +0000808 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
809 << ValType << Ptr->getSourceRange();
810 return ExprError();
811 }
812
813 QualType ResultType = ValType;
Richard Smithff34d402012-04-12 05:08:17 +0000814 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedman276b0612011-10-11 02:20:01 +0000815 ResultType = Context.VoidTy;
Richard Smithff34d402012-04-12 05:08:17 +0000816 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedman276b0612011-10-11 02:20:01 +0000817 ResultType = Context.BoolTy;
818
Richard Smithff34d402012-04-12 05:08:17 +0000819 // The type of a parameter passed 'by value'. In the GNU atomics, such
820 // arguments are actually passed as pointers.
821 QualType ByValType = ValType; // 'CP'
822 if (!IsC11 && !IsN)
823 ByValType = Ptr->getType();
824
Eli Friedman276b0612011-10-11 02:20:01 +0000825 // The first argument --- the pointer --- has a fixed type; we
826 // deduce the types of the rest of the arguments accordingly. Walk
827 // the remaining arguments, converting them to the deduced value type.
Richard Smithff34d402012-04-12 05:08:17 +0000828 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedman276b0612011-10-11 02:20:01 +0000829 QualType Ty;
Richard Smithff34d402012-04-12 05:08:17 +0000830 if (i < NumVals[Form] + 1) {
831 switch (i) {
832 case 1:
833 // The second argument is the non-atomic operand. For arithmetic, this
834 // is always passed by value, and for a compare_exchange it is always
835 // passed by address. For the rest, GNU uses by-address and C11 uses
836 // by-value.
837 assert(Form != Load);
838 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
839 Ty = ValType;
840 else if (Form == Copy || Form == Xchg)
841 Ty = ByValType;
842 else if (Form == Arithmetic)
843 Ty = Context.getPointerDiffType();
844 else
845 Ty = Context.getPointerType(ValType.getUnqualifiedType());
846 break;
847 case 2:
848 // The third argument to compare_exchange / GNU exchange is a
849 // (pointer to a) desired value.
850 Ty = ByValType;
851 break;
852 case 3:
853 // The fourth argument to GNU compare_exchange is a 'weak' flag.
854 Ty = Context.BoolTy;
855 break;
856 }
Eli Friedman276b0612011-10-11 02:20:01 +0000857 } else {
858 // The order(s) are always converted to int.
859 Ty = Context.IntTy;
860 }
Richard Smithff34d402012-04-12 05:08:17 +0000861
Eli Friedman276b0612011-10-11 02:20:01 +0000862 InitializedEntity Entity =
863 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithff34d402012-04-12 05:08:17 +0000864 ExprResult Arg = TheCall->getArg(i);
Eli Friedman276b0612011-10-11 02:20:01 +0000865 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
866 if (Arg.isInvalid())
867 return true;
868 TheCall->setArg(i, Arg.get());
869 }
870
Richard Smithff34d402012-04-12 05:08:17 +0000871 // Permute the arguments into a 'consistent' order.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000872 SmallVector<Expr*, 5> SubExprs;
873 SubExprs.push_back(Ptr);
Richard Smithff34d402012-04-12 05:08:17 +0000874 switch (Form) {
875 case Init:
876 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnall7a7ee302012-01-16 17:27:18 +0000877 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +0000878 break;
879 case Load:
880 SubExprs.push_back(TheCall->getArg(1)); // Order
881 break;
882 case Copy:
883 case Arithmetic:
884 case Xchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000885 SubExprs.push_back(TheCall->getArg(2)); // Order
886 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +0000887 break;
888 case GNUXchg:
889 // Note, AtomicExpr::getVal2() has a special case for this atomic.
890 SubExprs.push_back(TheCall->getArg(3)); // Order
891 SubExprs.push_back(TheCall->getArg(1)); // Val1
892 SubExprs.push_back(TheCall->getArg(2)); // Val2
893 break;
894 case C11CmpXchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000895 SubExprs.push_back(TheCall->getArg(3)); // Order
896 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000897 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall2ebb98a2012-03-29 17:58:59 +0000898 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithff34d402012-04-12 05:08:17 +0000899 break;
900 case GNUCmpXchg:
901 SubExprs.push_back(TheCall->getArg(4)); // Order
902 SubExprs.push_back(TheCall->getArg(1)); // Val1
903 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
904 SubExprs.push_back(TheCall->getArg(2)); // Val2
905 SubExprs.push_back(TheCall->getArg(3)); // Weak
906 break;
Eli Friedman276b0612011-10-11 02:20:01 +0000907 }
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000908
909 return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +0000910 SubExprs, ResultType, Op,
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000911 TheCall->getRParenLoc()));
Eli Friedman276b0612011-10-11 02:20:01 +0000912}
913
914
John McCall5f8d6042011-08-27 01:09:30 +0000915/// checkBuiltinArgument - Given a call to a builtin function, perform
916/// normal type-checking on the given argument, updating the call in
917/// place. This is useful when a builtin function requires custom
918/// type-checking for some of its arguments but not necessarily all of
919/// them.
920///
921/// Returns true on error.
922static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
923 FunctionDecl *Fn = E->getDirectCallee();
924 assert(Fn && "builtin call without direct callee!");
925
926 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
927 InitializedEntity Entity =
928 InitializedEntity::InitializeParameter(S.Context, Param);
929
930 ExprResult Arg = E->getArg(0);
931 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
932 if (Arg.isInvalid())
933 return true;
934
935 E->setArg(ArgIndex, Arg.take());
936 return false;
937}
938
Chris Lattner5caa3702009-05-08 06:58:22 +0000939/// SemaBuiltinAtomicOverloaded - We have a call to a function like
940/// __sync_fetch_and_add, which is an overloaded function based on the pointer
941/// type of its first argument. The main ActOnCallExpr routines have already
942/// promoted the types of arguments because all of these calls are prototyped as
943/// void(...).
944///
945/// This function goes through and does final semantic checking for these
946/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +0000947ExprResult
948Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000949 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +0000950 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
951 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
952
953 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +0000954 if (TheCall->getNumArgs() < 1) {
955 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
956 << 0 << 1 << TheCall->getNumArgs()
957 << TheCall->getCallee()->getSourceRange();
958 return ExprError();
959 }
Mike Stump1eb44332009-09-09 15:08:12 +0000960
Chris Lattner5caa3702009-05-08 06:58:22 +0000961 // Inspect the first argument of the atomic builtin. This should always be
962 // a pointer type, whose element is an integral scalar or pointer type.
963 // Because it is a pointer type, we don't have to worry about any implicit
964 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +0000965 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +0000966 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman8c382062012-01-23 02:35:22 +0000967 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
968 if (FirstArgResult.isInvalid())
969 return ExprError();
970 FirstArg = FirstArgResult.take();
971 TheCall->setArg(0, FirstArg);
972
John McCallf85e1932011-06-15 23:02:42 +0000973 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
974 if (!pointerType) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000975 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
976 << FirstArg->getType() << FirstArg->getSourceRange();
977 return ExprError();
978 }
Mike Stump1eb44332009-09-09 15:08:12 +0000979
John McCallf85e1932011-06-15 23:02:42 +0000980 QualType ValType = pointerType->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +0000981 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +0000982 !ValType->isBlockPointerType()) {
983 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
984 << FirstArg->getType() << FirstArg->getSourceRange();
985 return ExprError();
986 }
Chris Lattner5caa3702009-05-08 06:58:22 +0000987
John McCallf85e1932011-06-15 23:02:42 +0000988 switch (ValType.getObjCLifetime()) {
989 case Qualifiers::OCL_None:
990 case Qualifiers::OCL_ExplicitNone:
991 // okay
992 break;
993
994 case Qualifiers::OCL_Weak:
995 case Qualifiers::OCL_Strong:
996 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +0000997 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCallf85e1932011-06-15 23:02:42 +0000998 << ValType << FirstArg->getSourceRange();
999 return ExprError();
1000 }
1001
John McCallb45ae252011-10-05 07:41:44 +00001002 // Strip any qualifiers off ValType.
1003 ValType = ValType.getUnqualifiedType();
1004
Chandler Carruth8d13d222010-07-18 20:54:12 +00001005 // The majority of builtins return a value, but a few have special return
1006 // types, so allow them to override appropriately below.
1007 QualType ResultType = ValType;
1008
Chris Lattner5caa3702009-05-08 06:58:22 +00001009 // We need to figure out which concrete builtin this maps onto. For example,
1010 // __sync_fetch_and_add with a 2 byte object turns into
1011 // __sync_fetch_and_add_2.
1012#define BUILTIN_ROW(x) \
1013 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1014 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +00001015
Chris Lattner5caa3702009-05-08 06:58:22 +00001016 static const unsigned BuiltinIndices[][5] = {
1017 BUILTIN_ROW(__sync_fetch_and_add),
1018 BUILTIN_ROW(__sync_fetch_and_sub),
1019 BUILTIN_ROW(__sync_fetch_and_or),
1020 BUILTIN_ROW(__sync_fetch_and_and),
1021 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +00001022
Chris Lattner5caa3702009-05-08 06:58:22 +00001023 BUILTIN_ROW(__sync_add_and_fetch),
1024 BUILTIN_ROW(__sync_sub_and_fetch),
1025 BUILTIN_ROW(__sync_and_and_fetch),
1026 BUILTIN_ROW(__sync_or_and_fetch),
1027 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +00001028
Chris Lattner5caa3702009-05-08 06:58:22 +00001029 BUILTIN_ROW(__sync_val_compare_and_swap),
1030 BUILTIN_ROW(__sync_bool_compare_and_swap),
1031 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +00001032 BUILTIN_ROW(__sync_lock_release),
1033 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +00001034 };
Mike Stump1eb44332009-09-09 15:08:12 +00001035#undef BUILTIN_ROW
1036
Chris Lattner5caa3702009-05-08 06:58:22 +00001037 // Determine the index of the size.
1038 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +00001039 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +00001040 case 1: SizeIndex = 0; break;
1041 case 2: SizeIndex = 1; break;
1042 case 4: SizeIndex = 2; break;
1043 case 8: SizeIndex = 3; break;
1044 case 16: SizeIndex = 4; break;
1045 default:
Chandler Carruthd2014572010-07-09 18:59:35 +00001046 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1047 << FirstArg->getType() << FirstArg->getSourceRange();
1048 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +00001049 }
Mike Stump1eb44332009-09-09 15:08:12 +00001050
Chris Lattner5caa3702009-05-08 06:58:22 +00001051 // Each of these builtins has one pointer argument, followed by some number of
1052 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1053 // that we ignore. Find out which row of BuiltinIndices to read from as well
1054 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00001055 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +00001056 unsigned BuiltinIndex, NumFixed = 1;
1057 switch (BuiltinID) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001058 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregora9766412011-11-28 16:30:08 +00001059 case Builtin::BI__sync_fetch_and_add:
1060 case Builtin::BI__sync_fetch_and_add_1:
1061 case Builtin::BI__sync_fetch_and_add_2:
1062 case Builtin::BI__sync_fetch_and_add_4:
1063 case Builtin::BI__sync_fetch_and_add_8:
1064 case Builtin::BI__sync_fetch_and_add_16:
1065 BuiltinIndex = 0;
1066 break;
1067
1068 case Builtin::BI__sync_fetch_and_sub:
1069 case Builtin::BI__sync_fetch_and_sub_1:
1070 case Builtin::BI__sync_fetch_and_sub_2:
1071 case Builtin::BI__sync_fetch_and_sub_4:
1072 case Builtin::BI__sync_fetch_and_sub_8:
1073 case Builtin::BI__sync_fetch_and_sub_16:
1074 BuiltinIndex = 1;
1075 break;
1076
1077 case Builtin::BI__sync_fetch_and_or:
1078 case Builtin::BI__sync_fetch_and_or_1:
1079 case Builtin::BI__sync_fetch_and_or_2:
1080 case Builtin::BI__sync_fetch_and_or_4:
1081 case Builtin::BI__sync_fetch_and_or_8:
1082 case Builtin::BI__sync_fetch_and_or_16:
1083 BuiltinIndex = 2;
1084 break;
1085
1086 case Builtin::BI__sync_fetch_and_and:
1087 case Builtin::BI__sync_fetch_and_and_1:
1088 case Builtin::BI__sync_fetch_and_and_2:
1089 case Builtin::BI__sync_fetch_and_and_4:
1090 case Builtin::BI__sync_fetch_and_and_8:
1091 case Builtin::BI__sync_fetch_and_and_16:
1092 BuiltinIndex = 3;
1093 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001094
Douglas Gregora9766412011-11-28 16:30:08 +00001095 case Builtin::BI__sync_fetch_and_xor:
1096 case Builtin::BI__sync_fetch_and_xor_1:
1097 case Builtin::BI__sync_fetch_and_xor_2:
1098 case Builtin::BI__sync_fetch_and_xor_4:
1099 case Builtin::BI__sync_fetch_and_xor_8:
1100 case Builtin::BI__sync_fetch_and_xor_16:
1101 BuiltinIndex = 4;
1102 break;
1103
1104 case Builtin::BI__sync_add_and_fetch:
1105 case Builtin::BI__sync_add_and_fetch_1:
1106 case Builtin::BI__sync_add_and_fetch_2:
1107 case Builtin::BI__sync_add_and_fetch_4:
1108 case Builtin::BI__sync_add_and_fetch_8:
1109 case Builtin::BI__sync_add_and_fetch_16:
1110 BuiltinIndex = 5;
1111 break;
1112
1113 case Builtin::BI__sync_sub_and_fetch:
1114 case Builtin::BI__sync_sub_and_fetch_1:
1115 case Builtin::BI__sync_sub_and_fetch_2:
1116 case Builtin::BI__sync_sub_and_fetch_4:
1117 case Builtin::BI__sync_sub_and_fetch_8:
1118 case Builtin::BI__sync_sub_and_fetch_16:
1119 BuiltinIndex = 6;
1120 break;
1121
1122 case Builtin::BI__sync_and_and_fetch:
1123 case Builtin::BI__sync_and_and_fetch_1:
1124 case Builtin::BI__sync_and_and_fetch_2:
1125 case Builtin::BI__sync_and_and_fetch_4:
1126 case Builtin::BI__sync_and_and_fetch_8:
1127 case Builtin::BI__sync_and_and_fetch_16:
1128 BuiltinIndex = 7;
1129 break;
1130
1131 case Builtin::BI__sync_or_and_fetch:
1132 case Builtin::BI__sync_or_and_fetch_1:
1133 case Builtin::BI__sync_or_and_fetch_2:
1134 case Builtin::BI__sync_or_and_fetch_4:
1135 case Builtin::BI__sync_or_and_fetch_8:
1136 case Builtin::BI__sync_or_and_fetch_16:
1137 BuiltinIndex = 8;
1138 break;
1139
1140 case Builtin::BI__sync_xor_and_fetch:
1141 case Builtin::BI__sync_xor_and_fetch_1:
1142 case Builtin::BI__sync_xor_and_fetch_2:
1143 case Builtin::BI__sync_xor_and_fetch_4:
1144 case Builtin::BI__sync_xor_and_fetch_8:
1145 case Builtin::BI__sync_xor_and_fetch_16:
1146 BuiltinIndex = 9;
1147 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001148
Chris Lattner5caa3702009-05-08 06:58:22 +00001149 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001150 case Builtin::BI__sync_val_compare_and_swap_1:
1151 case Builtin::BI__sync_val_compare_and_swap_2:
1152 case Builtin::BI__sync_val_compare_and_swap_4:
1153 case Builtin::BI__sync_val_compare_and_swap_8:
1154 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001155 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +00001156 NumFixed = 2;
1157 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001158
Chris Lattner5caa3702009-05-08 06:58:22 +00001159 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001160 case Builtin::BI__sync_bool_compare_and_swap_1:
1161 case Builtin::BI__sync_bool_compare_and_swap_2:
1162 case Builtin::BI__sync_bool_compare_and_swap_4:
1163 case Builtin::BI__sync_bool_compare_and_swap_8:
1164 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001165 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +00001166 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001167 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001168 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001169
1170 case Builtin::BI__sync_lock_test_and_set:
1171 case Builtin::BI__sync_lock_test_and_set_1:
1172 case Builtin::BI__sync_lock_test_and_set_2:
1173 case Builtin::BI__sync_lock_test_and_set_4:
1174 case Builtin::BI__sync_lock_test_and_set_8:
1175 case Builtin::BI__sync_lock_test_and_set_16:
1176 BuiltinIndex = 12;
1177 break;
1178
Chris Lattner5caa3702009-05-08 06:58:22 +00001179 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +00001180 case Builtin::BI__sync_lock_release_1:
1181 case Builtin::BI__sync_lock_release_2:
1182 case Builtin::BI__sync_lock_release_4:
1183 case Builtin::BI__sync_lock_release_8:
1184 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001185 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +00001186 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001187 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001188 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001189
1190 case Builtin::BI__sync_swap:
1191 case Builtin::BI__sync_swap_1:
1192 case Builtin::BI__sync_swap_2:
1193 case Builtin::BI__sync_swap_4:
1194 case Builtin::BI__sync_swap_8:
1195 case Builtin::BI__sync_swap_16:
1196 BuiltinIndex = 14;
1197 break;
Chris Lattner5caa3702009-05-08 06:58:22 +00001198 }
Mike Stump1eb44332009-09-09 15:08:12 +00001199
Chris Lattner5caa3702009-05-08 06:58:22 +00001200 // Now that we know how many fixed arguments we expect, first check that we
1201 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +00001202 if (TheCall->getNumArgs() < 1+NumFixed) {
1203 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1204 << 0 << 1+NumFixed << TheCall->getNumArgs()
1205 << TheCall->getCallee()->getSourceRange();
1206 return ExprError();
1207 }
Mike Stump1eb44332009-09-09 15:08:12 +00001208
Chris Lattnere7ac0a92009-05-08 15:36:58 +00001209 // Get the decl for the concrete builtin from this, we can tell what the
1210 // concrete integer type we should convert to is.
1211 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1212 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara2ad11cd2012-09-22 09:05:22 +00001213 FunctionDecl *NewBuiltinDecl;
1214 if (NewBuiltinID == BuiltinID)
1215 NewBuiltinDecl = FDecl;
1216 else {
1217 // Perform builtin lookup to avoid redeclaring it.
1218 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1219 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1220 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1221 assert(Res.getFoundDecl());
1222 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
1223 if (NewBuiltinDecl == 0)
1224 return ExprError();
1225 }
Chandler Carruthd2014572010-07-09 18:59:35 +00001226
John McCallf871d0c2010-08-07 06:22:56 +00001227 // The first argument --- the pointer --- has a fixed type; we
1228 // deduce the types of the rest of the arguments accordingly. Walk
1229 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +00001230 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +00001231 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +00001232
Chris Lattner5caa3702009-05-08 06:58:22 +00001233 // GCC does an implicit conversion to the pointer or integer ValType. This
1234 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb45ae252011-10-05 07:41:44 +00001235 // Initialize the argument.
1236 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1237 ValType, /*consume*/ false);
1238 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley429bb272011-04-08 18:41:53 +00001239 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +00001240 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001241
Chris Lattner5caa3702009-05-08 06:58:22 +00001242 // Okay, we have something that *can* be converted to the right type. Check
1243 // to see if there is a potentially weird extension going on here. This can
1244 // happen when you do an atomic operation on something like an char* and
1245 // pass in 42. The 42 gets converted to char. This is even more strange
1246 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +00001247 // FIXME: Do this check.
John McCallb45ae252011-10-05 07:41:44 +00001248 TheCall->setArg(i+1, Arg.take());
Chris Lattner5caa3702009-05-08 06:58:22 +00001249 }
Mike Stump1eb44332009-09-09 15:08:12 +00001250
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001251 ASTContext& Context = this->getASTContext();
1252
1253 // Create a new DeclRefExpr to refer to the new decl.
1254 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1255 Context,
1256 DRE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001257 SourceLocation(),
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001258 NewBuiltinDecl,
John McCallf4b88a42012-03-10 09:33:50 +00001259 /*enclosing*/ false,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001260 DRE->getLocation(),
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001261 Context.BuiltinFnTy,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001262 DRE->getValueKind());
Mike Stump1eb44332009-09-09 15:08:12 +00001263
Chris Lattner5caa3702009-05-08 06:58:22 +00001264 // Set the callee in the CallExpr.
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001265 // FIXME: This loses syntactic information.
1266 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1267 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1268 CK_BuiltinFnToFnPtr);
John Wiegley429bb272011-04-08 18:41:53 +00001269 TheCall->setCallee(PromotedCall.take());
Mike Stump1eb44332009-09-09 15:08:12 +00001270
Chandler Carruthdb4325b2010-07-18 07:23:17 +00001271 // Change the result type of the call to match the original value type. This
1272 // is arbitrary, but the codegen for these builtins ins design to handle it
1273 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +00001274 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +00001275
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001276 return TheCallResult;
Chris Lattner5caa3702009-05-08 06:58:22 +00001277}
1278
Chris Lattner69039812009-02-18 06:01:06 +00001279/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +00001280/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +00001281/// Note: It might also make sense to do the UTF-16 conversion here (would
1282/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +00001283bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +00001284 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +00001285 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1286
Douglas Gregor5cee1192011-07-27 05:40:30 +00001287 if (!Literal || !Literal->isAscii()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001288 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1289 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001290 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +00001291 }
Mike Stump1eb44332009-09-09 15:08:12 +00001292
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001293 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001294 StringRef String = Literal->getString();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001295 unsigned NumBytes = String.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001296 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divacky31ba6132012-09-06 15:59:27 +00001297 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001298 UTF16 *ToPtr = &ToBuf[0];
1299
1300 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1301 &ToPtr, ToPtr + NumBytes,
1302 strictConversion);
1303 // Check for conversion failure.
1304 if (Result != conversionOK)
1305 Diag(Arg->getLocStart(),
1306 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1307 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001308 return false;
Chris Lattner59907c42007-08-10 20:18:51 +00001309}
1310
Chris Lattnerc27c6652007-12-20 00:05:45 +00001311/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1312/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +00001313bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1314 Expr *Fn = TheCall->getCallee();
1315 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +00001316 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001317 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001318 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1319 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +00001320 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001321 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +00001322 return true;
1323 }
Eli Friedman56f20ae2008-12-15 22:05:35 +00001324
1325 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +00001326 return Diag(TheCall->getLocEnd(),
1327 diag::err_typecheck_call_too_few_args_at_least)
1328 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +00001329 }
1330
John McCall5f8d6042011-08-27 01:09:30 +00001331 // Type-check the first argument normally.
1332 if (checkBuiltinArgument(*this, TheCall, 0))
1333 return true;
1334
Chris Lattnerc27c6652007-12-20 00:05:45 +00001335 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001336 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +00001337 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001338 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +00001339 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +00001340 else if (FunctionDecl *FD = getCurFunctionDecl())
1341 isVariadic = FD->isVariadic();
1342 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001343 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +00001344
Chris Lattnerc27c6652007-12-20 00:05:45 +00001345 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001346 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1347 return true;
1348 }
Mike Stump1eb44332009-09-09 15:08:12 +00001349
Chris Lattner30ce3442007-12-19 23:59:04 +00001350 // Verify that the second argument to the builtin is the last argument of the
1351 // current function or method.
1352 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +00001353 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001354
Anders Carlsson88cf2262008-02-11 04:20:54 +00001355 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1356 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001357 // FIXME: This isn't correct for methods (results in bogus warning).
1358 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +00001359 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001360 if (CurBlock)
1361 LastArg = *(CurBlock->TheDecl->param_end()-1);
1362 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +00001363 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001364 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001365 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001366 SecondArgIsLastNamedArgument = PV == LastArg;
1367 }
1368 }
Mike Stump1eb44332009-09-09 15:08:12 +00001369
Chris Lattner30ce3442007-12-19 23:59:04 +00001370 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001371 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +00001372 diag::warn_second_parameter_of_va_start_not_last_named_argument);
1373 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +00001374}
Chris Lattner30ce3442007-12-19 23:59:04 +00001375
Chris Lattner1b9a0792007-12-20 00:26:33 +00001376/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1377/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +00001378bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1379 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +00001380 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001381 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +00001382 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +00001383 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001384 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001385 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001386 << SourceRange(TheCall->getArg(2)->getLocStart(),
1387 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001388
John Wiegley429bb272011-04-08 18:41:53 +00001389 ExprResult OrigArg0 = TheCall->getArg(0);
1390 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +00001391
Chris Lattner1b9a0792007-12-20 00:26:33 +00001392 // Do standard promotions between the two arguments, returning their common
1393 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +00001394 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +00001395 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1396 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +00001397
1398 // Make sure any conversions are pushed back into the call; this is
1399 // type safe since unordered compare builtins are declared as "_Bool
1400 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +00001401 TheCall->setArg(0, OrigArg0.get());
1402 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001403
John Wiegley429bb272011-04-08 18:41:53 +00001404 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +00001405 return false;
1406
Chris Lattner1b9a0792007-12-20 00:26:33 +00001407 // If the common type isn't a real floating type, then the arguments were
1408 // invalid for this operation.
Eli Friedman860a3192012-06-16 02:19:17 +00001409 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +00001410 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001411 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +00001412 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1413 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001414
Chris Lattner1b9a0792007-12-20 00:26:33 +00001415 return false;
1416}
1417
Benjamin Kramere771a7a2010-02-15 22:42:31 +00001418/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1419/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001420/// to check everything. We expect the last argument to be a floating point
1421/// value.
1422bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1423 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +00001424 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001425 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001426 if (TheCall->getNumArgs() > NumArgs)
1427 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001428 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001429 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001430 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001431 (*(TheCall->arg_end()-1))->getLocEnd());
1432
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001433 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001434
Eli Friedman9ac6f622009-08-31 20:06:00 +00001435 if (OrigArg->isTypeDependent())
1436 return false;
1437
Chris Lattner81368fb2010-05-06 05:50:07 +00001438 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +00001439 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +00001440 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001441 diag::err_typecheck_call_invalid_unary_fp)
1442 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001443
Chris Lattner81368fb2010-05-06 05:50:07 +00001444 // If this is an implicit conversion from float -> double, remove it.
1445 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1446 Expr *CastArg = Cast->getSubExpr();
1447 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1448 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1449 "promotion from float to double is the only expected cast here");
1450 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +00001451 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner81368fb2010-05-06 05:50:07 +00001452 }
1453 }
1454
Eli Friedman9ac6f622009-08-31 20:06:00 +00001455 return false;
1456}
1457
Eli Friedmand38617c2008-05-14 19:38:39 +00001458/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1459// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +00001460ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001461 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001462 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +00001463 diag::err_typecheck_call_too_few_args_at_least)
Nate Begeman37b6a572010-06-08 00:16:34 +00001464 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherd77b9a22010-04-16 04:48:22 +00001465 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001466
Nate Begeman37b6a572010-06-08 00:16:34 +00001467 // Determine which of the following types of shufflevector we're checking:
1468 // 1) unary, vector mask: (lhs, mask)
1469 // 2) binary, vector mask: (lhs, rhs, mask)
1470 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1471 QualType resType = TheCall->getArg(0)->getType();
1472 unsigned numElements = 0;
1473
Douglas Gregorcde01732009-05-19 22:10:17 +00001474 if (!TheCall->getArg(0)->isTypeDependent() &&
1475 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001476 QualType LHSType = TheCall->getArg(0)->getType();
1477 QualType RHSType = TheCall->getArg(1)->getType();
1478
1479 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001480 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001481 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001482 TheCall->getArg(1)->getLocEnd());
1483 return ExprError();
1484 }
Nate Begeman37b6a572010-06-08 00:16:34 +00001485
1486 numElements = LHSType->getAs<VectorType>()->getNumElements();
1487 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +00001488
Nate Begeman37b6a572010-06-08 00:16:34 +00001489 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1490 // with mask. If so, verify that RHS is an integer vector type with the
1491 // same number of elts as lhs.
1492 if (TheCall->getNumArgs() == 2) {
Douglas Gregorf6094622010-07-23 15:58:24 +00001493 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +00001494 RHSType->getAs<VectorType>()->getNumElements() != numElements)
1495 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1496 << SourceRange(TheCall->getArg(1)->getLocStart(),
1497 TheCall->getArg(1)->getLocEnd());
1498 numResElements = numElements;
1499 }
1500 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001501 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001502 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001503 TheCall->getArg(1)->getLocEnd());
1504 return ExprError();
Nate Begeman37b6a572010-06-08 00:16:34 +00001505 } else if (numElements != numResElements) {
1506 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +00001507 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001508 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +00001509 }
Eli Friedmand38617c2008-05-14 19:38:39 +00001510 }
1511
1512 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001513 if (TheCall->getArg(i)->isTypeDependent() ||
1514 TheCall->getArg(i)->isValueDependent())
1515 continue;
1516
Nate Begeman37b6a572010-06-08 00:16:34 +00001517 llvm::APSInt Result(32);
1518 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1519 return ExprError(Diag(TheCall->getLocStart(),
1520 diag::err_shufflevector_nonconstant_argument)
1521 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001522
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001523 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001524 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001525 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001526 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001527 }
1528
Chris Lattner5f9e2722011-07-23 10:55:15 +00001529 SmallVector<Expr*, 32> exprs;
Eli Friedmand38617c2008-05-14 19:38:39 +00001530
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001531 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +00001532 exprs.push_back(TheCall->getArg(i));
1533 TheCall->setArg(i, 0);
1534 }
1535
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001536 return Owned(new (Context) ShuffleVectorExpr(Context, exprs, resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001537 TheCall->getCallee()->getLocStart(),
1538 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +00001539}
Chris Lattner30ce3442007-12-19 23:59:04 +00001540
Daniel Dunbar4493f792008-07-21 22:59:13 +00001541/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1542// This is declared to take (const void*, ...) and can take two
1543// optional constant int args.
1544bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001545 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001546
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001547 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +00001548 return Diag(TheCall->getLocEnd(),
1549 diag::err_typecheck_call_too_many_args_at_most)
1550 << 0 /*function call*/ << 3 << NumArgs
1551 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001552
1553 // Argument 0 is checked for us and the remaining arguments must be
1554 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001555 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +00001556 Expr *Arg = TheCall->getArg(i);
Douglas Gregor592a4232012-06-29 01:05:22 +00001557
1558 // We can't check the value of a dependent argument.
1559 if (Arg->isTypeDependent() || Arg->isValueDependent())
1560 continue;
1561
Eli Friedman9aef7262009-12-04 00:30:06 +00001562 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +00001563 if (SemaBuiltinConstantArg(TheCall, i, Result))
1564 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001565
Daniel Dunbar4493f792008-07-21 22:59:13 +00001566 // FIXME: gcc issues a warning and rewrites these to 0. These
1567 // seems especially odd for the third argument since the default
1568 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001569 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +00001570 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001571 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001572 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001573 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +00001574 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001575 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001576 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001577 }
1578 }
1579
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001580 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +00001581}
1582
Eric Christopher691ebc32010-04-17 02:26:23 +00001583/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1584/// TheCall is a constant expression.
1585bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1586 llvm::APSInt &Result) {
1587 Expr *Arg = TheCall->getArg(ArgNum);
1588 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1589 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1590
1591 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1592
1593 if (!Arg->isIntegerConstantExpr(Result, Context))
1594 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +00001595 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +00001596
Chris Lattner21fb98e2009-09-23 06:06:36 +00001597 return false;
1598}
1599
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001600/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1601/// int type). This simply type checks that type is one of the defined
1602/// constants (0-3).
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001603// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001604bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +00001605 llvm::APSInt Result;
Douglas Gregor592a4232012-06-29 01:05:22 +00001606
1607 // We can't check the value of a dependent argument.
1608 if (TheCall->getArg(1)->isTypeDependent() ||
1609 TheCall->getArg(1)->isValueDependent())
1610 return false;
1611
Eric Christopher691ebc32010-04-17 02:26:23 +00001612 // Check constant-ness first.
1613 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1614 return true;
1615
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001616 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001617 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001618 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1619 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001620 }
1621
1622 return false;
1623}
1624
Eli Friedman586d6a82009-05-03 06:04:26 +00001625/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +00001626/// This checks that val is a constant 1.
1627bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1628 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +00001629 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +00001630
Eric Christopher691ebc32010-04-17 02:26:23 +00001631 // TODO: This is less than ideal. Overload this to take a value.
1632 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1633 return true;
1634
1635 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +00001636 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1637 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1638
1639 return false;
1640}
1641
Richard Smith831421f2012-06-25 20:30:08 +00001642// Determine if an expression is a string literal or constant string.
1643// If this function returns false on the arguments to a function expecting a
1644// format string, we will usually need to emit a warning.
1645// True string literals are then checked by CheckFormatString.
1646Sema::StringLiteralCheckType
1647Sema::checkFormatStringExpr(const Expr *E, Expr **Args,
1648 unsigned NumArgs, bool HasVAListArg,
1649 unsigned format_idx, unsigned firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001650 FormatStringType Type, VariadicCallType CallType,
1651 bool inFunctionCall) {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001652 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +00001653 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith831421f2012-06-25 20:30:08 +00001654 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001655
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001656 E = E->IgnoreParenCasts();
Peter Collingbournef111d932011-04-15 00:35:48 +00001657
David Blaikiea73cdcb2012-02-10 21:07:25 +00001658 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
1659 // Technically -Wformat-nonliteral does not warn about this case.
1660 // The behavior of printf and friends in this case is implementation
1661 // dependent. Ideally if the format string cannot be null then
1662 // it should have a 'nonnull' attribute in the function prototype.
Richard Smith831421f2012-06-25 20:30:08 +00001663 return SLCT_CheckedLiteral;
David Blaikiea73cdcb2012-02-10 21:07:25 +00001664
Ted Kremenekd30ef872009-01-12 23:09:09 +00001665 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +00001666 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +00001667 case Stmt::ConditionalOperatorClass: {
Richard Smith831421f2012-06-25 20:30:08 +00001668 // The expression is a literal if both sub-expressions were, and it was
1669 // completely checked only if both sub-expressions were checked.
1670 const AbstractConditionalOperator *C =
1671 cast<AbstractConditionalOperator>(E);
1672 StringLiteralCheckType Left =
1673 checkFormatStringExpr(C->getTrueExpr(), Args, NumArgs,
1674 HasVAListArg, format_idx, firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001675 Type, CallType, inFunctionCall);
Richard Smith831421f2012-06-25 20:30:08 +00001676 if (Left == SLCT_NotALiteral)
1677 return SLCT_NotALiteral;
1678 StringLiteralCheckType Right =
1679 checkFormatStringExpr(C->getFalseExpr(), Args, NumArgs,
1680 HasVAListArg, format_idx, firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001681 Type, CallType, inFunctionCall);
Richard Smith831421f2012-06-25 20:30:08 +00001682 return Left < Right ? Left : Right;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001683 }
1684
1685 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001686 E = cast<ImplicitCastExpr>(E)->getSubExpr();
1687 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001688 }
1689
John McCall56ca35d2011-02-17 10:25:35 +00001690 case Stmt::OpaqueValueExprClass:
1691 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
1692 E = src;
1693 goto tryAgain;
1694 }
Richard Smith831421f2012-06-25 20:30:08 +00001695 return SLCT_NotALiteral;
John McCall56ca35d2011-02-17 10:25:35 +00001696
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001697 case Stmt::PredefinedExprClass:
1698 // While __func__, etc., are technically not string literals, they
1699 // cannot contain format specifiers and thus are not a security
1700 // liability.
Richard Smith831421f2012-06-25 20:30:08 +00001701 return SLCT_UncheckedLiteral;
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001702
Ted Kremenek082d9362009-03-20 21:35:28 +00001703 case Stmt::DeclRefExprClass: {
1704 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001705
Ted Kremenek082d9362009-03-20 21:35:28 +00001706 // As an exception, do not flag errors for variables binding to
1707 // const string literals.
1708 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1709 bool isConstant = false;
1710 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001711
Ted Kremenek082d9362009-03-20 21:35:28 +00001712 if (const ArrayType *AT = Context.getAsArrayType(T)) {
1713 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001714 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001715 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +00001716 PT->getPointeeType().isConstant(Context);
Jean-Daniel Dupase98e5b52012-01-25 10:35:33 +00001717 } else if (T->isObjCObjectPointerType()) {
1718 // In ObjC, there is usually no "const ObjectPointer" type,
1719 // so don't check if the pointee type is constant.
1720 isConstant = T.isConstant(Context);
Ted Kremenek082d9362009-03-20 21:35:28 +00001721 }
Mike Stump1eb44332009-09-09 15:08:12 +00001722
Ted Kremenek082d9362009-03-20 21:35:28 +00001723 if (isConstant) {
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00001724 if (const Expr *Init = VD->getAnyInitializer()) {
1725 // Look through initializers like const char c[] = { "foo" }
1726 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
1727 if (InitList->isStringLiteralInit())
1728 Init = InitList->getInit(0)->IgnoreParenImpCasts();
1729 }
Richard Smith831421f2012-06-25 20:30:08 +00001730 return checkFormatStringExpr(Init, Args, NumArgs,
1731 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001732 firstDataArg, Type, CallType,
Richard Smith831421f2012-06-25 20:30:08 +00001733 /*inFunctionCall*/false);
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00001734 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001735 }
Mike Stump1eb44332009-09-09 15:08:12 +00001736
Anders Carlssond966a552009-06-28 19:55:58 +00001737 // For vprintf* functions (i.e., HasVAListArg==true), we add a
1738 // special check to see if the format string is a function parameter
1739 // of the function calling the printf function. If the function
1740 // has an attribute indicating it is a printf-like function, then we
1741 // should suppress warnings concerning non-literals being used in a call
1742 // to a vprintf function. For example:
1743 //
1744 // void
1745 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1746 // va_list ap;
1747 // va_start(ap, fmt);
1748 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
1749 // ...
1750 //
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00001751 if (HasVAListArg) {
1752 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
1753 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
1754 int PVIndex = PV->getFunctionScopeIndex() + 1;
1755 for (specific_attr_iterator<FormatAttr>
1756 i = ND->specific_attr_begin<FormatAttr>(),
1757 e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) {
1758 FormatAttr *PVFormat = *i;
1759 // adjust for implicit parameter
1760 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1761 if (MD->isInstance())
1762 ++PVIndex;
1763 // We also check if the formats are compatible.
1764 // We can't pass a 'scanf' string to a 'printf' function.
1765 if (PVIndex == PVFormat->getFormatIdx() &&
1766 Type == GetFormatStringType(PVFormat))
Richard Smith831421f2012-06-25 20:30:08 +00001767 return SLCT_UncheckedLiteral;
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00001768 }
1769 }
1770 }
1771 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001772 }
Mike Stump1eb44332009-09-09 15:08:12 +00001773
Richard Smith831421f2012-06-25 20:30:08 +00001774 return SLCT_NotALiteral;
Ted Kremenek082d9362009-03-20 21:35:28 +00001775 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00001776
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001777 case Stmt::CallExprClass:
1778 case Stmt::CXXMemberCallExprClass: {
Anders Carlsson8f031b32009-06-27 04:05:33 +00001779 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001780 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
1781 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
1782 unsigned ArgIndex = FA->getFormatIdx();
1783 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1784 if (MD->isInstance())
1785 --ArgIndex;
1786 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001787
Richard Smith831421f2012-06-25 20:30:08 +00001788 return checkFormatStringExpr(Arg, Args, NumArgs,
1789 HasVAListArg, format_idx, firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001790 Type, CallType, inFunctionCall);
Jordan Rose50687312012-06-04 23:52:23 +00001791 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
1792 unsigned BuiltinID = FD->getBuiltinID();
1793 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
1794 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
1795 const Expr *Arg = CE->getArg(0);
Richard Smith831421f2012-06-25 20:30:08 +00001796 return checkFormatStringExpr(Arg, Args, NumArgs,
1797 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001798 firstDataArg, Type, CallType,
1799 inFunctionCall);
Jordan Rose50687312012-06-04 23:52:23 +00001800 }
Anders Carlsson8f031b32009-06-27 04:05:33 +00001801 }
1802 }
Mike Stump1eb44332009-09-09 15:08:12 +00001803
Richard Smith831421f2012-06-25 20:30:08 +00001804 return SLCT_NotALiteral;
Anders Carlsson8f031b32009-06-27 04:05:33 +00001805 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001806 case Stmt::ObjCStringLiteralClass:
1807 case Stmt::StringLiteralClass: {
1808 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001809
Ted Kremenek082d9362009-03-20 21:35:28 +00001810 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00001811 StrE = ObjCFExpr->getString();
1812 else
Ted Kremenek082d9362009-03-20 21:35:28 +00001813 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001814
Ted Kremenekd30ef872009-01-12 23:09:09 +00001815 if (StrE) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001816 CheckFormatString(StrE, E, Args, NumArgs, HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001817 firstDataArg, Type, inFunctionCall, CallType);
Richard Smith831421f2012-06-25 20:30:08 +00001818 return SLCT_CheckedLiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001819 }
Mike Stump1eb44332009-09-09 15:08:12 +00001820
Richard Smith831421f2012-06-25 20:30:08 +00001821 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001822 }
Mike Stump1eb44332009-09-09 15:08:12 +00001823
Ted Kremenek082d9362009-03-20 21:35:28 +00001824 default:
Richard Smith831421f2012-06-25 20:30:08 +00001825 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001826 }
1827}
1828
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001829void
Mike Stump1eb44332009-09-09 15:08:12 +00001830Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewycky909a70d2011-03-25 01:44:32 +00001831 const Expr * const *ExprArgs,
1832 SourceLocation CallSiteLoc) {
Sean Huntcf807c42010-08-18 23:23:40 +00001833 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1834 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001835 i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +00001836 const Expr *ArgExpr = ExprArgs[*i];
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001837 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00001838 Expr::NPC_ValueDependentIsNotNull))
Nick Lewycky909a70d2011-03-25 01:44:32 +00001839 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001840 }
1841}
Ted Kremenekd30ef872009-01-12 23:09:09 +00001842
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001843Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
1844 return llvm::StringSwitch<FormatStringType>(Format->getType())
1845 .Case("scanf", FST_Scanf)
1846 .Cases("printf", "printf0", FST_Printf)
1847 .Cases("NSString", "CFString", FST_NSString)
1848 .Case("strftime", FST_Strftime)
1849 .Case("strfmon", FST_Strfmon)
1850 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
1851 .Default(FST_Unknown);
1852}
1853
Jordan Roseddcfbc92012-07-19 18:10:23 +00001854/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek826a3452010-07-16 02:11:22 +00001855/// functions) for correct use of format strings.
Richard Smith831421f2012-06-25 20:30:08 +00001856/// Returns true if a format string has been fully checked.
Richard Smith831421f2012-06-25 20:30:08 +00001857bool Sema::CheckFormatArguments(const FormatAttr *Format, Expr **Args,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001858 unsigned NumArgs, bool IsCXXMember,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001859 VariadicCallType CallType,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001860 SourceLocation Loc, SourceRange Range) {
Richard Smith831421f2012-06-25 20:30:08 +00001861 FormatStringInfo FSI;
1862 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
1863 return CheckFormatArguments(Args, NumArgs, FSI.HasVAListArg, FSI.FormatIdx,
1864 FSI.FirstDataArg, GetFormatStringType(Format),
Jordan Roseddcfbc92012-07-19 18:10:23 +00001865 CallType, Loc, Range);
Richard Smith831421f2012-06-25 20:30:08 +00001866 return false;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001867}
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001868
Richard Smith831421f2012-06-25 20:30:08 +00001869bool Sema::CheckFormatArguments(Expr **Args, unsigned NumArgs,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001870 bool HasVAListArg, unsigned format_idx,
1871 unsigned firstDataArg, FormatStringType Type,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001872 VariadicCallType CallType,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001873 SourceLocation Loc, SourceRange Range) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001874 // CHECK: printf/scanf-like function is called with no format string.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001875 if (format_idx >= NumArgs) {
1876 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith831421f2012-06-25 20:30:08 +00001877 return false;
Ted Kremenek71895b92007-08-14 17:39:48 +00001878 }
Mike Stump1eb44332009-09-09 15:08:12 +00001879
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001880 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001881
Chris Lattner59907c42007-08-10 20:18:51 +00001882 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001883 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001884 // Dynamically generated format strings are difficult to
1885 // automatically vet at compile time. Requiring that format strings
1886 // are string literals: (1) permits the checking of format strings by
1887 // the compiler and thereby (2) can practically remove the source of
1888 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001889
Mike Stump1eb44332009-09-09 15:08:12 +00001890 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001891 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001892 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001893 // the same format string checking logic for both ObjC and C strings.
Richard Smith831421f2012-06-25 20:30:08 +00001894 StringLiteralCheckType CT =
1895 checkFormatStringExpr(OrigFormatExpr, Args, NumArgs, HasVAListArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001896 format_idx, firstDataArg, Type, CallType);
Richard Smith831421f2012-06-25 20:30:08 +00001897 if (CT != SLCT_NotALiteral)
1898 // Literal format string found, check done!
1899 return CT == SLCT_CheckedLiteral;
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001900
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00001901 // Strftime is particular as it always uses a single 'time' argument,
1902 // so it is safe to pass a non-literal string.
1903 if (Type == FST_Strftime)
Richard Smith831421f2012-06-25 20:30:08 +00001904 return false;
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00001905
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00001906 // Do not emit diag when the string param is a macro expansion and the
1907 // format is either NSString or CFString. This is a hack to prevent
1908 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
1909 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupasdc170202012-05-04 21:08:08 +00001910 if (Type == FST_NSString &&
1911 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith831421f2012-06-25 20:30:08 +00001912 return false;
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00001913
Chris Lattner655f1412009-04-29 04:59:47 +00001914 // If there are no arguments specified, warn with -Wformat-security, otherwise
1915 // warn only with -Wformat-nonliteral.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001916 if (NumArgs == format_idx+1)
1917 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001918 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00001919 << OrigFormatExpr->getSourceRange();
1920 else
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001921 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001922 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00001923 << OrigFormatExpr->getSourceRange();
Richard Smith831421f2012-06-25 20:30:08 +00001924 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001925}
Ted Kremenek71895b92007-08-14 17:39:48 +00001926
Ted Kremeneke0e53132010-01-28 23:39:18 +00001927namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00001928class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1929protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001930 Sema &S;
1931 const StringLiteral *FExpr;
1932 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001933 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001934 const unsigned NumDataArgs;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001935 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001936 const bool HasVAListArg;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001937 const Expr * const *Args;
1938 const unsigned NumArgs;
Ted Kremenek0d277352010-01-29 01:06:55 +00001939 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001940 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00001941 bool usesPositionalArgs;
1942 bool atFirstArg;
Richard Trieu55733de2011-10-28 00:41:25 +00001943 bool inFunctionCall;
Jordan Roseddcfbc92012-07-19 18:10:23 +00001944 Sema::VariadicCallType CallType;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001945public:
Ted Kremenek826a3452010-07-16 02:11:22 +00001946 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00001947 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00001948 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001949 Expr **args, unsigned numArgs,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001950 unsigned formatIdx, bool inFunctionCall,
1951 Sema::VariadicCallType callType)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001952 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose50687312012-06-04 23:52:23 +00001953 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
1954 Beg(beg), HasVAListArg(hasVAListArg),
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001955 Args(args), NumArgs(numArgs), FormatIdx(formatIdx),
Richard Trieu55733de2011-10-28 00:41:25 +00001956 usesPositionalArgs(false), atFirstArg(true),
Jordan Roseddcfbc92012-07-19 18:10:23 +00001957 inFunctionCall(inFunctionCall), CallType(callType) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001958 CoveredArgs.resize(numDataArgs);
1959 CoveredArgs.reset();
1960 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001961
Ted Kremenek07d161f2010-01-29 01:50:07 +00001962 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001963
Ted Kremenek826a3452010-07-16 02:11:22 +00001964 void HandleIncompleteSpecifier(const char *startSpecifier,
1965 unsigned specifierLen);
Hans Wennborg76517422012-02-22 10:17:01 +00001966
Jordan Rosebbb6bb42012-09-08 04:00:03 +00001967 void HandleInvalidLengthModifier(
1968 const analyze_format_string::FormatSpecifier &FS,
1969 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose8be066e2012-09-08 04:00:12 +00001970 const char *startSpecifier, unsigned specifierLen, unsigned DiagID);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00001971
Hans Wennborg76517422012-02-22 10:17:01 +00001972 void HandleNonStandardLengthModifier(
Jordan Rose8be066e2012-09-08 04:00:12 +00001973 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborg76517422012-02-22 10:17:01 +00001974 const char *startSpecifier, unsigned specifierLen);
1975
1976 void HandleNonStandardConversionSpecifier(
1977 const analyze_format_string::ConversionSpecifier &CS,
1978 const char *startSpecifier, unsigned specifierLen);
1979
Hans Wennborgf8562642012-03-09 10:10:54 +00001980 virtual void HandlePosition(const char *startPos, unsigned posLen);
1981
Ted Kremenekefaff192010-02-27 01:41:03 +00001982 virtual void HandleInvalidPosition(const char *startSpecifier,
1983 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00001984 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00001985
1986 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1987
Ted Kremeneke0e53132010-01-28 23:39:18 +00001988 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001989
Richard Trieu55733de2011-10-28 00:41:25 +00001990 template <typename Range>
1991 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
1992 const Expr *ArgumentExpr,
1993 PartialDiagnostic PDiag,
1994 SourceLocation StringLoc,
1995 bool IsStringLocation, Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00001996 ArrayRef<FixItHint> Fixit = ArrayRef<FixItHint>());
Richard Trieu55733de2011-10-28 00:41:25 +00001997
Ted Kremenek826a3452010-07-16 02:11:22 +00001998protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001999 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2000 const char *startSpec,
2001 unsigned specifierLen,
2002 const char *csStart, unsigned csLen);
Richard Trieu55733de2011-10-28 00:41:25 +00002003
2004 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2005 const char *startSpec,
2006 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002007
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002008 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00002009 CharSourceRange getSpecifierRange(const char *startSpecifier,
2010 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002011 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002012
Ted Kremenek0d277352010-01-29 01:06:55 +00002013 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00002014
2015 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2016 const analyze_format_string::ConversionSpecifier &CS,
2017 const char *startSpecifier, unsigned specifierLen,
2018 unsigned argIndex);
Richard Trieu55733de2011-10-28 00:41:25 +00002019
2020 template <typename Range>
2021 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2022 bool IsStringLocation, Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002023 ArrayRef<FixItHint> Fixit = ArrayRef<FixItHint>());
Richard Trieu55733de2011-10-28 00:41:25 +00002024
2025 void CheckPositionalAndNonpositionalArgs(
2026 const analyze_format_string::FormatSpecifier *FS);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002027};
2028}
2029
Ted Kremenek826a3452010-07-16 02:11:22 +00002030SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00002031 return OrigFormatExpr->getSourceRange();
2032}
2033
Ted Kremenek826a3452010-07-16 02:11:22 +00002034CharSourceRange CheckFormatHandler::
2035getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002036 SourceLocation Start = getLocationOfByte(startSpecifier);
2037 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2038
2039 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002040 End = End.getLocWithOffset(1);
Tom Care45f9b7e2010-06-21 21:21:01 +00002041
2042 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002043}
2044
Ted Kremenek826a3452010-07-16 02:11:22 +00002045SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002046 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002047}
2048
Ted Kremenek826a3452010-07-16 02:11:22 +00002049void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2050 unsigned specifierLen){
Richard Trieu55733de2011-10-28 00:41:25 +00002051 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2052 getLocationOfByte(startSpecifier),
2053 /*IsStringLocation*/true,
2054 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek808015a2010-01-29 03:16:21 +00002055}
2056
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002057void CheckFormatHandler::HandleInvalidLengthModifier(
2058 const analyze_format_string::FormatSpecifier &FS,
2059 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose8be066e2012-09-08 04:00:12 +00002060 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002061 using namespace analyze_format_string;
2062
2063 const LengthModifier &LM = FS.getLengthModifier();
2064 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2065
2066 // See if we know how to fix this length modifier.
2067 llvm::Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
2068 if (FixedLM) {
Jordan Rose8be066e2012-09-08 04:00:12 +00002069 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002070 getLocationOfByte(LM.getStart()),
2071 /*IsStringLocation*/true,
2072 getSpecifierRange(startSpecifier, specifierLen));
2073
2074 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2075 << FixedLM->toString()
2076 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2077
2078 } else {
Jordan Rose8be066e2012-09-08 04:00:12 +00002079 FixItHint Hint;
2080 if (DiagID == diag::warn_format_nonsensical_length)
2081 Hint = FixItHint::CreateRemoval(LMRange);
2082
2083 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002084 getLocationOfByte(LM.getStart()),
2085 /*IsStringLocation*/true,
2086 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose8be066e2012-09-08 04:00:12 +00002087 Hint);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002088 }
2089}
2090
Hans Wennborg76517422012-02-22 10:17:01 +00002091void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose8be066e2012-09-08 04:00:12 +00002092 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborg76517422012-02-22 10:17:01 +00002093 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose8be066e2012-09-08 04:00:12 +00002094 using namespace analyze_format_string;
2095
2096 const LengthModifier &LM = FS.getLengthModifier();
2097 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2098
2099 // See if we know how to fix this length modifier.
2100 llvm::Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
2101 if (FixedLM) {
2102 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2103 << LM.toString() << 0,
2104 getLocationOfByte(LM.getStart()),
2105 /*IsStringLocation*/true,
2106 getSpecifierRange(startSpecifier, specifierLen));
2107
2108 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2109 << FixedLM->toString()
2110 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2111
2112 } else {
2113 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2114 << LM.toString() << 0,
2115 getLocationOfByte(LM.getStart()),
2116 /*IsStringLocation*/true,
2117 getSpecifierRange(startSpecifier, specifierLen));
2118 }
Hans Wennborg76517422012-02-22 10:17:01 +00002119}
2120
2121void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2122 const analyze_format_string::ConversionSpecifier &CS,
2123 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose670941c2012-09-13 02:11:15 +00002124 using namespace analyze_format_string;
2125
2126 // See if we know how to fix this conversion specifier.
2127 llvm::Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
2128 if (FixedCS) {
2129 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2130 << CS.toString() << /*conversion specifier*/1,
2131 getLocationOfByte(CS.getStart()),
2132 /*IsStringLocation*/true,
2133 getSpecifierRange(startSpecifier, specifierLen));
2134
2135 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2136 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2137 << FixedCS->toString()
2138 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2139 } else {
2140 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2141 << CS.toString() << /*conversion specifier*/1,
2142 getLocationOfByte(CS.getStart()),
2143 /*IsStringLocation*/true,
2144 getSpecifierRange(startSpecifier, specifierLen));
2145 }
Hans Wennborg76517422012-02-22 10:17:01 +00002146}
2147
Hans Wennborgf8562642012-03-09 10:10:54 +00002148void CheckFormatHandler::HandlePosition(const char *startPos,
2149 unsigned posLen) {
2150 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2151 getLocationOfByte(startPos),
2152 /*IsStringLocation*/true,
2153 getSpecifierRange(startPos, posLen));
2154}
2155
Ted Kremenekefaff192010-02-27 01:41:03 +00002156void
Ted Kremenek826a3452010-07-16 02:11:22 +00002157CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2158 analyze_format_string::PositionContext p) {
Richard Trieu55733de2011-10-28 00:41:25 +00002159 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2160 << (unsigned) p,
2161 getLocationOfByte(startPos), /*IsStringLocation*/true,
2162 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002163}
2164
Ted Kremenek826a3452010-07-16 02:11:22 +00002165void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00002166 unsigned posLen) {
Richard Trieu55733de2011-10-28 00:41:25 +00002167 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2168 getLocationOfByte(startPos),
2169 /*IsStringLocation*/true,
2170 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002171}
2172
Ted Kremenek826a3452010-07-16 02:11:22 +00002173void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose50687312012-06-04 23:52:23 +00002174 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0c069442011-03-15 21:18:48 +00002175 // The presence of a null character is likely an error.
Richard Trieu55733de2011-10-28 00:41:25 +00002176 EmitFormatDiagnostic(
2177 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2178 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2179 getFormatStringRange());
Ted Kremenek0c069442011-03-15 21:18:48 +00002180 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002181}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002182
Jordan Rose48716662012-07-19 18:10:08 +00002183// Note that this may return NULL if there was an error parsing or building
2184// one of the argument expressions.
Ted Kremenek826a3452010-07-16 02:11:22 +00002185const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002186 return Args[FirstDataArg + i];
Ted Kremenek826a3452010-07-16 02:11:22 +00002187}
2188
2189void CheckFormatHandler::DoneProcessing() {
2190 // Does the number of data arguments exceed the number of
2191 // format conversions in the format string?
2192 if (!HasVAListArg) {
2193 // Find any arguments that weren't covered.
2194 CoveredArgs.flip();
2195 signed notCoveredArg = CoveredArgs.find_first();
2196 if (notCoveredArg >= 0) {
2197 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose48716662012-07-19 18:10:08 +00002198 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2199 SourceLocation Loc = E->getLocStart();
2200 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2201 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2202 Loc, /*IsStringLocation*/false,
2203 getFormatStringRange());
2204 }
Bob Wilsonc03f2df2012-05-03 19:47:19 +00002205 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002206 }
2207 }
2208}
2209
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002210bool
2211CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2212 SourceLocation Loc,
2213 const char *startSpec,
2214 unsigned specifierLen,
2215 const char *csStart,
2216 unsigned csLen) {
2217
2218 bool keepGoing = true;
2219 if (argIndex < NumDataArgs) {
2220 // Consider the argument coverered, even though the specifier doesn't
2221 // make sense.
2222 CoveredArgs.set(argIndex);
2223 }
2224 else {
2225 // If argIndex exceeds the number of data arguments we
2226 // don't issue a warning because that is just a cascade of warnings (and
2227 // they may have intended '%%' anyway). We don't want to continue processing
2228 // the format string after this point, however, as we will like just get
2229 // gibberish when trying to match arguments.
2230 keepGoing = false;
2231 }
2232
Richard Trieu55733de2011-10-28 00:41:25 +00002233 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2234 << StringRef(csStart, csLen),
2235 Loc, /*IsStringLocation*/true,
2236 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002237
2238 return keepGoing;
2239}
2240
Richard Trieu55733de2011-10-28 00:41:25 +00002241void
2242CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2243 const char *startSpec,
2244 unsigned specifierLen) {
2245 EmitFormatDiagnostic(
2246 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2247 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2248}
2249
Ted Kremenek666a1972010-07-26 19:45:42 +00002250bool
2251CheckFormatHandler::CheckNumArgs(
2252 const analyze_format_string::FormatSpecifier &FS,
2253 const analyze_format_string::ConversionSpecifier &CS,
2254 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2255
2256 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002257 PartialDiagnostic PDiag = FS.usesPositionalArg()
2258 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2259 << (argIndex+1) << NumDataArgs)
2260 : S.PDiag(diag::warn_printf_insufficient_data_args);
2261 EmitFormatDiagnostic(
2262 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2263 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek666a1972010-07-26 19:45:42 +00002264 return false;
2265 }
2266 return true;
2267}
2268
Richard Trieu55733de2011-10-28 00:41:25 +00002269template<typename Range>
2270void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2271 SourceLocation Loc,
2272 bool IsStringLocation,
2273 Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002274 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002275 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu55733de2011-10-28 00:41:25 +00002276 Loc, IsStringLocation, StringRange, FixIt);
2277}
2278
2279/// \brief If the format string is not within the funcion call, emit a note
2280/// so that the function call and string are in diagnostic messages.
2281///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00002282/// \param InFunctionCall if true, the format string is within the function
Richard Trieu55733de2011-10-28 00:41:25 +00002283/// call and only one diagnostic message will be produced. Otherwise, an
2284/// extra note will be emitted pointing to location of the format string.
2285///
2286/// \param ArgumentExpr the expression that is passed as the format string
2287/// argument in the function call. Used for getting locations when two
2288/// diagnostics are emitted.
2289///
2290/// \param PDiag the callee should already have provided any strings for the
2291/// diagnostic message. This function only adds locations and fixits
2292/// to diagnostics.
2293///
2294/// \param Loc primary location for diagnostic. If two diagnostics are
2295/// required, one will be at Loc and a new SourceLocation will be created for
2296/// the other one.
2297///
2298/// \param IsStringLocation if true, Loc points to the format string should be
2299/// used for the note. Otherwise, Loc points to the argument list and will
2300/// be used with PDiag.
2301///
2302/// \param StringRange some or all of the string to highlight. This is
2303/// templated so it can accept either a CharSourceRange or a SourceRange.
2304///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00002305/// \param FixIt optional fix it hint for the format string.
Richard Trieu55733de2011-10-28 00:41:25 +00002306template<typename Range>
2307void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2308 const Expr *ArgumentExpr,
2309 PartialDiagnostic PDiag,
2310 SourceLocation Loc,
2311 bool IsStringLocation,
2312 Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002313 ArrayRef<FixItHint> FixIt) {
2314 if (InFunctionCall) {
2315 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2316 D << StringRange;
2317 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2318 I != E; ++I) {
2319 D << *I;
2320 }
2321 } else {
Richard Trieu55733de2011-10-28 00:41:25 +00002322 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2323 << ArgumentExpr->getSourceRange();
Jordan Roseec087352012-09-05 22:56:26 +00002324
2325 const Sema::SemaDiagnosticBuilder &Note =
2326 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2327 diag::note_format_string_defined);
2328
2329 Note << StringRange;
2330 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2331 I != E; ++I) {
2332 Note << *I;
2333 }
Richard Trieu55733de2011-10-28 00:41:25 +00002334 }
2335}
2336
Ted Kremenek826a3452010-07-16 02:11:22 +00002337//===--- CHECK: Printf format string checking ------------------------------===//
2338
2339namespace {
2340class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose50687312012-06-04 23:52:23 +00002341 bool ObjCContext;
Ted Kremenek826a3452010-07-16 02:11:22 +00002342public:
2343 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2344 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002345 unsigned numDataArgs, bool isObjC,
Ted Kremenek826a3452010-07-16 02:11:22 +00002346 const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002347 Expr **Args, unsigned NumArgs,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002348 unsigned formatIdx, bool inFunctionCall,
2349 Sema::VariadicCallType CallType)
Ted Kremenek826a3452010-07-16 02:11:22 +00002350 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002351 numDataArgs, beg, hasVAListArg, Args, NumArgs,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002352 formatIdx, inFunctionCall, CallType), ObjCContext(isObjC)
2353 {}
2354
Ted Kremenek826a3452010-07-16 02:11:22 +00002355
2356 bool HandleInvalidPrintfConversionSpecifier(
2357 const analyze_printf::PrintfSpecifier &FS,
2358 const char *startSpecifier,
2359 unsigned specifierLen);
2360
2361 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2362 const char *startSpecifier,
2363 unsigned specifierLen);
Richard Smith831421f2012-06-25 20:30:08 +00002364 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2365 const char *StartSpecifier,
2366 unsigned SpecifierLen,
2367 const Expr *E);
2368
Ted Kremenek826a3452010-07-16 02:11:22 +00002369 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2370 const char *startSpecifier, unsigned specifierLen);
2371 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2372 const analyze_printf::OptionalAmount &Amt,
2373 unsigned type,
2374 const char *startSpecifier, unsigned specifierLen);
2375 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2376 const analyze_printf::OptionalFlag &flag,
2377 const char *startSpecifier, unsigned specifierLen);
2378 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2379 const analyze_printf::OptionalFlag &ignoredFlag,
2380 const analyze_printf::OptionalFlag &flag,
2381 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgf3749f42012-08-07 08:11:26 +00002382 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith831421f2012-06-25 20:30:08 +00002383 const Expr *E, const CharSourceRange &CSR);
2384
Ted Kremenek826a3452010-07-16 02:11:22 +00002385};
2386}
2387
2388bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2389 const analyze_printf::PrintfSpecifier &FS,
2390 const char *startSpecifier,
2391 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002392 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002393 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002394
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002395 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2396 getLocationOfByte(CS.getStart()),
2397 startSpecifier, specifierLen,
2398 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00002399}
2400
Ted Kremenek826a3452010-07-16 02:11:22 +00002401bool CheckPrintfHandler::HandleAmount(
2402 const analyze_format_string::OptionalAmount &Amt,
2403 unsigned k, const char *startSpecifier,
2404 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002405
2406 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002407 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002408 unsigned argIndex = Amt.getArgIndex();
2409 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002410 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2411 << k,
2412 getLocationOfByte(Amt.getStart()),
2413 /*IsStringLocation*/true,
2414 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002415 // Don't do any more checking. We will just emit
2416 // spurious errors.
2417 return false;
2418 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002419
Ted Kremenek0d277352010-01-29 01:06:55 +00002420 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00002421 // Although not in conformance with C99, we also allow the argument to be
2422 // an 'unsigned int' as that is a reasonably safe case. GCC also
2423 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002424 CoveredArgs.set(argIndex);
2425 const Expr *Arg = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00002426 if (!Arg)
2427 return false;
2428
Ted Kremenek0d277352010-01-29 01:06:55 +00002429 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002430
Hans Wennborgf3749f42012-08-07 08:11:26 +00002431 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
2432 assert(AT.isValid());
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002433
Hans Wennborgf3749f42012-08-07 08:11:26 +00002434 if (!AT.matchesType(S.Context, T)) {
Richard Trieu55733de2011-10-28 00:41:25 +00002435 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgf3749f42012-08-07 08:11:26 +00002436 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu55733de2011-10-28 00:41:25 +00002437 << T << Arg->getSourceRange(),
2438 getLocationOfByte(Amt.getStart()),
2439 /*IsStringLocation*/true,
2440 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002441 // Don't do any more checking. We will just emit
2442 // spurious errors.
2443 return false;
2444 }
2445 }
2446 }
2447 return true;
2448}
Ted Kremenek0d277352010-01-29 01:06:55 +00002449
Tom Caree4ee9662010-06-17 19:00:27 +00002450void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00002451 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002452 const analyze_printf::OptionalAmount &Amt,
2453 unsigned type,
2454 const char *startSpecifier,
2455 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002456 const analyze_printf::PrintfConversionSpecifier &CS =
2457 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00002458
Richard Trieu55733de2011-10-28 00:41:25 +00002459 FixItHint fixit =
2460 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2461 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2462 Amt.getConstantLength()))
2463 : FixItHint();
2464
2465 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2466 << type << CS.toString(),
2467 getLocationOfByte(Amt.getStart()),
2468 /*IsStringLocation*/true,
2469 getSpecifierRange(startSpecifier, specifierLen),
2470 fixit);
Tom Caree4ee9662010-06-17 19:00:27 +00002471}
2472
Ted Kremenek826a3452010-07-16 02:11:22 +00002473void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002474 const analyze_printf::OptionalFlag &flag,
2475 const char *startSpecifier,
2476 unsigned specifierLen) {
2477 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002478 const analyze_printf::PrintfConversionSpecifier &CS =
2479 FS.getConversionSpecifier();
Richard Trieu55733de2011-10-28 00:41:25 +00002480 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2481 << flag.toString() << CS.toString(),
2482 getLocationOfByte(flag.getPosition()),
2483 /*IsStringLocation*/true,
2484 getSpecifierRange(startSpecifier, specifierLen),
2485 FixItHint::CreateRemoval(
2486 getSpecifierRange(flag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002487}
2488
2489void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00002490 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002491 const analyze_printf::OptionalFlag &ignoredFlag,
2492 const analyze_printf::OptionalFlag &flag,
2493 const char *startSpecifier,
2494 unsigned specifierLen) {
2495 // Warn about ignored flag with a fixit removal.
Richard Trieu55733de2011-10-28 00:41:25 +00002496 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2497 << ignoredFlag.toString() << flag.toString(),
2498 getLocationOfByte(ignoredFlag.getPosition()),
2499 /*IsStringLocation*/true,
2500 getSpecifierRange(startSpecifier, specifierLen),
2501 FixItHint::CreateRemoval(
2502 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002503}
2504
Richard Smith831421f2012-06-25 20:30:08 +00002505// Determines if the specified is a C++ class or struct containing
2506// a member with the specified name and kind (e.g. a CXXMethodDecl named
2507// "c_str()").
2508template<typename MemberKind>
2509static llvm::SmallPtrSet<MemberKind*, 1>
2510CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2511 const RecordType *RT = Ty->getAs<RecordType>();
2512 llvm::SmallPtrSet<MemberKind*, 1> Results;
2513
2514 if (!RT)
2515 return Results;
2516 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
2517 if (!RD)
2518 return Results;
2519
2520 LookupResult R(S, &S.PP.getIdentifierTable().get(Name), SourceLocation(),
2521 Sema::LookupMemberName);
2522
2523 // We just need to include all members of the right kind turned up by the
2524 // filter, at this point.
2525 if (S.LookupQualifiedName(R, RT->getDecl()))
2526 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2527 NamedDecl *decl = (*I)->getUnderlyingDecl();
2528 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
2529 Results.insert(FK);
2530 }
2531 return Results;
2532}
2533
2534// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgf3749f42012-08-07 08:11:26 +00002535// better diagnostic if so. AT is assumed to be valid.
Richard Smith831421f2012-06-25 20:30:08 +00002536// Returns true when a c_str() conversion method is found.
2537bool CheckPrintfHandler::checkForCStrMembers(
Hans Wennborgf3749f42012-08-07 08:11:26 +00002538 const analyze_printf::ArgType &AT, const Expr *E,
Richard Smith831421f2012-06-25 20:30:08 +00002539 const CharSourceRange &CSR) {
2540 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2541
2542 MethodSet Results =
2543 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
2544
2545 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2546 MI != ME; ++MI) {
2547 const CXXMethodDecl *Method = *MI;
2548 if (Method->getNumParams() == 0 &&
Hans Wennborgf3749f42012-08-07 08:11:26 +00002549 AT.matchesType(S.Context, Method->getResultType())) {
Richard Smith831421f2012-06-25 20:30:08 +00002550 // FIXME: Suggest parens if the expression needs them.
2551 SourceLocation EndLoc =
2552 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd());
2553 S.Diag(E->getLocStart(), diag::note_printf_c_str)
2554 << "c_str()"
2555 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
2556 return true;
2557 }
2558 }
2559
2560 return false;
2561}
2562
Ted Kremeneke0e53132010-01-28 23:39:18 +00002563bool
Ted Kremenek826a3452010-07-16 02:11:22 +00002564CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002565 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00002566 const char *startSpecifier,
2567 unsigned specifierLen) {
2568
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002569 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00002570 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002571 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00002572
Ted Kremenekbaa40062010-07-19 22:01:06 +00002573 if (FS.consumesDataArgument()) {
2574 if (atFirstArg) {
2575 atFirstArg = false;
2576 usesPositionalArgs = FS.usesPositionalArg();
2577 }
2578 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002579 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2580 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002581 return false;
2582 }
Ted Kremenek0d277352010-01-29 01:06:55 +00002583 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002584
Ted Kremenekefaff192010-02-27 01:41:03 +00002585 // First check if the field width, precision, and conversion specifier
2586 // have matching data arguments.
2587 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2588 startSpecifier, specifierLen)) {
2589 return false;
2590 }
2591
2592 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2593 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002594 return false;
2595 }
2596
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002597 if (!CS.consumesDataArgument()) {
2598 // FIXME: Technically specifying a precision or field width here
2599 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002600 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002601 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002602
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002603 // Consume the argument.
2604 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00002605 if (argIndex < NumDataArgs) {
2606 // The check to see if the argIndex is valid will come later.
2607 // We set the bit here because we may exit early from this
2608 // function if we encounter some other error.
2609 CoveredArgs.set(argIndex);
2610 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002611
2612 // Check for using an Objective-C specific conversion specifier
2613 // in a non-ObjC literal.
Jordan Rose50687312012-06-04 23:52:23 +00002614 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002615 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2616 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002617 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002618
Tom Caree4ee9662010-06-17 19:00:27 +00002619 // Check for invalid use of field width
2620 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002621 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00002622 startSpecifier, specifierLen);
2623 }
2624
2625 // Check for invalid use of precision
2626 if (!FS.hasValidPrecision()) {
2627 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
2628 startSpecifier, specifierLen);
2629 }
2630
2631 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00002632 if (!FS.hasValidThousandsGroupingPrefix())
2633 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002634 if (!FS.hasValidLeadingZeros())
2635 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
2636 if (!FS.hasValidPlusPrefix())
2637 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00002638 if (!FS.hasValidSpacePrefix())
2639 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002640 if (!FS.hasValidAlternativeForm())
2641 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
2642 if (!FS.hasValidLeftJustified())
2643 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
2644
2645 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00002646 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
2647 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
2648 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002649 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
2650 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
2651 startSpecifier, specifierLen);
2652
2653 // Check the length modifier is valid with the given conversion specifier.
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002654 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose8be066e2012-09-08 04:00:12 +00002655 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
2656 diag::warn_format_nonsensical_length);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002657 else if (!FS.hasStandardLengthModifier())
Jordan Rose8be066e2012-09-08 04:00:12 +00002658 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002659 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose8be066e2012-09-08 04:00:12 +00002660 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
2661 diag::warn_format_non_standard_conversion_spec);
Tom Caree4ee9662010-06-17 19:00:27 +00002662
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002663 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
2664 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
2665
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002666 // The remaining checks depend on the data arguments.
2667 if (HasVAListArg)
2668 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002669
Ted Kremenek666a1972010-07-26 19:45:42 +00002670 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002671 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002672
Jordan Rose48716662012-07-19 18:10:08 +00002673 const Expr *Arg = getDataArg(argIndex);
2674 if (!Arg)
2675 return true;
2676
2677 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith831421f2012-06-25 20:30:08 +00002678}
2679
Jordan Roseec087352012-09-05 22:56:26 +00002680static bool requiresParensToAddCast(const Expr *E) {
2681 // FIXME: We should have a general way to reason about operator
2682 // precedence and whether parens are actually needed here.
2683 // Take care of a few common cases where they aren't.
2684 const Expr *Inside = E->IgnoreImpCasts();
2685 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
2686 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
2687
2688 switch (Inside->getStmtClass()) {
2689 case Stmt::ArraySubscriptExprClass:
2690 case Stmt::CallExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00002691 case Stmt::CharacterLiteralClass:
2692 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00002693 case Stmt::DeclRefExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00002694 case Stmt::FloatingLiteralClass:
2695 case Stmt::IntegerLiteralClass:
Jordan Roseec087352012-09-05 22:56:26 +00002696 case Stmt::MemberExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00002697 case Stmt::ObjCArrayLiteralClass:
2698 case Stmt::ObjCBoolLiteralExprClass:
2699 case Stmt::ObjCBoxedExprClass:
2700 case Stmt::ObjCDictionaryLiteralClass:
2701 case Stmt::ObjCEncodeExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00002702 case Stmt::ObjCIvarRefExprClass:
2703 case Stmt::ObjCMessageExprClass:
2704 case Stmt::ObjCPropertyRefExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00002705 case Stmt::ObjCStringLiteralClass:
2706 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00002707 case Stmt::ParenExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00002708 case Stmt::StringLiteralClass:
Jordan Roseec087352012-09-05 22:56:26 +00002709 case Stmt::UnaryOperatorClass:
2710 return false;
2711 default:
2712 return true;
2713 }
2714}
2715
Richard Smith831421f2012-06-25 20:30:08 +00002716bool
2717CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2718 const char *StartSpecifier,
2719 unsigned SpecifierLen,
2720 const Expr *E) {
2721 using namespace analyze_format_string;
2722 using namespace analyze_printf;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002723 // Now type check the data expression that matches the
2724 // format specifier.
Hans Wennborgf3749f42012-08-07 08:11:26 +00002725 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
2726 ObjCContext);
Jordan Rose614a8652012-09-05 22:56:19 +00002727 if (!AT.isValid())
2728 return true;
Jordan Roseec087352012-09-05 22:56:26 +00002729
Jordan Rose448ac3e2012-12-05 18:44:40 +00002730 QualType ExprTy = E->getType();
2731 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose614a8652012-09-05 22:56:19 +00002732 return true;
Jordan Roseee0259d2012-06-04 22:48:57 +00002733
Jordan Rose614a8652012-09-05 22:56:19 +00002734 // Look through argument promotions for our error message's reported type.
2735 // This includes the integral and floating promotions, but excludes array
2736 // and function pointer decay; seeing that an argument intended to be a
2737 // string has type 'char [6]' is probably more confusing than 'char *'.
2738 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2739 if (ICE->getCastKind() == CK_IntegralCast ||
2740 ICE->getCastKind() == CK_FloatingCast) {
2741 E = ICE->getSubExpr();
Jordan Rose448ac3e2012-12-05 18:44:40 +00002742 ExprTy = E->getType();
Jordan Rose614a8652012-09-05 22:56:19 +00002743
2744 // Check if we didn't match because of an implicit cast from a 'char'
2745 // or 'short' to an 'int'. This is done because printf is a varargs
2746 // function.
2747 if (ICE->getType() == S.Context.IntTy ||
2748 ICE->getType() == S.Context.UnsignedIntTy) {
2749 // All further checking is done on the subexpression.
Jordan Rose448ac3e2012-12-05 18:44:40 +00002750 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose614a8652012-09-05 22:56:19 +00002751 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00002752 }
Jordan Roseee0259d2012-06-04 22:48:57 +00002753 }
Jordan Rose448ac3e2012-12-05 18:44:40 +00002754 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
2755 // Special case for 'a', which has type 'int' in C.
2756 // Note, however, that we do /not/ want to treat multibyte constants like
2757 // 'MooV' as characters! This form is deprecated but still exists.
2758 if (ExprTy == S.Context.IntTy)
2759 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
2760 ExprTy = S.Context.CharTy;
Jordan Rose614a8652012-09-05 22:56:19 +00002761 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002762
Jordan Rose2cd34402012-12-05 18:44:49 +00002763 // %C in an Objective-C context prints a unichar, not a wchar_t.
2764 // If the argument is an integer of some kind, believe the %C and suggest
2765 // a cast instead of changing the conversion specifier.
Jordan Rose448ac3e2012-12-05 18:44:40 +00002766 QualType IntendedTy = ExprTy;
Jordan Rose2cd34402012-12-05 18:44:49 +00002767 if (ObjCContext &&
2768 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
2769 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
2770 !ExprTy->isCharType()) {
2771 // 'unichar' is defined as a typedef of unsigned short, but we should
2772 // prefer using the typedef if it is visible.
2773 IntendedTy = S.Context.UnsignedShortTy;
2774
2775 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
2776 Sema::LookupOrdinaryName);
2777 if (S.LookupName(Result, S.getCurScope())) {
2778 NamedDecl *ND = Result.getFoundDecl();
2779 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
2780 if (TD->getUnderlyingType() == IntendedTy)
2781 IntendedTy = S.Context.getTypedefType(TD);
2782 }
2783 }
2784 }
2785
2786 // Special-case some of Darwin's platform-independence types by suggesting
2787 // casts to primitive types that are known to be large enough.
2788 bool ShouldNotPrintDirectly = false;
Jordan Roseec087352012-09-05 22:56:26 +00002789 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Jordan Roseec087352012-09-05 22:56:26 +00002790 if (const TypedefType *UserTy = IntendedTy->getAs<TypedefType>()) {
2791 StringRef Name = UserTy->getDecl()->getName();
Jordan Rose2cd34402012-12-05 18:44:49 +00002792 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Jordan Roseec087352012-09-05 22:56:26 +00002793 .Case("NSInteger", S.Context.LongTy)
2794 .Case("NSUInteger", S.Context.UnsignedLongTy)
2795 .Case("SInt32", S.Context.IntTy)
2796 .Case("UInt32", S.Context.UnsignedIntTy)
Jordan Rose2cd34402012-12-05 18:44:49 +00002797 .Default(QualType());
2798
2799 if (!CastTy.isNull()) {
2800 ShouldNotPrintDirectly = true;
2801 IntendedTy = CastTy;
2802 }
Jordan Roseec087352012-09-05 22:56:26 +00002803 }
2804 }
2805
Jordan Rose614a8652012-09-05 22:56:19 +00002806 // We may be able to offer a FixItHint if it is a supported type.
2807 PrintfSpecifier fixedFS = FS;
Jordan Roseec087352012-09-05 22:56:26 +00002808 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose614a8652012-09-05 22:56:19 +00002809 S.Context, ObjCContext);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002810
Jordan Rose614a8652012-09-05 22:56:19 +00002811 if (success) {
2812 // Get the fix string from the fixed format specifier
2813 SmallString<16> buf;
2814 llvm::raw_svector_ostream os(buf);
2815 fixedFS.toString(os);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002816
Jordan Roseec087352012-09-05 22:56:26 +00002817 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
2818
Jordan Rose2cd34402012-12-05 18:44:49 +00002819 if (IntendedTy == ExprTy) {
2820 // In this case, the specifier is wrong and should be changed to match
2821 // the argument.
2822 EmitFormatDiagnostic(
2823 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2824 << AT.getRepresentativeTypeName(S.Context) << IntendedTy
2825 << E->getSourceRange(),
2826 E->getLocStart(),
2827 /*IsStringLocation*/false,
2828 SpecRange,
2829 FixItHint::CreateReplacement(SpecRange, os.str()));
2830
2831 } else {
Jordan Roseec087352012-09-05 22:56:26 +00002832 // The canonical type for formatting this value is different from the
2833 // actual type of the expression. (This occurs, for example, with Darwin's
2834 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
2835 // should be printed as 'long' for 64-bit compatibility.)
2836 // Rather than emitting a normal format/argument mismatch, we want to
2837 // add a cast to the recommended type (and correct the format string
2838 // if necessary).
2839 SmallString<16> CastBuf;
2840 llvm::raw_svector_ostream CastFix(CastBuf);
2841 CastFix << "(";
2842 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
2843 CastFix << ")";
2844
2845 SmallVector<FixItHint,4> Hints;
2846 if (!AT.matchesType(S.Context, IntendedTy))
2847 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
2848
2849 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
2850 // If there's already a cast present, just replace it.
2851 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
2852 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
2853
2854 } else if (!requiresParensToAddCast(E)) {
2855 // If the expression has high enough precedence,
2856 // just write the C-style cast.
2857 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
2858 CastFix.str()));
2859 } else {
2860 // Otherwise, add parens around the expression as well as the cast.
2861 CastFix << "(";
2862 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
2863 CastFix.str()));
2864
2865 SourceLocation After = S.PP.getLocForEndOfToken(E->getLocEnd());
2866 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
2867 }
2868
Jordan Rose2cd34402012-12-05 18:44:49 +00002869 if (ShouldNotPrintDirectly) {
2870 // The expression has a type that should not be printed directly.
2871 // We extract the name from the typedef because we don't want to show
2872 // the underlying type in the diagnostic.
2873 StringRef Name = cast<TypedefType>(ExprTy)->getDecl()->getName();
Jordan Roseec087352012-09-05 22:56:26 +00002874
Jordan Rose2cd34402012-12-05 18:44:49 +00002875 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
2876 << Name << IntendedTy
2877 << E->getSourceRange(),
2878 E->getLocStart(), /*IsStringLocation=*/false,
2879 SpecRange, Hints);
2880 } else {
2881 // In this case, the expression could be printed using a different
2882 // specifier, but we've decided that the specifier is probably correct
2883 // and we should cast instead. Just use the normal warning message.
2884 EmitFormatDiagnostic(
2885 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2886 << AT.getRepresentativeTypeName(S.Context) << ExprTy
2887 << E->getSourceRange(),
2888 E->getLocStart(), /*IsStringLocation*/false,
2889 SpecRange, Hints);
2890 }
Jordan Roseec087352012-09-05 22:56:26 +00002891 }
Jordan Rose614a8652012-09-05 22:56:19 +00002892 } else {
2893 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
2894 SpecifierLen);
2895 // Since the warning for passing non-POD types to variadic functions
2896 // was deferred until now, we emit a warning for non-POD
2897 // arguments here.
Jordan Rose448ac3e2012-12-05 18:44:40 +00002898 if (S.isValidVarArgType(ExprTy) == Sema::VAK_Invalid) {
Jordan Rose614a8652012-09-05 22:56:19 +00002899 unsigned DiagKind;
Jordan Rose448ac3e2012-12-05 18:44:40 +00002900 if (ExprTy->isObjCObjectType())
Jordan Rose614a8652012-09-05 22:56:19 +00002901 DiagKind = diag::err_cannot_pass_objc_interface_to_vararg_format;
2902 else
2903 DiagKind = diag::warn_non_pod_vararg_with_format_string;
2904
2905 EmitFormatDiagnostic(
2906 S.PDiag(DiagKind)
2907 << S.getLangOpts().CPlusPlus0x
Jordan Rose448ac3e2012-12-05 18:44:40 +00002908 << ExprTy
Jordan Rose614a8652012-09-05 22:56:19 +00002909 << CallType
2910 << AT.getRepresentativeTypeName(S.Context)
2911 << CSR
2912 << E->getSourceRange(),
2913 E->getLocStart(), /*IsStringLocation*/false, CSR);
2914
2915 checkForCStrMembers(AT, E, CSR);
2916 } else
Richard Trieu55733de2011-10-28 00:41:25 +00002917 EmitFormatDiagnostic(
2918 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Jordan Rose448ac3e2012-12-05 18:44:40 +00002919 << AT.getRepresentativeTypeName(S.Context) << ExprTy
Jordan Rose614a8652012-09-05 22:56:19 +00002920 << CSR
Richard Smith831421f2012-06-25 20:30:08 +00002921 << E->getSourceRange(),
Jordan Rose614a8652012-09-05 22:56:19 +00002922 E->getLocStart(), /*IsStringLocation*/false, CSR);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002923 }
2924
Ted Kremeneke0e53132010-01-28 23:39:18 +00002925 return true;
2926}
2927
Ted Kremenek826a3452010-07-16 02:11:22 +00002928//===--- CHECK: Scanf format string checking ------------------------------===//
2929
2930namespace {
2931class CheckScanfHandler : public CheckFormatHandler {
2932public:
2933 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
2934 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002935 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002936 Expr **Args, unsigned NumArgs,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002937 unsigned formatIdx, bool inFunctionCall,
2938 Sema::VariadicCallType CallType)
Ted Kremenek826a3452010-07-16 02:11:22 +00002939 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002940 numDataArgs, beg, hasVAListArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002941 Args, NumArgs, formatIdx, inFunctionCall, CallType)
2942 {}
Ted Kremenek826a3452010-07-16 02:11:22 +00002943
2944 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
2945 const char *startSpecifier,
2946 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002947
2948 bool HandleInvalidScanfConversionSpecifier(
2949 const analyze_scanf::ScanfSpecifier &FS,
2950 const char *startSpecifier,
2951 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00002952
2953 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00002954};
Ted Kremenek07d161f2010-01-29 01:50:07 +00002955}
Ted Kremeneke0e53132010-01-28 23:39:18 +00002956
Ted Kremenekb7c21012010-07-16 18:28:03 +00002957void CheckScanfHandler::HandleIncompleteScanList(const char *start,
2958 const char *end) {
Richard Trieu55733de2011-10-28 00:41:25 +00002959 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
2960 getLocationOfByte(end), /*IsStringLocation*/true,
2961 getSpecifierRange(start, end - start));
Ted Kremenekb7c21012010-07-16 18:28:03 +00002962}
2963
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002964bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
2965 const analyze_scanf::ScanfSpecifier &FS,
2966 const char *startSpecifier,
2967 unsigned specifierLen) {
2968
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002969 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002970 FS.getConversionSpecifier();
2971
2972 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2973 getLocationOfByte(CS.getStart()),
2974 startSpecifier, specifierLen,
2975 CS.getStart(), CS.getLength());
2976}
2977
Ted Kremenek826a3452010-07-16 02:11:22 +00002978bool CheckScanfHandler::HandleScanfSpecifier(
2979 const analyze_scanf::ScanfSpecifier &FS,
2980 const char *startSpecifier,
2981 unsigned specifierLen) {
2982
2983 using namespace analyze_scanf;
2984 using namespace analyze_format_string;
2985
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002986 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002987
Ted Kremenekbaa40062010-07-19 22:01:06 +00002988 // Handle case where '%' and '*' don't consume an argument. These shouldn't
2989 // be used to decide if we are using positional arguments consistently.
2990 if (FS.consumesDataArgument()) {
2991 if (atFirstArg) {
2992 atFirstArg = false;
2993 usesPositionalArgs = FS.usesPositionalArg();
2994 }
2995 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002996 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2997 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002998 return false;
2999 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003000 }
3001
3002 // Check if the field with is non-zero.
3003 const OptionalAmount &Amt = FS.getFieldWidth();
3004 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3005 if (Amt.getConstantAmount() == 0) {
3006 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3007 Amt.getConstantLength());
Richard Trieu55733de2011-10-28 00:41:25 +00003008 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3009 getLocationOfByte(Amt.getStart()),
3010 /*IsStringLocation*/true, R,
3011 FixItHint::CreateRemoval(R));
Ted Kremenek826a3452010-07-16 02:11:22 +00003012 }
3013 }
3014
3015 if (!FS.consumesDataArgument()) {
3016 // FIXME: Technically specifying a precision or field width here
3017 // makes no sense. Worth issuing a warning at some point.
3018 return true;
3019 }
3020
3021 // Consume the argument.
3022 unsigned argIndex = FS.getArgIndex();
3023 if (argIndex < NumDataArgs) {
3024 // The check to see if the argIndex is valid will come later.
3025 // We set the bit here because we may exit early from this
3026 // function if we encounter some other error.
3027 CoveredArgs.set(argIndex);
3028 }
3029
Ted Kremenek1e51c202010-07-20 20:04:47 +00003030 // Check the length modifier is valid with the given conversion specifier.
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003031 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose8be066e2012-09-08 04:00:12 +00003032 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3033 diag::warn_format_nonsensical_length);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003034 else if (!FS.hasStandardLengthModifier())
Jordan Rose8be066e2012-09-08 04:00:12 +00003035 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003036 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose8be066e2012-09-08 04:00:12 +00003037 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3038 diag::warn_format_non_standard_conversion_spec);
Hans Wennborg76517422012-02-22 10:17:01 +00003039
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003040 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3041 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3042
Ted Kremenek826a3452010-07-16 02:11:22 +00003043 // The remaining checks depend on the data arguments.
3044 if (HasVAListArg)
3045 return true;
3046
Ted Kremenek666a1972010-07-26 19:45:42 +00003047 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00003048 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00003049
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003050 // Check that the argument type matches the format specifier.
3051 const Expr *Ex = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00003052 if (!Ex)
3053 return true;
3054
Hans Wennborg58e1e542012-08-07 08:59:46 +00003055 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3056 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003057 ScanfSpecifier fixedFS = FS;
David Blaikie4e4d0842012-03-11 07:00:24 +00003058 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
Hans Wennborgbe6126a2012-02-15 09:59:46 +00003059 S.Context);
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003060
3061 if (success) {
3062 // Get the fix string from the fixed format specifier.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003063 SmallString<128> buf;
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003064 llvm::raw_svector_ostream os(buf);
3065 fixedFS.toString(os);
3066
3067 EmitFormatDiagnostic(
3068 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg58e1e542012-08-07 08:59:46 +00003069 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003070 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00003071 Ex->getLocStart(),
3072 /*IsStringLocation*/false,
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003073 getSpecifierRange(startSpecifier, specifierLen),
3074 FixItHint::CreateReplacement(
3075 getSpecifierRange(startSpecifier, specifierLen),
3076 os.str()));
3077 } else {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003078 EmitFormatDiagnostic(
3079 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg58e1e542012-08-07 08:59:46 +00003080 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003081 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00003082 Ex->getLocStart(),
3083 /*IsStringLocation*/false,
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003084 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003085 }
3086 }
3087
Ted Kremenek826a3452010-07-16 02:11:22 +00003088 return true;
3089}
3090
3091void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00003092 const Expr *OrigFormatExpr,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003093 Expr **Args, unsigned NumArgs,
3094 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003095 unsigned firstDataArg, FormatStringType Type,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003096 bool inFunctionCall, VariadicCallType CallType) {
Ted Kremenek826a3452010-07-16 02:11:22 +00003097
Ted Kremeneke0e53132010-01-28 23:39:18 +00003098 // CHECK: is the format string a wide literal?
Richard Smithdf9ef1b2012-06-13 05:37:23 +00003099 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu55733de2011-10-28 00:41:25 +00003100 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003101 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00003102 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3103 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00003104 return;
3105 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003106
Ted Kremeneke0e53132010-01-28 23:39:18 +00003107 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner5f9e2722011-07-23 10:55:15 +00003108 StringRef StrRef = FExpr->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00003109 const char *Str = StrRef.data();
3110 unsigned StrLen = StrRef.size();
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003111 const unsigned numDataArgs = NumArgs - firstDataArg;
Ted Kremenek826a3452010-07-16 02:11:22 +00003112
Ted Kremeneke0e53132010-01-28 23:39:18 +00003113 // CHECK: empty format string?
Ted Kremenek4cd57912011-09-29 05:52:16 +00003114 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu55733de2011-10-28 00:41:25 +00003115 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003116 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00003117 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3118 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00003119 return;
3120 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003121
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003122 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek826a3452010-07-16 02:11:22 +00003123 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00003124 numDataArgs, (Type == FST_NSString),
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003125 Str, HasVAListArg, Args, NumArgs, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003126 inFunctionCall, CallType);
Ted Kremenek826a3452010-07-16 02:11:22 +00003127
Hans Wennborgd02deeb2011-12-15 10:25:47 +00003128 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose275b6f52012-09-13 02:11:03 +00003129 getLangOpts(),
3130 Context.getTargetInfo()))
Ted Kremenek826a3452010-07-16 02:11:22 +00003131 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003132 } else if (Type == FST_Scanf) {
Jordan Rose50687312012-06-04 23:52:23 +00003133 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003134 Str, HasVAListArg, Args, NumArgs, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003135 inFunctionCall, CallType);
Ted Kremenek826a3452010-07-16 02:11:22 +00003136
Hans Wennborgd02deeb2011-12-15 10:25:47 +00003137 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose275b6f52012-09-13 02:11:03 +00003138 getLangOpts(),
3139 Context.getTargetInfo()))
Ted Kremenek826a3452010-07-16 02:11:22 +00003140 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003141 } // TODO: handle other formats
Ted Kremenekce7024e2010-01-28 01:18:22 +00003142}
3143
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003144//===--- CHECK: Standard memory functions ---------------------------------===//
3145
Douglas Gregor2a053a32011-05-03 20:05:22 +00003146/// \brief Determine whether the given type is a dynamic class type (e.g.,
3147/// whether it has a vtable).
3148static bool isDynamicClassType(QualType T) {
3149 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3150 if (CXXRecordDecl *Definition = Record->getDefinition())
3151 if (Definition->isDynamicClass())
3152 return true;
3153
3154 return false;
3155}
3156
Chandler Carrutha72a12f2011-06-21 23:04:20 +00003157/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth000d4282011-06-16 09:09:40 +00003158/// otherwise returns NULL.
3159static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Webere4a1c642011-06-14 16:14:58 +00003160 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth000d4282011-06-16 09:09:40 +00003161 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3162 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
3163 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00003164
Chandler Carruth000d4282011-06-16 09:09:40 +00003165 return 0;
3166}
3167
Chandler Carrutha72a12f2011-06-21 23:04:20 +00003168/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth000d4282011-06-16 09:09:40 +00003169static QualType getSizeOfArgType(const Expr* E) {
3170 if (const UnaryExprOrTypeTraitExpr *SizeOf =
3171 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3172 if (SizeOf->getKind() == clang::UETT_SizeOf)
3173 return SizeOf->getTypeOfArgument();
3174
3175 return QualType();
Nico Webere4a1c642011-06-14 16:14:58 +00003176}
3177
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003178/// \brief Check for dangerous or invalid arguments to memset().
3179///
Chandler Carruth929f0132011-06-03 06:23:57 +00003180/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003181/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
3182/// function calls.
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003183///
3184/// \param Call The call expression to diagnose.
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003185void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks0a151a12012-01-17 00:37:07 +00003186 unsigned BId,
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003187 IdentifierInfo *FnName) {
Anna Zaks0a151a12012-01-17 00:37:07 +00003188 assert(BId != 0);
3189
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00003190 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor707a23e2011-06-16 17:56:04 +00003191 // we have enough arguments, and if not, abort further checking.
Anna Zaks0a151a12012-01-17 00:37:07 +00003192 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Webercda57822011-10-13 22:30:23 +00003193 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00003194 return;
3195
Anna Zaks0a151a12012-01-17 00:37:07 +00003196 unsigned LastArg = (BId == Builtin::BImemset ||
3197 BId == Builtin::BIstrndup ? 1 : 2);
3198 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Webercda57822011-10-13 22:30:23 +00003199 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth000d4282011-06-16 09:09:40 +00003200
3201 // We have special checking when the length is a sizeof expression.
3202 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
3203 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
3204 llvm::FoldingSetNodeID SizeOfArgID;
3205
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003206 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
3207 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00003208 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003209
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003210 QualType DestTy = Dest->getType();
3211 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
3212 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00003213
Chandler Carruth000d4282011-06-16 09:09:40 +00003214 // Never warn about void type pointers. This can be used to suppress
3215 // false positives.
3216 if (PointeeTy->isVoidType())
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003217 continue;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003218
Chandler Carruth000d4282011-06-16 09:09:40 +00003219 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
3220 // actually comparing the expressions for equality. Because computing the
3221 // expression IDs can be expensive, we only do this if the diagnostic is
3222 // enabled.
3223 if (SizeOfArg &&
3224 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
3225 SizeOfArg->getExprLoc())) {
3226 // We only compute IDs for expressions if the warning is enabled, and
3227 // cache the sizeof arg's ID.
3228 if (SizeOfArgID == llvm::FoldingSetNodeID())
3229 SizeOfArg->Profile(SizeOfArgID, Context, true);
3230 llvm::FoldingSetNodeID DestID;
3231 Dest->Profile(DestID, Context, true);
3232 if (DestID == SizeOfArgID) {
Nico Webercda57822011-10-13 22:30:23 +00003233 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
3234 // over sizeof(src) as well.
Chandler Carruth000d4282011-06-16 09:09:40 +00003235 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks6fcb3722012-05-30 00:34:21 +00003236 StringRef ReadableName = FnName->getName();
3237
Chandler Carruth000d4282011-06-16 09:09:40 +00003238 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaks90c78322012-05-30 23:14:52 +00003239 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth000d4282011-06-16 09:09:40 +00003240 ActionIdx = 1; // If its an address-of operator, just remove it.
3241 if (Context.getTypeSize(PointeeTy) == Context.getCharWidth())
3242 ActionIdx = 2; // If the pointee's size is sizeof(char),
3243 // suggest an explicit length.
Anna Zaks6fcb3722012-05-30 00:34:21 +00003244
3245 // If the function is defined as a builtin macro, do not show macro
3246 // expansion.
3247 SourceLocation SL = SizeOfArg->getExprLoc();
3248 SourceRange DSR = Dest->getSourceRange();
3249 SourceRange SSR = SizeOfArg->getSourceRange();
3250 SourceManager &SM = PP.getSourceManager();
3251
3252 if (SM.isMacroArgExpansion(SL)) {
3253 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
3254 SL = SM.getSpellingLoc(SL);
3255 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
3256 SM.getSpellingLoc(DSR.getEnd()));
3257 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
3258 SM.getSpellingLoc(SSR.getEnd()));
3259 }
3260
Anna Zaks90c78322012-05-30 23:14:52 +00003261 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth000d4282011-06-16 09:09:40 +00003262 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks6fcb3722012-05-30 00:34:21 +00003263 << ReadableName
Anna Zaks90c78322012-05-30 23:14:52 +00003264 << PointeeTy
3265 << DestTy
Anna Zaks6fcb3722012-05-30 00:34:21 +00003266 << DSR
Anna Zaks90c78322012-05-30 23:14:52 +00003267 << SSR);
3268 DiagRuntimeBehavior(SL, SizeOfArg,
3269 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
3270 << ActionIdx
3271 << SSR);
3272
Chandler Carruth000d4282011-06-16 09:09:40 +00003273 break;
3274 }
3275 }
3276
3277 // Also check for cases where the sizeof argument is the exact same
3278 // type as the memory argument, and where it points to a user-defined
3279 // record type.
3280 if (SizeOfArgTy != QualType()) {
3281 if (PointeeTy->isRecordType() &&
3282 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
3283 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
3284 PDiag(diag::warn_sizeof_pointer_type_memaccess)
3285 << FnName << SizeOfArgTy << ArgIdx
3286 << PointeeTy << Dest->getSourceRange()
3287 << LenExpr->getSourceRange());
3288 break;
3289 }
Nico Webere4a1c642011-06-14 16:14:58 +00003290 }
3291
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003292 // Always complain about dynamic classes.
Anna Zaks0a151a12012-01-17 00:37:07 +00003293 if (isDynamicClassType(PointeeTy)) {
3294
3295 unsigned OperationType = 0;
3296 // "overwritten" if we're warning about the destination for any call
3297 // but memcmp; otherwise a verb appropriate to the call.
3298 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
3299 if (BId == Builtin::BImemcpy)
3300 OperationType = 1;
3301 else if(BId == Builtin::BImemmove)
3302 OperationType = 2;
3303 else if (BId == Builtin::BImemcmp)
3304 OperationType = 3;
3305 }
3306
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003307 DiagRuntimeBehavior(
3308 Dest->getExprLoc(), Dest,
3309 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks0a151a12012-01-17 00:37:07 +00003310 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Anna Zaksd9b859a2012-01-13 21:52:01 +00003311 << FnName << PointeeTy
Anna Zaks0a151a12012-01-17 00:37:07 +00003312 << OperationType
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003313 << Call->getCallee()->getSourceRange());
Anna Zaks0a151a12012-01-17 00:37:07 +00003314 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
3315 BId != Builtin::BImemset)
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003316 DiagRuntimeBehavior(
3317 Dest->getExprLoc(), Dest,
3318 PDiag(diag::warn_arc_object_memaccess)
3319 << ArgIdx << FnName << PointeeTy
3320 << Call->getCallee()->getSourceRange());
John McCallf85e1932011-06-15 23:02:42 +00003321 else
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003322 continue;
John McCallf85e1932011-06-15 23:02:42 +00003323
3324 DiagRuntimeBehavior(
3325 Dest->getExprLoc(), Dest,
Chandler Carruth929f0132011-06-03 06:23:57 +00003326 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003327 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
3328 break;
3329 }
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003330 }
3331}
3332
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003333// A little helper routine: ignore addition and subtraction of integer literals.
3334// This intentionally does not ignore all integer constant expressions because
3335// we don't want to remove sizeof().
3336static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
3337 Ex = Ex->IgnoreParenCasts();
3338
3339 for (;;) {
3340 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
3341 if (!BO || !BO->isAdditiveOp())
3342 break;
3343
3344 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
3345 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
3346
3347 if (isa<IntegerLiteral>(RHS))
3348 Ex = LHS;
3349 else if (isa<IntegerLiteral>(LHS))
3350 Ex = RHS;
3351 else
3352 break;
3353 }
3354
3355 return Ex;
3356}
3357
Anna Zaks0f38ace2012-08-08 21:42:23 +00003358static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
3359 ASTContext &Context) {
3360 // Only handle constant-sized or VLAs, but not flexible members.
3361 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
3362 // Only issue the FIXIT for arrays of size > 1.
3363 if (CAT->getSize().getSExtValue() <= 1)
3364 return false;
3365 } else if (!Ty->isVariableArrayType()) {
3366 return false;
3367 }
3368 return true;
3369}
3370
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003371// Warn if the user has made the 'size' argument to strlcpy or strlcat
3372// be the size of the source, instead of the destination.
3373void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
3374 IdentifierInfo *FnName) {
3375
3376 // Don't crash if the user has the wrong number of arguments
3377 if (Call->getNumArgs() != 3)
3378 return;
3379
3380 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
3381 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
3382 const Expr *CompareWithSrc = NULL;
3383
3384 // Look for 'strlcpy(dst, x, sizeof(x))'
3385 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
3386 CompareWithSrc = Ex;
3387 else {
3388 // Look for 'strlcpy(dst, x, strlen(x))'
3389 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Richard Smith180f4792011-11-10 06:34:14 +00003390 if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003391 && SizeCall->getNumArgs() == 1)
3392 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
3393 }
3394 }
3395
3396 if (!CompareWithSrc)
3397 return;
3398
3399 // Determine if the argument to sizeof/strlen is equal to the source
3400 // argument. In principle there's all kinds of things you could do
3401 // here, for instance creating an == expression and evaluating it with
3402 // EvaluateAsBooleanCondition, but this uses a more direct technique:
3403 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
3404 if (!SrcArgDRE)
3405 return;
3406
3407 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
3408 if (!CompareWithSrcDRE ||
3409 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
3410 return;
3411
3412 const Expr *OriginalSizeArg = Call->getArg(2);
3413 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
3414 << OriginalSizeArg->getSourceRange() << FnName;
3415
3416 // Output a FIXIT hint if the destination is an array (rather than a
3417 // pointer to an array). This could be enhanced to handle some
3418 // pointers if we know the actual size, like if DstArg is 'array+2'
3419 // we could say 'sizeof(array)-2'.
3420 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks0f38ace2012-08-08 21:42:23 +00003421 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek8f746222011-08-18 22:48:41 +00003422 return;
Ted Kremenek8f746222011-08-18 22:48:41 +00003423
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003424 SmallString<128> sizeString;
Ted Kremenek8f746222011-08-18 22:48:41 +00003425 llvm::raw_svector_ostream OS(sizeString);
3426 OS << "sizeof(";
Richard Smithd1420c62012-08-16 03:56:14 +00003427 DstArg->printPretty(OS, 0, getPrintingPolicy());
Ted Kremenek8f746222011-08-18 22:48:41 +00003428 OS << ")";
3429
3430 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
3431 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
3432 OS.str());
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003433}
3434
Anna Zaksc36bedc2012-02-01 19:08:57 +00003435/// Check if two expressions refer to the same declaration.
3436static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
3437 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
3438 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
3439 return D1->getDecl() == D2->getDecl();
3440 return false;
3441}
3442
3443static const Expr *getStrlenExprArg(const Expr *E) {
3444 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
3445 const FunctionDecl *FD = CE->getDirectCallee();
3446 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
3447 return 0;
3448 return CE->getArg(0)->IgnoreParenCasts();
3449 }
3450 return 0;
3451}
3452
3453// Warn on anti-patterns as the 'size' argument to strncat.
3454// The correct size argument should look like following:
3455// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
3456void Sema::CheckStrncatArguments(const CallExpr *CE,
3457 IdentifierInfo *FnName) {
3458 // Don't crash if the user has the wrong number of arguments.
3459 if (CE->getNumArgs() < 3)
3460 return;
3461 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
3462 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
3463 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
3464
3465 // Identify common expressions, which are wrongly used as the size argument
3466 // to strncat and may lead to buffer overflows.
3467 unsigned PatternType = 0;
3468 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
3469 // - sizeof(dst)
3470 if (referToTheSameDecl(SizeOfArg, DstArg))
3471 PatternType = 1;
3472 // - sizeof(src)
3473 else if (referToTheSameDecl(SizeOfArg, SrcArg))
3474 PatternType = 2;
3475 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
3476 if (BE->getOpcode() == BO_Sub) {
3477 const Expr *L = BE->getLHS()->IgnoreParenCasts();
3478 const Expr *R = BE->getRHS()->IgnoreParenCasts();
3479 // - sizeof(dst) - strlen(dst)
3480 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
3481 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
3482 PatternType = 1;
3483 // - sizeof(src) - (anything)
3484 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
3485 PatternType = 2;
3486 }
3487 }
3488
3489 if (PatternType == 0)
3490 return;
3491
Anna Zaksafdb0412012-02-03 01:27:37 +00003492 // Generate the diagnostic.
3493 SourceLocation SL = LenArg->getLocStart();
3494 SourceRange SR = LenArg->getSourceRange();
3495 SourceManager &SM = PP.getSourceManager();
3496
3497 // If the function is defined as a builtin macro, do not show macro expansion.
3498 if (SM.isMacroArgExpansion(SL)) {
3499 SL = SM.getSpellingLoc(SL);
3500 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
3501 SM.getSpellingLoc(SR.getEnd()));
3502 }
3503
Anna Zaks0f38ace2012-08-08 21:42:23 +00003504 // Check if the destination is an array (rather than a pointer to an array).
3505 QualType DstTy = DstArg->getType();
3506 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
3507 Context);
3508 if (!isKnownSizeArray) {
3509 if (PatternType == 1)
3510 Diag(SL, diag::warn_strncat_wrong_size) << SR;
3511 else
3512 Diag(SL, diag::warn_strncat_src_size) << SR;
3513 return;
3514 }
3515
Anna Zaksc36bedc2012-02-01 19:08:57 +00003516 if (PatternType == 1)
Anna Zaksafdb0412012-02-03 01:27:37 +00003517 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003518 else
Anna Zaksafdb0412012-02-03 01:27:37 +00003519 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003520
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003521 SmallString<128> sizeString;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003522 llvm::raw_svector_ostream OS(sizeString);
3523 OS << "sizeof(";
Richard Smithd1420c62012-08-16 03:56:14 +00003524 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003525 OS << ") - ";
3526 OS << "strlen(";
Richard Smithd1420c62012-08-16 03:56:14 +00003527 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003528 OS << ") - 1";
3529
Anna Zaksafdb0412012-02-03 01:27:37 +00003530 Diag(SL, diag::note_strncat_wrong_size)
3531 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003532}
3533
Ted Kremenek06de2762007-08-17 16:46:58 +00003534//===--- CHECK: Return Address of Stack Variable --------------------------===//
3535
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003536static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3537 Decl *ParentDecl);
3538static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
3539 Decl *ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003540
3541/// CheckReturnStackAddr - Check if a return statement returns the address
3542/// of a stack variable.
3543void
3544Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
3545 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00003546
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003547 Expr *stackE = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003548 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003549
3550 // Perform checking for returned stack addresses, local blocks,
3551 // label addresses or references to temporaries.
John McCallf85e1932011-06-15 23:02:42 +00003552 if (lhsType->isPointerType() ||
David Blaikie4e4d0842012-03-11 07:00:24 +00003553 (!getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003554 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003555 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003556 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003557 }
3558
3559 if (stackE == 0)
3560 return; // Nothing suspicious was found.
3561
3562 SourceLocation diagLoc;
3563 SourceRange diagRange;
3564 if (refVars.empty()) {
3565 diagLoc = stackE->getLocStart();
3566 diagRange = stackE->getSourceRange();
3567 } else {
3568 // We followed through a reference variable. 'stackE' contains the
3569 // problematic expression but we will warn at the return statement pointing
3570 // at the reference variable. We will later display the "trail" of
3571 // reference variables using notes.
3572 diagLoc = refVars[0]->getLocStart();
3573 diagRange = refVars[0]->getSourceRange();
3574 }
3575
3576 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
3577 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
3578 : diag::warn_ret_stack_addr)
3579 << DR->getDecl()->getDeclName() << diagRange;
3580 } else if (isa<BlockExpr>(stackE)) { // local block.
3581 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
3582 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
3583 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
3584 } else { // local temporary.
3585 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
3586 : diag::warn_ret_local_temp_addr)
3587 << diagRange;
3588 }
3589
3590 // Display the "trail" of reference variables that we followed until we
3591 // found the problematic expression using notes.
3592 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
3593 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
3594 // If this var binds to another reference var, show the range of the next
3595 // var, otherwise the var binds to the problematic expression, in which case
3596 // show the range of the expression.
3597 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
3598 : stackE->getSourceRange();
3599 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
3600 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00003601 }
3602}
3603
3604/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
3605/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003606/// to a location on the stack, a local block, an address of a label, or a
3607/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00003608/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003609/// encounter a subexpression that (1) clearly does not lead to one of the
3610/// above problematic expressions (2) is something we cannot determine leads to
3611/// a problematic expression based on such local checking.
3612///
3613/// Both EvalAddr and EvalVal follow through reference variables to evaluate
3614/// the expression that they point to. Such variables are added to the
3615/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00003616///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00003617/// EvalAddr processes expressions that are pointers that are used as
3618/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003619/// At the base case of the recursion is a check for the above problematic
3620/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00003621///
3622/// This implementation handles:
3623///
3624/// * pointer-to-pointer casts
3625/// * implicit conversions from array references to pointers
3626/// * taking the address of fields
3627/// * arbitrary interplay between "&" and "*" operators
3628/// * pointer arithmetic from an address of a stack variable
3629/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003630static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3631 Decl *ParentDecl) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003632 if (E->isTypeDependent())
3633 return NULL;
3634
Ted Kremenek06de2762007-08-17 16:46:58 +00003635 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00003636 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00003637 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003638 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003639 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00003640
Peter Collingbournef111d932011-04-15 00:35:48 +00003641 E = E->IgnoreParens();
3642
Ted Kremenek06de2762007-08-17 16:46:58 +00003643 // Our "symbolic interpreter" is just a dispatch off the currently
3644 // viewed AST node. We then recursively traverse the AST by calling
3645 // EvalAddr and EvalVal appropriately.
3646 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003647 case Stmt::DeclRefExprClass: {
3648 DeclRefExpr *DR = cast<DeclRefExpr>(E);
3649
3650 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
3651 // If this is a reference variable, follow through to the expression that
3652 // it points to.
3653 if (V->hasLocalStorage() &&
3654 V->getType()->isReferenceType() && V->hasInit()) {
3655 // Add the reference variable to the "trail".
3656 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003657 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003658 }
3659
3660 return NULL;
3661 }
Ted Kremenek06de2762007-08-17 16:46:58 +00003662
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003663 case Stmt::UnaryOperatorClass: {
3664 // The only unary operator that make sense to handle here
3665 // is AddrOf. All others don't make sense as pointers.
3666 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003667
John McCall2de56d12010-08-25 11:45:40 +00003668 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003669 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003670 else
Ted Kremenek06de2762007-08-17 16:46:58 +00003671 return NULL;
3672 }
Mike Stump1eb44332009-09-09 15:08:12 +00003673
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003674 case Stmt::BinaryOperatorClass: {
3675 // Handle pointer arithmetic. All other binary operators are not valid
3676 // in this context.
3677 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00003678 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00003679
John McCall2de56d12010-08-25 11:45:40 +00003680 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003681 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00003682
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003683 Expr *Base = B->getLHS();
3684
3685 // Determine which argument is the real pointer base. It could be
3686 // the RHS argument instead of the LHS.
3687 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00003688
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003689 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003690 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003691 }
Steve Naroff61f40a22008-09-10 19:17:48 +00003692
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003693 // For conditional operators we need to see if either the LHS or RHS are
3694 // valid DeclRefExpr*s. If one of them is valid, we return it.
3695 case Stmt::ConditionalOperatorClass: {
3696 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003697
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003698 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003699 if (Expr *lhsExpr = C->getLHS()) {
3700 // In C++, we can have a throw-expression, which has 'void' type.
3701 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003702 if (Expr* LHS = EvalAddr(lhsExpr, refVars, ParentDecl))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003703 return LHS;
3704 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003705
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003706 // In C++, we can have a throw-expression, which has 'void' type.
3707 if (C->getRHS()->getType()->isVoidType())
3708 return NULL;
3709
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003710 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003711 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003712
3713 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00003714 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003715 return E; // local block.
3716 return NULL;
3717
3718 case Stmt::AddrLabelExprClass:
3719 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00003720
John McCall80ee6e82011-11-10 05:35:25 +00003721 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003722 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
3723 ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00003724
Ted Kremenek54b52742008-08-07 00:49:01 +00003725 // For casts, we need to handle conversions from arrays to
3726 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00003727 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00003728 case Stmt::CStyleCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00003729 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8b9414e2012-02-23 23:04:32 +00003730 case Stmt::ObjCBridgedCastExprClass:
Mike Stump1eb44332009-09-09 15:08:12 +00003731 case Stmt::CXXStaticCastExprClass:
3732 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00003733 case Stmt::CXXConstCastExprClass:
3734 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8b9414e2012-02-23 23:04:32 +00003735 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
3736 switch (cast<CastExpr>(E)->getCastKind()) {
3737 case CK_BitCast:
3738 case CK_LValueToRValue:
3739 case CK_NoOp:
3740 case CK_BaseToDerived:
3741 case CK_DerivedToBase:
3742 case CK_UncheckedDerivedToBase:
3743 case CK_Dynamic:
3744 case CK_CPointerToObjCPointerCast:
3745 case CK_BlockPointerToObjCPointerCast:
3746 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003747 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00003748
3749 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003750 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00003751
3752 default:
3753 return 0;
3754 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003755 }
Mike Stump1eb44332009-09-09 15:08:12 +00003756
Douglas Gregor03e80032011-06-21 17:03:29 +00003757 case Stmt::MaterializeTemporaryExprClass:
3758 if (Expr *Result = EvalAddr(
3759 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003760 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00003761 return Result;
3762
3763 return E;
3764
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003765 // Everything else: we simply don't reason about them.
3766 default:
3767 return NULL;
3768 }
Ted Kremenek06de2762007-08-17 16:46:58 +00003769}
Mike Stump1eb44332009-09-09 15:08:12 +00003770
Ted Kremenek06de2762007-08-17 16:46:58 +00003771
3772/// EvalVal - This function is complements EvalAddr in the mutual recursion.
3773/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003774static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3775 Decl *ParentDecl) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003776do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00003777 // We should only be called for evaluating non-pointer expressions, or
3778 // expressions with a pointer type that are not used as references but instead
3779 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00003780
Ted Kremenek06de2762007-08-17 16:46:58 +00003781 // Our "symbolic interpreter" is just a dispatch off the currently
3782 // viewed AST node. We then recursively traverse the AST by calling
3783 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00003784
3785 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00003786 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003787 case Stmt::ImplicitCastExprClass: {
3788 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00003789 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003790 E = IE->getSubExpr();
3791 continue;
3792 }
3793 return NULL;
3794 }
3795
John McCall80ee6e82011-11-10 05:35:25 +00003796 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003797 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00003798
Douglas Gregora2813ce2009-10-23 18:54:35 +00003799 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003800 // When we hit a DeclRefExpr we are looking at code that refers to a
3801 // variable's name. If it's not a reference variable we check if it has
3802 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00003803 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003804
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003805 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
3806 // Check if it refers to itself, e.g. "int& i = i;".
3807 if (V == ParentDecl)
3808 return DR;
3809
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003810 if (V->hasLocalStorage()) {
3811 if (!V->getType()->isReferenceType())
3812 return DR;
3813
3814 // Reference variable, follow through to the expression that
3815 // it points to.
3816 if (V->hasInit()) {
3817 // Add the reference variable to the "trail".
3818 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003819 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003820 }
3821 }
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003822 }
Mike Stump1eb44332009-09-09 15:08:12 +00003823
Ted Kremenek06de2762007-08-17 16:46:58 +00003824 return NULL;
3825 }
Mike Stump1eb44332009-09-09 15:08:12 +00003826
Ted Kremenek06de2762007-08-17 16:46:58 +00003827 case Stmt::UnaryOperatorClass: {
3828 // The only unary operator that make sense to handle here
3829 // is Deref. All others don't resolve to a "name." This includes
3830 // handling all sorts of rvalues passed to a unary operator.
3831 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003832
John McCall2de56d12010-08-25 11:45:40 +00003833 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003834 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003835
3836 return NULL;
3837 }
Mike Stump1eb44332009-09-09 15:08:12 +00003838
Ted Kremenek06de2762007-08-17 16:46:58 +00003839 case Stmt::ArraySubscriptExprClass: {
3840 // Array subscripts are potential references to data on the stack. We
3841 // retrieve the DeclRefExpr* for the array variable if it indeed
3842 // has local storage.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003843 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003844 }
Mike Stump1eb44332009-09-09 15:08:12 +00003845
Ted Kremenek06de2762007-08-17 16:46:58 +00003846 case Stmt::ConditionalOperatorClass: {
3847 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003848 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00003849 ConditionalOperator *C = cast<ConditionalOperator>(E);
3850
Anders Carlsson39073232007-11-30 19:04:31 +00003851 // Handle the GNU extension for missing LHS.
3852 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003853 if (Expr *LHS = EvalVal(lhsExpr, refVars, ParentDecl))
Anders Carlsson39073232007-11-30 19:04:31 +00003854 return LHS;
3855
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003856 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003857 }
Mike Stump1eb44332009-09-09 15:08:12 +00003858
Ted Kremenek06de2762007-08-17 16:46:58 +00003859 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00003860 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00003861 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003862
Ted Kremenek06de2762007-08-17 16:46:58 +00003863 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00003864 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00003865 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00003866
3867 // Check whether the member type is itself a reference, in which case
3868 // we're not going to refer to the member, but to what the member refers to.
3869 if (M->getMemberDecl()->getType()->isReferenceType())
3870 return NULL;
3871
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003872 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003873 }
Mike Stump1eb44332009-09-09 15:08:12 +00003874
Douglas Gregor03e80032011-06-21 17:03:29 +00003875 case Stmt::MaterializeTemporaryExprClass:
3876 if (Expr *Result = EvalVal(
3877 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003878 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00003879 return Result;
3880
3881 return E;
3882
Ted Kremenek06de2762007-08-17 16:46:58 +00003883 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003884 // Check that we don't return or take the address of a reference to a
3885 // temporary. This is only useful in C++.
3886 if (!E->isTypeDependent() && E->isRValue())
3887 return E;
3888
3889 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00003890 return NULL;
3891 }
Ted Kremenek68957a92010-08-04 20:01:07 +00003892} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00003893}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003894
3895//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
3896
3897/// Check for comparisons of floating point operands using != and ==.
3898/// Issue a warning if these are no self-comparisons, as they are not likely
3899/// to do what the programmer intended.
Richard Trieudd225092011-09-15 21:56:47 +00003900void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieudd225092011-09-15 21:56:47 +00003901 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
3902 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003903
3904 // Special case: check for x == x (which is OK).
3905 // Do not emit warnings for such cases.
3906 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
3907 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
3908 if (DRL->getDecl() == DRR->getDecl())
David Blaikie980343b2012-07-16 20:47:22 +00003909 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003910
3911
Ted Kremenek1b500bb2007-11-29 00:59:04 +00003912 // Special case: check for comparisons against literals that can be exactly
3913 // represented by APFloat. In such cases, do not emit a warning. This
3914 // is a heuristic: often comparison against such literals are used to
3915 // detect if a value in a variable has not changed. This clearly can
3916 // lead to false negatives.
David Blaikie980343b2012-07-16 20:47:22 +00003917 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
3918 if (FLL->isExact())
3919 return;
3920 } else
3921 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
3922 if (FLR->isExact())
3923 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003924
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003925 // Check for comparisons with builtin types.
David Blaikie980343b2012-07-16 20:47:22 +00003926 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
3927 if (CL->isBuiltinCall())
3928 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003929
David Blaikie980343b2012-07-16 20:47:22 +00003930 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
3931 if (CR->isBuiltinCall())
3932 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003933
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003934 // Emit the diagnostic.
David Blaikie980343b2012-07-16 20:47:22 +00003935 Diag(Loc, diag::warn_floatingpoint_eq)
3936 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003937}
John McCallba26e582010-01-04 23:21:16 +00003938
John McCallf2370c92010-01-06 05:24:50 +00003939//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
3940//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00003941
John McCallf2370c92010-01-06 05:24:50 +00003942namespace {
John McCallba26e582010-01-04 23:21:16 +00003943
John McCallf2370c92010-01-06 05:24:50 +00003944/// Structure recording the 'active' range of an integer-valued
3945/// expression.
3946struct IntRange {
3947 /// The number of bits active in the int.
3948 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00003949
John McCallf2370c92010-01-06 05:24:50 +00003950 /// True if the int is known not to have negative values.
3951 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00003952
John McCallf2370c92010-01-06 05:24:50 +00003953 IntRange(unsigned Width, bool NonNegative)
3954 : Width(Width), NonNegative(NonNegative)
3955 {}
John McCallba26e582010-01-04 23:21:16 +00003956
John McCall1844a6e2010-11-10 23:38:19 +00003957 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00003958 static IntRange forBoolType() {
3959 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00003960 }
3961
John McCall1844a6e2010-11-10 23:38:19 +00003962 /// Returns the range of an opaque value of the given integral type.
3963 static IntRange forValueOfType(ASTContext &C, QualType T) {
3964 return forValueOfCanonicalType(C,
3965 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00003966 }
3967
John McCall1844a6e2010-11-10 23:38:19 +00003968 /// Returns the range of an opaque value of a canonical integral type.
3969 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00003970 assert(T->isCanonicalUnqualified());
3971
3972 if (const VectorType *VT = dyn_cast<VectorType>(T))
3973 T = VT->getElementType().getTypePtr();
3974 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
3975 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00003976
John McCall091f23f2010-11-09 22:22:12 +00003977 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00003978 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
3979 EnumDecl *Enum = ET->getDecl();
John McCall5e1cdac2011-10-07 06:10:15 +00003980 if (!Enum->isCompleteDefinition())
John McCall091f23f2010-11-09 22:22:12 +00003981 return IntRange(C.getIntWidth(QualType(T, 0)), false);
3982
John McCall323ed742010-05-06 08:58:33 +00003983 unsigned NumPositive = Enum->getNumPositiveBits();
3984 unsigned NumNegative = Enum->getNumNegativeBits();
3985
Richard Trieu8f50b242012-11-16 01:32:40 +00003986 if (NumNegative == 0)
3987 return IntRange(NumPositive, true/*NonNegative*/);
3988 else
3989 return IntRange(std::max(NumPositive + 1, NumNegative),
3990 false/*NonNegative*/);
John McCall323ed742010-05-06 08:58:33 +00003991 }
John McCallf2370c92010-01-06 05:24:50 +00003992
3993 const BuiltinType *BT = cast<BuiltinType>(T);
3994 assert(BT->isInteger());
3995
3996 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
3997 }
3998
John McCall1844a6e2010-11-10 23:38:19 +00003999 /// Returns the "target" range of a canonical integral type, i.e.
4000 /// the range of values expressible in the type.
4001 ///
4002 /// This matches forValueOfCanonicalType except that enums have the
4003 /// full range of their type, not the range of their enumerators.
4004 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
4005 assert(T->isCanonicalUnqualified());
4006
4007 if (const VectorType *VT = dyn_cast<VectorType>(T))
4008 T = VT->getElementType().getTypePtr();
4009 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4010 T = CT->getElementType().getTypePtr();
4011 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor69ff26b2011-09-08 23:29:05 +00004012 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall1844a6e2010-11-10 23:38:19 +00004013
4014 const BuiltinType *BT = cast<BuiltinType>(T);
4015 assert(BT->isInteger());
4016
4017 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4018 }
4019
4020 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00004021 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00004022 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00004023 L.NonNegative && R.NonNegative);
4024 }
4025
John McCall1844a6e2010-11-10 23:38:19 +00004026 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00004027 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00004028 return IntRange(std::min(L.Width, R.Width),
4029 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00004030 }
4031};
4032
Ted Kremenek0692a192012-01-31 05:37:37 +00004033static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
4034 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004035 if (value.isSigned() && value.isNegative())
4036 return IntRange(value.getMinSignedBits(), false);
4037
4038 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00004039 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00004040
4041 // isNonNegative() just checks the sign bit without considering
4042 // signedness.
4043 return IntRange(value.getActiveBits(), true);
4044}
4045
Ted Kremenek0692a192012-01-31 05:37:37 +00004046static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
4047 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004048 if (result.isInt())
4049 return GetValueRange(C, result.getInt(), MaxWidth);
4050
4051 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00004052 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
4053 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
4054 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
4055 R = IntRange::join(R, El);
4056 }
John McCallf2370c92010-01-06 05:24:50 +00004057 return R;
4058 }
4059
4060 if (result.isComplexInt()) {
4061 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
4062 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
4063 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00004064 }
4065
4066 // This can happen with lossless casts to intptr_t of "based" lvalues.
4067 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00004068 // FIXME: The only reason we need to pass the type in here is to get
4069 // the sign right on this one case. It would be nice if APValue
4070 // preserved this.
Eli Friedman65639282012-01-04 23:13:47 +00004071 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00004072 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall51313c32010-01-04 23:31:57 +00004073}
John McCallf2370c92010-01-06 05:24:50 +00004074
4075/// Pseudo-evaluate the given integer expression, estimating the
4076/// range of values it might take.
4077///
4078/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek0692a192012-01-31 05:37:37 +00004079static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004080 E = E->IgnoreParens();
4081
4082 // Try a full evaluation first.
4083 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00004084 if (E->EvaluateAsRValue(result, C))
John McCall0acc3112010-01-06 22:57:21 +00004085 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00004086
4087 // I think we only want to look through implicit casts here; if the
4088 // user has an explicit widening cast, we should treat the value as
4089 // being of the new, wider type.
4090 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedmanb17ee5b2011-12-15 02:41:52 +00004091 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCallf2370c92010-01-06 05:24:50 +00004092 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
4093
John McCall1844a6e2010-11-10 23:38:19 +00004094 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCallf2370c92010-01-06 05:24:50 +00004095
John McCall2de56d12010-08-25 11:45:40 +00004096 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00004097
John McCallf2370c92010-01-06 05:24:50 +00004098 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00004099 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00004100 return OutputTypeRange;
4101
4102 IntRange SubRange
4103 = GetExprRange(C, CE->getSubExpr(),
4104 std::min(MaxWidth, OutputTypeRange.Width));
4105
4106 // Bail out if the subexpr's range is as wide as the cast type.
4107 if (SubRange.Width >= OutputTypeRange.Width)
4108 return OutputTypeRange;
4109
4110 // Otherwise, we take the smaller width, and we're non-negative if
4111 // either the output type or the subexpr is.
4112 return IntRange(SubRange.Width,
4113 SubRange.NonNegative || OutputTypeRange.NonNegative);
4114 }
4115
4116 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4117 // If we can fold the condition, just take that operand.
4118 bool CondResult;
4119 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
4120 return GetExprRange(C, CondResult ? CO->getTrueExpr()
4121 : CO->getFalseExpr(),
4122 MaxWidth);
4123
4124 // Otherwise, conservatively merge.
4125 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
4126 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
4127 return IntRange::join(L, R);
4128 }
4129
4130 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4131 switch (BO->getOpcode()) {
4132
4133 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00004134 case BO_LAnd:
4135 case BO_LOr:
4136 case BO_LT:
4137 case BO_GT:
4138 case BO_LE:
4139 case BO_GE:
4140 case BO_EQ:
4141 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00004142 return IntRange::forBoolType();
4143
John McCall862ff872011-07-13 06:35:24 +00004144 // The type of the assignments is the type of the LHS, so the RHS
4145 // is not necessarily the same type.
John McCall2de56d12010-08-25 11:45:40 +00004146 case BO_MulAssign:
4147 case BO_DivAssign:
4148 case BO_RemAssign:
4149 case BO_AddAssign:
4150 case BO_SubAssign:
John McCall862ff872011-07-13 06:35:24 +00004151 case BO_XorAssign:
4152 case BO_OrAssign:
4153 // TODO: bitfields?
John McCall1844a6e2010-11-10 23:38:19 +00004154 return IntRange::forValueOfType(C, E->getType());
John McCallc0cd21d2010-02-23 19:22:29 +00004155
John McCall862ff872011-07-13 06:35:24 +00004156 // Simple assignments just pass through the RHS, which will have
4157 // been coerced to the LHS type.
4158 case BO_Assign:
4159 // TODO: bitfields?
4160 return GetExprRange(C, BO->getRHS(), MaxWidth);
4161
John McCallf2370c92010-01-06 05:24:50 +00004162 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00004163 case BO_PtrMemD:
4164 case BO_PtrMemI:
John McCall1844a6e2010-11-10 23:38:19 +00004165 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00004166
John McCall60fad452010-01-06 22:07:33 +00004167 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00004168 case BO_And:
4169 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00004170 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
4171 GetExprRange(C, BO->getRHS(), MaxWidth));
4172
John McCallf2370c92010-01-06 05:24:50 +00004173 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00004174 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00004175 // ...except that we want to treat '1 << (blah)' as logically
4176 // positive. It's an important idiom.
4177 if (IntegerLiteral *I
4178 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
4179 if (I->getValue() == 1) {
John McCall1844a6e2010-11-10 23:38:19 +00004180 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall3aae6092010-04-07 01:14:35 +00004181 return IntRange(R.Width, /*NonNegative*/ true);
4182 }
4183 }
4184 // fallthrough
4185
John McCall2de56d12010-08-25 11:45:40 +00004186 case BO_ShlAssign:
John McCall1844a6e2010-11-10 23:38:19 +00004187 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00004188
John McCall60fad452010-01-06 22:07:33 +00004189 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00004190 case BO_Shr:
4191 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00004192 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4193
4194 // If the shift amount is a positive constant, drop the width by
4195 // that much.
4196 llvm::APSInt shift;
4197 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
4198 shift.isNonNegative()) {
4199 unsigned zext = shift.getZExtValue();
4200 if (zext >= L.Width)
4201 L.Width = (L.NonNegative ? 0 : 1);
4202 else
4203 L.Width -= zext;
4204 }
4205
4206 return L;
4207 }
4208
4209 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00004210 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00004211 return GetExprRange(C, BO->getRHS(), MaxWidth);
4212
John McCall60fad452010-01-06 22:07:33 +00004213 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00004214 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00004215 if (BO->getLHS()->getType()->isPointerType())
John McCall1844a6e2010-11-10 23:38:19 +00004216 return IntRange::forValueOfType(C, E->getType());
John McCall00fe7612011-07-14 22:39:48 +00004217 break;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00004218
John McCall00fe7612011-07-14 22:39:48 +00004219 // The width of a division result is mostly determined by the size
4220 // of the LHS.
4221 case BO_Div: {
4222 // Don't 'pre-truncate' the operands.
4223 unsigned opWidth = C.getIntWidth(E->getType());
4224 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4225
4226 // If the divisor is constant, use that.
4227 llvm::APSInt divisor;
4228 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
4229 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
4230 if (log2 >= L.Width)
4231 L.Width = (L.NonNegative ? 0 : 1);
4232 else
4233 L.Width = std::min(L.Width - log2, MaxWidth);
4234 return L;
4235 }
4236
4237 // Otherwise, just use the LHS's width.
4238 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4239 return IntRange(L.Width, L.NonNegative && R.NonNegative);
4240 }
4241
4242 // The result of a remainder can't be larger than the result of
4243 // either side.
4244 case BO_Rem: {
4245 // Don't 'pre-truncate' the operands.
4246 unsigned opWidth = C.getIntWidth(E->getType());
4247 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4248 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4249
4250 IntRange meet = IntRange::meet(L, R);
4251 meet.Width = std::min(meet.Width, MaxWidth);
4252 return meet;
4253 }
4254
4255 // The default behavior is okay for these.
4256 case BO_Mul:
4257 case BO_Add:
4258 case BO_Xor:
4259 case BO_Or:
John McCallf2370c92010-01-06 05:24:50 +00004260 break;
4261 }
4262
John McCall00fe7612011-07-14 22:39:48 +00004263 // The default case is to treat the operation as if it were closed
4264 // on the narrowest type that encompasses both operands.
John McCallf2370c92010-01-06 05:24:50 +00004265 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4266 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
4267 return IntRange::join(L, R);
4268 }
4269
4270 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
4271 switch (UO->getOpcode()) {
4272 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00004273 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00004274 return IntRange::forBoolType();
4275
4276 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00004277 case UO_Deref:
4278 case UO_AddrOf: // should be impossible
John McCall1844a6e2010-11-10 23:38:19 +00004279 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00004280
4281 default:
4282 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
4283 }
4284 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004285
4286 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall1844a6e2010-11-10 23:38:19 +00004287 IntRange::forValueOfType(C, E->getType());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004288 }
John McCallf2370c92010-01-06 05:24:50 +00004289
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004290 if (FieldDecl *BitField = E->getBitField())
4291 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00004292 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00004293
John McCall1844a6e2010-11-10 23:38:19 +00004294 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00004295}
John McCall51313c32010-01-04 23:31:57 +00004296
Ted Kremenek0692a192012-01-31 05:37:37 +00004297static IntRange GetExprRange(ASTContext &C, Expr *E) {
John McCall323ed742010-05-06 08:58:33 +00004298 return GetExprRange(C, E, C.getIntWidth(E->getType()));
4299}
4300
John McCall51313c32010-01-04 23:31:57 +00004301/// Checks whether the given value, which currently has the given
4302/// source semantics, has the same value when coerced through the
4303/// target semantics.
Ted Kremenek0692a192012-01-31 05:37:37 +00004304static bool IsSameFloatAfterCast(const llvm::APFloat &value,
4305 const llvm::fltSemantics &Src,
4306 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00004307 llvm::APFloat truncated = value;
4308
4309 bool ignored;
4310 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
4311 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
4312
4313 return truncated.bitwiseIsEqual(value);
4314}
4315
4316/// Checks whether the given value, which currently has the given
4317/// source semantics, has the same value when coerced through the
4318/// target semantics.
4319///
4320/// The value might be a vector of floats (or a complex number).
Ted Kremenek0692a192012-01-31 05:37:37 +00004321static bool IsSameFloatAfterCast(const APValue &value,
4322 const llvm::fltSemantics &Src,
4323 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00004324 if (value.isFloat())
4325 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
4326
4327 if (value.isVector()) {
4328 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
4329 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
4330 return false;
4331 return true;
4332 }
4333
4334 assert(value.isComplexFloat());
4335 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
4336 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
4337}
4338
Ted Kremenek0692a192012-01-31 05:37:37 +00004339static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00004340
Ted Kremeneke3b159c2010-09-23 21:43:44 +00004341static bool IsZero(Sema &S, Expr *E) {
4342 // Suppress cases where we are comparing against an enum constant.
4343 if (const DeclRefExpr *DR =
4344 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
4345 if (isa<EnumConstantDecl>(DR->getDecl()))
4346 return false;
4347
4348 // Suppress cases where the '0' value is expanded from a macro.
4349 if (E->getLocStart().isMacroID())
4350 return false;
4351
John McCall323ed742010-05-06 08:58:33 +00004352 llvm::APSInt Value;
4353 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
4354}
4355
John McCall372e1032010-10-06 00:25:24 +00004356static bool HasEnumType(Expr *E) {
4357 // Strip off implicit integral promotions.
4358 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00004359 if (ICE->getCastKind() != CK_IntegralCast &&
4360 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00004361 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00004362 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00004363 }
4364
4365 return E->getType()->isEnumeralType();
4366}
4367
Ted Kremenek0692a192012-01-31 05:37:37 +00004368static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00004369 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00004370 if (E->isValueDependent())
4371 return;
4372
John McCall2de56d12010-08-25 11:45:40 +00004373 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00004374 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004375 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00004376 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004377 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00004378 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004379 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00004380 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004381 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00004382 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004383 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00004384 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004385 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00004386 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004387 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00004388 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4389 }
4390}
4391
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004392static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004393 Expr *Constant, Expr *Other,
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004394 llvm::APSInt Value,
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004395 bool RhsConstant) {
Richard Trieu526e6272012-11-14 22:50:24 +00004396 // 0 values are handled later by CheckTrivialUnsignedComparison().
4397 if (Value == 0)
4398 return;
4399
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004400 BinaryOperatorKind op = E->getOpcode();
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004401 QualType OtherT = Other->getType();
4402 QualType ConstantT = Constant->getType();
Richard Trieu526e6272012-11-14 22:50:24 +00004403 QualType CommonT = E->getLHS()->getType();
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004404 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004405 return;
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004406 assert((OtherT->isIntegerType() && ConstantT->isIntegerType())
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004407 && "comparison with non-integer type");
Richard Trieu526e6272012-11-14 22:50:24 +00004408
4409 bool ConstantSigned = ConstantT->isSignedIntegerType();
Richard Trieu526e6272012-11-14 22:50:24 +00004410 bool CommonSigned = CommonT->isSignedIntegerType();
4411
4412 bool EqualityOnly = false;
4413
4414 // TODO: Investigate using GetExprRange() to get tighter bounds on
4415 // on the bit ranges.
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004416 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
Richard Trieu526e6272012-11-14 22:50:24 +00004417 unsigned OtherWidth = OtherRange.Width;
4418
4419 if (CommonSigned) {
4420 // The common type is signed, therefore no signed to unsigned conversion.
Eli Friedmand87de7b2012-11-30 23:09:29 +00004421 if (!OtherRange.NonNegative) {
Richard Trieu526e6272012-11-14 22:50:24 +00004422 // Check that the constant is representable in type OtherT.
4423 if (ConstantSigned) {
4424 if (OtherWidth >= Value.getMinSignedBits())
4425 return;
4426 } else { // !ConstantSigned
4427 if (OtherWidth >= Value.getActiveBits() + 1)
4428 return;
4429 }
4430 } else { // !OtherSigned
4431 // Check that the constant is representable in type OtherT.
4432 // Negative values are out of range.
4433 if (ConstantSigned) {
4434 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
4435 return;
4436 } else { // !ConstantSigned
4437 if (OtherWidth >= Value.getActiveBits())
4438 return;
4439 }
4440 }
4441 } else { // !CommonSigned
Eli Friedmand87de7b2012-11-30 23:09:29 +00004442 if (OtherRange.NonNegative) {
Richard Trieu526e6272012-11-14 22:50:24 +00004443 if (OtherWidth >= Value.getActiveBits())
4444 return;
Eli Friedmand87de7b2012-11-30 23:09:29 +00004445 } else if (!OtherRange.NonNegative && !ConstantSigned) {
Richard Trieu526e6272012-11-14 22:50:24 +00004446 // Check to see if the constant is representable in OtherT.
4447 if (OtherWidth > Value.getActiveBits())
4448 return;
4449 // Check to see if the constant is equivalent to a negative value
4450 // cast to CommonT.
4451 if (S.Context.getIntWidth(ConstantT) == S.Context.getIntWidth(CommonT) &&
Richard Trieu5d1cf4f2012-11-15 03:43:50 +00004452 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
Richard Trieu526e6272012-11-14 22:50:24 +00004453 return;
4454 // The constant value rests between values that OtherT can represent after
4455 // conversion. Relational comparison still works, but equality
4456 // comparisons will be tautological.
4457 EqualityOnly = true;
4458 } else { // OtherSigned && ConstantSigned
4459 assert(0 && "Two signed types converted to unsigned types.");
4460 }
4461 }
4462
4463 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
4464
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004465 bool IsTrue = true;
Richard Trieu526e6272012-11-14 22:50:24 +00004466 if (op == BO_EQ || op == BO_NE) {
4467 IsTrue = op == BO_NE;
4468 } else if (EqualityOnly) {
4469 return;
4470 } else if (RhsConstant) {
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004471 if (op == BO_GT || op == BO_GE)
Richard Trieu526e6272012-11-14 22:50:24 +00004472 IsTrue = !PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004473 else // op == BO_LT || op == BO_LE
Richard Trieu526e6272012-11-14 22:50:24 +00004474 IsTrue = PositiveConstant;
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004475 } else {
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004476 if (op == BO_LT || op == BO_LE)
Richard Trieu526e6272012-11-14 22:50:24 +00004477 IsTrue = !PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004478 else // op == BO_GT || op == BO_GE
Richard Trieu526e6272012-11-14 22:50:24 +00004479 IsTrue = PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004480 }
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004481 SmallString<16> PrettySourceValue(Value.toString(10));
4482 S.Diag(E->getOperatorLoc(), diag::warn_out_of_range_compare)
Richard Trieu526e6272012-11-14 22:50:24 +00004483 << PrettySourceValue << OtherT << IsTrue
4484 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004485}
4486
John McCall323ed742010-05-06 08:58:33 +00004487/// Analyze the operands of the given comparison. Implements the
4488/// fallback case from AnalyzeComparison.
Ted Kremenek0692a192012-01-31 05:37:37 +00004489static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00004490 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4491 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00004492}
John McCall51313c32010-01-04 23:31:57 +00004493
John McCallba26e582010-01-04 23:21:16 +00004494/// \brief Implements -Wsign-compare.
4495///
Richard Trieudd225092011-09-15 21:56:47 +00004496/// \param E the binary operator to check for warnings
Ted Kremenek0692a192012-01-31 05:37:37 +00004497static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCall323ed742010-05-06 08:58:33 +00004498 // The type the comparison is being performed in.
4499 QualType T = E->getLHS()->getType();
4500 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
4501 && "comparison with mismatched types");
Fariborz Jahanianab4702f2012-09-18 17:46:26 +00004502 if (E->isValueDependent())
4503 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004504
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004505 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
4506 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004507
4508 bool IsComparisonConstant = false;
4509
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004510 // Check whether an integer constant comparison results in a value
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004511 // of 'true' or 'false'.
4512 if (T->isIntegralType(S.Context)) {
4513 llvm::APSInt RHSValue;
4514 bool IsRHSIntegralLiteral =
4515 RHS->isIntegerConstantExpr(RHSValue, S.Context);
4516 llvm::APSInt LHSValue;
4517 bool IsLHSIntegralLiteral =
4518 LHS->isIntegerConstantExpr(LHSValue, S.Context);
4519 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
4520 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
4521 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
4522 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
4523 else
4524 IsComparisonConstant =
4525 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004526 } else if (!T->hasUnsignedIntegerRepresentation())
4527 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004528
John McCall323ed742010-05-06 08:58:33 +00004529 // We don't do anything special if this isn't an unsigned integral
4530 // comparison: we're only interested in integral comparisons, and
4531 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00004532 //
4533 // We also don't care about value-dependent expressions or expressions
4534 // whose result is a constant.
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004535 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCall323ed742010-05-06 08:58:33 +00004536 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004537
John McCall323ed742010-05-06 08:58:33 +00004538 // Check to see if one of the (unmodified) operands is of different
4539 // signedness.
4540 Expr *signedOperand, *unsignedOperand;
Richard Trieudd225092011-09-15 21:56:47 +00004541 if (LHS->getType()->hasSignedIntegerRepresentation()) {
4542 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00004543 "unsigned comparison between two signed integer expressions?");
Richard Trieudd225092011-09-15 21:56:47 +00004544 signedOperand = LHS;
4545 unsignedOperand = RHS;
4546 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
4547 signedOperand = RHS;
4548 unsignedOperand = LHS;
John McCallba26e582010-01-04 23:21:16 +00004549 } else {
John McCall323ed742010-05-06 08:58:33 +00004550 CheckTrivialUnsignedComparison(S, E);
4551 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004552 }
4553
John McCall323ed742010-05-06 08:58:33 +00004554 // Otherwise, calculate the effective range of the signed operand.
4555 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00004556
John McCall323ed742010-05-06 08:58:33 +00004557 // Go ahead and analyze implicit conversions in the operands. Note
4558 // that we skip the implicit conversions on both sides.
Richard Trieudd225092011-09-15 21:56:47 +00004559 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
4560 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00004561
John McCall323ed742010-05-06 08:58:33 +00004562 // If the signed range is non-negative, -Wsign-compare won't fire,
4563 // but we should still check for comparisons which are always true
4564 // or false.
4565 if (signedRange.NonNegative)
4566 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004567
4568 // For (in)equality comparisons, if the unsigned operand is a
4569 // constant which cannot collide with a overflowed signed operand,
4570 // then reinterpreting the signed operand as unsigned will not
4571 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00004572 if (E->isEqualityOp()) {
4573 unsigned comparisonWidth = S.Context.getIntWidth(T);
4574 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00004575
John McCall323ed742010-05-06 08:58:33 +00004576 // We should never be unable to prove that the unsigned operand is
4577 // non-negative.
4578 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
4579
4580 if (unsignedRange.Width < comparisonWidth)
4581 return;
4582 }
4583
Douglas Gregor6d3b93d2012-05-01 01:53:49 +00004584 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
4585 S.PDiag(diag::warn_mixed_sign_comparison)
4586 << LHS->getType() << RHS->getType()
4587 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallba26e582010-01-04 23:21:16 +00004588}
4589
John McCall15d7d122010-11-11 03:21:53 +00004590/// Analyzes an attempt to assign the given value to a bitfield.
4591///
4592/// Returns true if there was something fishy about the attempt.
Ted Kremenek0692a192012-01-31 05:37:37 +00004593static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
4594 SourceLocation InitLoc) {
John McCall15d7d122010-11-11 03:21:53 +00004595 assert(Bitfield->isBitField());
4596 if (Bitfield->isInvalidDecl())
4597 return false;
4598
John McCall91b60142010-11-11 05:33:51 +00004599 // White-list bool bitfields.
4600 if (Bitfield->getType()->isBooleanType())
4601 return false;
4602
Douglas Gregor46ff3032011-02-04 13:09:01 +00004603 // Ignore value- or type-dependent expressions.
4604 if (Bitfield->getBitWidth()->isValueDependent() ||
4605 Bitfield->getBitWidth()->isTypeDependent() ||
4606 Init->isValueDependent() ||
4607 Init->isTypeDependent())
4608 return false;
4609
John McCall15d7d122010-11-11 03:21:53 +00004610 Expr *OriginalInit = Init->IgnoreParenImpCasts();
4611
Richard Smith80d4b552011-12-28 19:48:30 +00004612 llvm::APSInt Value;
4613 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall15d7d122010-11-11 03:21:53 +00004614 return false;
4615
John McCall15d7d122010-11-11 03:21:53 +00004616 unsigned OriginalWidth = Value.getBitWidth();
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004617 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall15d7d122010-11-11 03:21:53 +00004618
4619 if (OriginalWidth <= FieldWidth)
4620 return false;
4621
Eli Friedman3a643af2012-01-26 23:11:39 +00004622 // Compute the value which the bitfield will contain.
Jay Foad9f71a8f2010-12-07 08:25:34 +00004623 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedman3a643af2012-01-26 23:11:39 +00004624 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall15d7d122010-11-11 03:21:53 +00004625
Eli Friedman3a643af2012-01-26 23:11:39 +00004626 // Check whether the stored value is equal to the original value.
4627 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieue1ecdc12012-07-23 20:21:35 +00004628 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall15d7d122010-11-11 03:21:53 +00004629 return false;
4630
Eli Friedman3a643af2012-01-26 23:11:39 +00004631 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedman34ff0622012-02-02 00:40:20 +00004632 // therefore don't strictly fit into a signed bitfield of width 1.
4633 if (FieldWidth == 1 && Value == 1)
Eli Friedman3a643af2012-01-26 23:11:39 +00004634 return false;
4635
John McCall15d7d122010-11-11 03:21:53 +00004636 std::string PrettyValue = Value.toString(10);
4637 std::string PrettyTrunc = TruncatedValue.toString(10);
4638
4639 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
4640 << PrettyValue << PrettyTrunc << OriginalInit->getType()
4641 << Init->getSourceRange();
4642
4643 return true;
4644}
4645
John McCallbeb22aa2010-11-09 23:24:47 +00004646/// Analyze the given simple or compound assignment for warning-worthy
4647/// operations.
Ted Kremenek0692a192012-01-31 05:37:37 +00004648static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCallbeb22aa2010-11-09 23:24:47 +00004649 // Just recurse on the LHS.
4650 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4651
4652 // We want to recurse on the RHS as normal unless we're assigning to
4653 // a bitfield.
4654 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
John McCall15d7d122010-11-11 03:21:53 +00004655 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
4656 E->getOperatorLoc())) {
4657 // Recurse, ignoring any implicit conversions on the RHS.
4658 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
4659 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00004660 }
4661 }
4662
4663 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
4664}
4665
John McCall51313c32010-01-04 23:31:57 +00004666/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00004667static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00004668 SourceLocation CContext, unsigned diag,
4669 bool pruneControlFlow = false) {
4670 if (pruneControlFlow) {
4671 S.DiagRuntimeBehavior(E->getExprLoc(), E,
4672 S.PDiag(diag)
4673 << SourceType << T << E->getSourceRange()
4674 << SourceRange(CContext));
4675 return;
4676 }
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004677 S.Diag(E->getExprLoc(), diag)
4678 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
4679}
4680
Chandler Carruthe1b02e02011-04-05 06:47:57 +00004681/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00004682static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00004683 SourceLocation CContext, unsigned diag,
4684 bool pruneControlFlow = false) {
4685 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruthe1b02e02011-04-05 06:47:57 +00004686}
4687
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004688/// Diagnose an implicit cast from a literal expression. Does not warn when the
4689/// cast wouldn't lose information.
Chandler Carruthf65076e2011-04-10 08:36:24 +00004690void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
4691 SourceLocation CContext) {
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004692 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruthf65076e2011-04-10 08:36:24 +00004693 bool isExact = false;
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004694 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00004695 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
4696 T->hasUnsignedIntegerRepresentation());
4697 if (Value.convertToInteger(IntegerValue,
Chandler Carruthf65076e2011-04-10 08:36:24 +00004698 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004699 == llvm::APFloat::opOK && isExact)
Chandler Carruthf65076e2011-04-10 08:36:24 +00004700 return;
4701
David Blaikiebe0ee872012-05-15 16:56:36 +00004702 SmallString<16> PrettySourceValue;
4703 Value.toString(PrettySourceValue);
David Blaikiede7e7b82012-05-15 17:18:27 +00004704 SmallString<16> PrettyTargetValue;
David Blaikiebe0ee872012-05-15 16:56:36 +00004705 if (T->isSpecificBuiltinType(BuiltinType::Bool))
4706 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
4707 else
David Blaikiede7e7b82012-05-15 17:18:27 +00004708 IntegerValue.toString(PrettyTargetValue);
David Blaikiebe0ee872012-05-15 16:56:36 +00004709
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004710 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikiebe0ee872012-05-15 16:56:36 +00004711 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
4712 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruthf65076e2011-04-10 08:36:24 +00004713}
4714
John McCall091f23f2010-11-09 22:22:12 +00004715std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
4716 if (!Range.Width) return "0";
4717
4718 llvm::APSInt ValueInRange = Value;
4719 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00004720 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00004721 return ValueInRange.toString(10);
4722}
4723
Hans Wennborg88617a22012-08-28 15:44:30 +00004724static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
4725 if (!isa<ImplicitCastExpr>(Ex))
4726 return false;
4727
4728 Expr *InnerE = Ex->IgnoreParenImpCasts();
4729 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
4730 const Type *Source =
4731 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
4732 if (Target->isDependentType())
4733 return false;
4734
4735 const BuiltinType *FloatCandidateBT =
4736 dyn_cast<BuiltinType>(ToBool ? Source : Target);
4737 const Type *BoolCandidateType = ToBool ? Target : Source;
4738
4739 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
4740 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
4741}
4742
4743void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
4744 SourceLocation CC) {
4745 unsigned NumArgs = TheCall->getNumArgs();
4746 for (unsigned i = 0; i < NumArgs; ++i) {
4747 Expr *CurrA = TheCall->getArg(i);
4748 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
4749 continue;
4750
4751 bool IsSwapped = ((i > 0) &&
4752 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
4753 IsSwapped |= ((i < (NumArgs - 1)) &&
4754 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
4755 if (IsSwapped) {
4756 // Warn on this floating-point to bool conversion.
4757 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
4758 CurrA->getType(), CC,
4759 diag::warn_impcast_floating_point_to_bool);
4760 }
4761 }
4762}
4763
John McCall323ed742010-05-06 08:58:33 +00004764void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00004765 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00004766 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00004767
John McCall323ed742010-05-06 08:58:33 +00004768 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
4769 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
4770 if (Source == Target) return;
4771 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00004772
Chandler Carruth108f7562011-07-26 05:40:03 +00004773 // If the conversion context location is invalid don't complain. We also
4774 // don't want to emit a warning if the issue occurs from the expansion of
4775 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
4776 // delay this check as long as possible. Once we detect we are in that
4777 // scenario, we just return.
Ted Kremenekef9ff882011-03-10 20:03:42 +00004778 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00004779 return;
4780
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004781 // Diagnose implicit casts to bool.
4782 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
4783 if (isa<StringLiteral>(E))
4784 // Warn on string literal to bool. Checks for string literals in logical
4785 // expressions, for instances, assert(0 && "error here"), is prevented
4786 // by a check in AnalyzeImplicitConversions().
4787 return DiagnoseImpCast(S, E, T, CC,
4788 diag::warn_impcast_string_literal_to_bool);
Lang Hamese14ca9f2011-12-05 20:49:50 +00004789 if (Source->isFunctionType()) {
4790 // Warn on function to bool. Checks free functions and static member
4791 // functions. Weakly imported functions are excluded from the check,
4792 // since it's common to test their value to check whether the linker
4793 // found a definition for them.
4794 ValueDecl *D = 0;
4795 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
4796 D = R->getDecl();
4797 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
4798 D = M->getMemberDecl();
4799 }
4800
4801 if (D && !D->isWeak()) {
Richard Trieu26b45d82011-12-06 04:48:01 +00004802 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
4803 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
4804 << F << E->getSourceRange() << SourceRange(CC);
David Blaikie2def7732011-12-09 21:42:37 +00004805 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
4806 << FixItHint::CreateInsertion(E->getExprLoc(), "&");
4807 QualType ReturnType;
4808 UnresolvedSet<4> NonTemplateOverloads;
4809 S.isExprCallable(*E, ReturnType, NonTemplateOverloads);
4810 if (!ReturnType.isNull()
4811 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
4812 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
4813 << FixItHint::CreateInsertion(
4814 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu26b45d82011-12-06 04:48:01 +00004815 return;
4816 }
Lang Hamese14ca9f2011-12-05 20:49:50 +00004817 }
4818 }
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004819 }
John McCall51313c32010-01-04 23:31:57 +00004820
4821 // Strip vector types.
4822 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004823 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004824 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004825 return;
John McCallb4eb64d2010-10-08 02:01:28 +00004826 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004827 }
Chris Lattnerb792b302011-06-14 04:51:15 +00004828
4829 // If the vector cast is cast between two vectors of the same size, it is
4830 // a bitcast, not a conversion.
4831 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
4832 return;
John McCall51313c32010-01-04 23:31:57 +00004833
4834 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
4835 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
4836 }
4837
4838 // Strip complex types.
4839 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004840 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004841 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004842 return;
4843
John McCallb4eb64d2010-10-08 02:01:28 +00004844 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004845 }
John McCall51313c32010-01-04 23:31:57 +00004846
4847 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
4848 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
4849 }
4850
4851 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
4852 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
4853
4854 // If the source is floating point...
4855 if (SourceBT && SourceBT->isFloatingPoint()) {
4856 // ...and the target is floating point...
4857 if (TargetBT && TargetBT->isFloatingPoint()) {
4858 // ...then warn if we're dropping FP rank.
4859
4860 // Builtin FP kinds are ordered by increasing FP rank.
4861 if (SourceBT->getKind() > TargetBT->getKind()) {
4862 // Don't warn about float constants that are precisely
4863 // representable in the target type.
4864 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00004865 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00004866 // Value might be a float, a float vector, or a float complex.
4867 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00004868 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
4869 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00004870 return;
4871 }
4872
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004873 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004874 return;
4875
John McCallb4eb64d2010-10-08 02:01:28 +00004876 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00004877 }
4878 return;
4879 }
4880
Ted Kremenekef9ff882011-03-10 20:03:42 +00004881 // If the target is integral, always warn.
David Blaikiebe0ee872012-05-15 16:56:36 +00004882 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004883 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004884 return;
4885
Chandler Carrutha5b93322011-02-17 11:05:49 +00004886 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay634c8af2011-09-08 22:30:47 +00004887 // We also want to warn on, e.g., "int i = -1.234"
4888 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
4889 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
4890 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
4891
Chandler Carruthf65076e2011-04-10 08:36:24 +00004892 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
4893 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00004894 } else {
4895 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
4896 }
4897 }
John McCall51313c32010-01-04 23:31:57 +00004898
Hans Wennborg88617a22012-08-28 15:44:30 +00004899 // If the target is bool, warn if expr is a function or method call.
4900 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
4901 isa<CallExpr>(E)) {
4902 // Check last argument of function call to see if it is an
4903 // implicit cast from a type matching the type the result
4904 // is being cast to.
4905 CallExpr *CEx = cast<CallExpr>(E);
4906 unsigned NumArgs = CEx->getNumArgs();
4907 if (NumArgs > 0) {
4908 Expr *LastA = CEx->getArg(NumArgs - 1);
4909 Expr *InnerE = LastA->IgnoreParenImpCasts();
4910 const Type *InnerType =
4911 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
4912 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
4913 // Warn on this floating-point to bool conversion
4914 DiagnoseImpCast(S, E, T, CC,
4915 diag::warn_impcast_floating_point_to_bool);
4916 }
4917 }
4918 }
John McCall51313c32010-01-04 23:31:57 +00004919 return;
4920 }
4921
Richard Trieu1838ca52011-05-29 19:59:02 +00004922 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
David Blaikieb26331b2012-06-19 21:19:06 +00004923 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
David Blaikiee81b43b2012-11-08 00:41:20 +00004924 && !Target->isBlockPointerType() && !Target->isMemberPointerType()
4925 && Target->isScalarType()) {
David Blaikieb1360492012-03-16 20:30:12 +00004926 SourceLocation Loc = E->getSourceRange().getBegin();
4927 if (Loc.isMacroID())
4928 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
David Blaikie9fb1ac52012-05-15 21:57:38 +00004929 if (!Loc.isMacroID() || CC.isMacroID())
4930 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
4931 << T << clang::SourceRange(CC)
4932 << FixItHint::CreateReplacement(Loc, S.getFixItZeroLiteralForType(T));
Richard Trieu1838ca52011-05-29 19:59:02 +00004933 }
4934
David Blaikieb26331b2012-06-19 21:19:06 +00004935 if (!Source->isIntegerType() || !Target->isIntegerType())
4936 return;
4937
David Blaikiebe0ee872012-05-15 16:56:36 +00004938 // TODO: remove this early return once the false positives for constant->bool
4939 // in templates, macros, etc, are reduced or removed.
4940 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
4941 return;
4942
John McCall323ed742010-05-06 08:58:33 +00004943 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00004944 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00004945
4946 if (SourceRange.Width > TargetRange.Width) {
John McCall091f23f2010-11-09 22:22:12 +00004947 // If the source is a constant, use a default-on diagnostic.
4948 // TODO: this should happen for bitfield stores, too.
4949 llvm::APSInt Value(32);
4950 if (E->isIntegerConstantExpr(Value, S.Context)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004951 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004952 return;
4953
John McCall091f23f2010-11-09 22:22:12 +00004954 std::string PrettySourceValue = Value.toString(10);
4955 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
4956
Ted Kremenek5e745da2011-10-22 02:37:33 +00004957 S.DiagRuntimeBehavior(E->getExprLoc(), E,
4958 S.PDiag(diag::warn_impcast_integer_precision_constant)
4959 << PrettySourceValue << PrettyTargetValue
4960 << E->getType() << T << E->getSourceRange()
4961 << clang::SourceRange(CC));
John McCall091f23f2010-11-09 22:22:12 +00004962 return;
4963 }
4964
Chris Lattnerb792b302011-06-14 04:51:15 +00004965 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004966 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004967 return;
David Blaikie0c5d0052012-11-19 23:12:51 +00004968
David Blaikie37050842012-04-12 22:40:54 +00004969 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaksc36bedc2012-02-01 19:08:57 +00004970 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
4971 /* pruneControlFlow */ true);
John McCallb4eb64d2010-10-08 02:01:28 +00004972 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00004973 }
4974
4975 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
4976 (!TargetRange.NonNegative && SourceRange.NonNegative &&
4977 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004978
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004979 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004980 return;
4981
John McCall323ed742010-05-06 08:58:33 +00004982 unsigned DiagID = diag::warn_impcast_integer_sign;
4983
4984 // Traditionally, gcc has warned about this under -Wsign-compare.
4985 // We also want to warn about it in -Wconversion.
4986 // So if -Wconversion is off, use a completely identical diagnostic
4987 // in the sign-compare group.
4988 // The conditional-checking code will
4989 if (ICContext) {
4990 DiagID = diag::warn_impcast_integer_sign_conditional;
4991 *ICContext = true;
4992 }
4993
John McCallb4eb64d2010-10-08 02:01:28 +00004994 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00004995 }
4996
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004997 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004998 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
4999 // type, to give us better diagnostics.
5000 QualType SourceType = E->getType();
David Blaikie4e4d0842012-03-11 07:00:24 +00005001 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005002 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5003 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
5004 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
5005 SourceType = S.Context.getTypeDeclType(Enum);
5006 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
5007 }
5008 }
5009
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005010 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
5011 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
5012 if ((SourceEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00005013 SourceEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005014 (TargetEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00005015 TargetEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00005016 SourceEnum != TargetEnum) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005017 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005018 return;
5019
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005020 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005021 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00005022 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005023
John McCall51313c32010-01-04 23:31:57 +00005024 return;
5025}
5026
David Blaikie9fb1ac52012-05-15 21:57:38 +00005027void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5028 SourceLocation CC, QualType T);
John McCall323ed742010-05-06 08:58:33 +00005029
5030void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00005031 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00005032 E = E->IgnoreParenImpCasts();
5033
5034 if (isa<ConditionalOperator>(E))
David Blaikie9fb1ac52012-05-15 21:57:38 +00005035 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCall323ed742010-05-06 08:58:33 +00005036
John McCallb4eb64d2010-10-08 02:01:28 +00005037 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005038 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00005039 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00005040 return;
5041}
5042
David Blaikie9fb1ac52012-05-15 21:57:38 +00005043void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5044 SourceLocation CC, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00005045 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00005046
5047 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00005048 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
5049 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00005050
5051 // If -Wconversion would have warned about either of the candidates
5052 // for a signedness conversion to the context type...
5053 if (!Suspicious) return;
5054
5055 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00005056 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
5057 CC))
John McCall323ed742010-05-06 08:58:33 +00005058 return;
5059
John McCall323ed742010-05-06 08:58:33 +00005060 // ...then check whether it would have warned about either of the
5061 // candidates for a signedness conversion to the condition type.
Richard Trieu52541612011-07-21 02:46:28 +00005062 if (E->getType() == T) return;
5063
5064 Suspicious = false;
5065 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
5066 E->getType(), CC, &Suspicious);
5067 if (!Suspicious)
5068 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00005069 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00005070}
5071
5072/// AnalyzeImplicitConversions - Find and report any interesting
5073/// implicit conversions in the given expression. There are a couple
5074/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00005075void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00005076 QualType T = OrigE->getType();
5077 Expr *E = OrigE->IgnoreParenImpCasts();
5078
Douglas Gregorf8b6e152011-10-10 17:38:18 +00005079 if (E->isTypeDependent() || E->isValueDependent())
5080 return;
5081
John McCall323ed742010-05-06 08:58:33 +00005082 // For conditional operators, we analyze the arguments as if they
5083 // were being fed directly into the output.
5084 if (isa<ConditionalOperator>(E)) {
5085 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie9fb1ac52012-05-15 21:57:38 +00005086 CheckConditionalOperator(S, CO, CC, T);
John McCall323ed742010-05-06 08:58:33 +00005087 return;
5088 }
5089
Hans Wennborg88617a22012-08-28 15:44:30 +00005090 // Check implicit argument conversions for function calls.
5091 if (CallExpr *Call = dyn_cast<CallExpr>(E))
5092 CheckImplicitArgumentConversions(S, Call, CC);
5093
John McCall323ed742010-05-06 08:58:33 +00005094 // Go ahead and check any implicit conversions we might have skipped.
5095 // The non-canonical typecheck is just an optimization;
5096 // CheckImplicitConversion will filter out dead implicit conversions.
5097 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00005098 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00005099
5100 // Now continue drilling into this expression.
5101
5102 // Skip past explicit casts.
5103 if (isa<ExplicitCastExpr>(E)) {
5104 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00005105 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005106 }
5107
John McCallbeb22aa2010-11-09 23:24:47 +00005108 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5109 // Do a somewhat different check with comparison operators.
5110 if (BO->isComparisonOp())
5111 return AnalyzeComparison(S, BO);
5112
Eli Friedman0fa06382012-01-26 23:34:06 +00005113 // And with simple assignments.
5114 if (BO->getOpcode() == BO_Assign)
John McCallbeb22aa2010-11-09 23:24:47 +00005115 return AnalyzeAssignment(S, BO);
5116 }
John McCall323ed742010-05-06 08:58:33 +00005117
5118 // These break the otherwise-useful invariant below. Fortunately,
5119 // we don't really need to recurse into them, because any internal
5120 // expressions should have been analyzed already when they were
5121 // built into statements.
5122 if (isa<StmtExpr>(E)) return;
5123
5124 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005125 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00005126
5127 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00005128 CC = E->getExprLoc();
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005129 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
5130 bool IsLogicalOperator = BO && BO->isLogicalOp();
5131 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor54042f12012-02-09 10:18:50 +00005132 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor503384f2012-02-09 00:47:04 +00005133 if (!ChildExpr)
5134 continue;
5135
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005136 if (IsLogicalOperator &&
5137 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
5138 // Ignore checking string literals that are in logical operators.
5139 continue;
5140 AnalyzeImplicitConversions(S, ChildExpr, CC);
5141 }
John McCall323ed742010-05-06 08:58:33 +00005142}
5143
5144} // end anonymous namespace
5145
5146/// Diagnoses "dangerous" implicit conversions within the given
5147/// expression (which is a full expression). Implements -Wconversion
5148/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00005149///
5150/// \param CC the "context" location of the implicit conversion, i.e.
5151/// the most location of the syntactic entity requiring the implicit
5152/// conversion
5153void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00005154 // Don't diagnose in unevaluated contexts.
David Blaikie71f55f72012-08-06 22:47:24 +00005155 if (isUnevaluatedContext())
John McCall323ed742010-05-06 08:58:33 +00005156 return;
5157
5158 // Don't diagnose for value- or type-dependent expressions.
5159 if (E->isTypeDependent() || E->isValueDependent())
5160 return;
5161
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005162 // Check for array bounds violations in cases where the check isn't triggered
5163 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
5164 // ArraySubscriptExpr is on the RHS of a variable initialization.
5165 CheckArrayAccess(E);
5166
John McCallb4eb64d2010-10-08 02:01:28 +00005167 // This is not the right CC for (e.g.) a variable initialization.
5168 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005169}
5170
John McCall15d7d122010-11-11 03:21:53 +00005171void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
5172 FieldDecl *BitField,
5173 Expr *Init) {
5174 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
5175}
5176
Mike Stumpf8c49212010-01-21 03:59:47 +00005177/// CheckParmsForFunctionDef - Check that the parameters of the given
5178/// function are appropriate for the definition of a function. This
5179/// takes care of any checks that cannot be performed on the
5180/// declaration itself, e.g., that the types of each of the function
5181/// parameters are complete.
Douglas Gregor82aa7132010-11-01 18:37:59 +00005182bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
5183 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00005184 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00005185 for (; P != PEnd; ++P) {
5186 ParmVarDecl *Param = *P;
5187
Mike Stumpf8c49212010-01-21 03:59:47 +00005188 // C99 6.7.5.3p4: the parameters in a parameter type list in a
5189 // function declarator that is part of a function definition of
5190 // that function shall not have incomplete type.
5191 //
5192 // This is also C++ [dcl.fct]p6.
5193 if (!Param->isInvalidDecl() &&
5194 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00005195 diag::err_typecheck_decl_incomplete_type)) {
Mike Stumpf8c49212010-01-21 03:59:47 +00005196 Param->setInvalidDecl();
5197 HasInvalidParm = true;
5198 }
5199
5200 // C99 6.9.1p5: If the declarator includes a parameter type list, the
5201 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00005202 if (CheckParameterNames &&
5203 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00005204 !Param->isImplicit() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00005205 !getLangOpts().CPlusPlus)
Mike Stumpf8c49212010-01-21 03:59:47 +00005206 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00005207
5208 // C99 6.7.5.3p12:
5209 // If the function declarator is not part of a definition of that
5210 // function, parameters may have incomplete type and may use the [*]
5211 // notation in their sequences of declarator specifiers to specify
5212 // variable length array types.
5213 QualType PType = Param->getOriginalType();
5214 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
5215 if (AT->getSizeModifier() == ArrayType::Star) {
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00005216 // FIXME: This diagnosic should point the '[*]' if source-location
Sam Weinigd17e3402010-02-01 05:02:49 +00005217 // information is added for it.
5218 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
5219 }
5220 }
Mike Stumpf8c49212010-01-21 03:59:47 +00005221 }
5222
5223 return HasInvalidParm;
5224}
John McCallb7f4ffe2010-08-12 21:44:57 +00005225
5226/// CheckCastAlign - Implements -Wcast-align, which warns when a
5227/// pointer cast increases the alignment requirements.
5228void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
5229 // This is actually a lot of work to potentially be doing on every
5230 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00005231 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
5232 TRange.getBegin())
David Blaikied6471f72011-09-25 23:23:43 +00005233 == DiagnosticsEngine::Ignored)
John McCallb7f4ffe2010-08-12 21:44:57 +00005234 return;
5235
5236 // Ignore dependent types.
5237 if (T->isDependentType() || Op->getType()->isDependentType())
5238 return;
5239
5240 // Require that the destination be a pointer type.
5241 const PointerType *DestPtr = T->getAs<PointerType>();
5242 if (!DestPtr) return;
5243
5244 // If the destination has alignment 1, we're done.
5245 QualType DestPointee = DestPtr->getPointeeType();
5246 if (DestPointee->isIncompleteType()) return;
5247 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
5248 if (DestAlign.isOne()) return;
5249
5250 // Require that the source be a pointer type.
5251 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
5252 if (!SrcPtr) return;
5253 QualType SrcPointee = SrcPtr->getPointeeType();
5254
5255 // Whitelist casts from cv void*. We already implicitly
5256 // whitelisted casts to cv void*, since they have alignment 1.
5257 // Also whitelist casts involving incomplete types, which implicitly
5258 // includes 'void'.
5259 if (SrcPointee->isIncompleteType()) return;
5260
5261 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
5262 if (SrcAlign >= DestAlign) return;
5263
5264 Diag(TRange.getBegin(), diag::warn_cast_align)
5265 << Op->getType() << T
5266 << static_cast<unsigned>(SrcAlign.getQuantity())
5267 << static_cast<unsigned>(DestAlign.getQuantity())
5268 << TRange << Op->getSourceRange();
5269}
5270
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005271static const Type* getElementType(const Expr *BaseExpr) {
5272 const Type* EltType = BaseExpr->getType().getTypePtr();
5273 if (EltType->isAnyPointerType())
5274 return EltType->getPointeeType().getTypePtr();
5275 else if (EltType->isArrayType())
5276 return EltType->getBaseElementTypeUnsafe();
5277 return EltType;
5278}
5279
Chandler Carruthc2684342011-08-05 09:10:50 +00005280/// \brief Check whether this array fits the idiom of a size-one tail padded
5281/// array member of a struct.
5282///
5283/// We avoid emitting out-of-bounds access warnings for such arrays as they are
5284/// commonly used to emulate flexible arrays in C89 code.
5285static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
5286 const NamedDecl *ND) {
5287 if (Size != 1 || !ND) return false;
5288
5289 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
5290 if (!FD) return false;
5291
5292 // Don't consider sizes resulting from macro expansions or template argument
5293 // substitution to form C89 tail-padded arrays.
Sean Callanand2cf3482012-05-04 18:22:53 +00005294
5295 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00005296 while (TInfo) {
5297 TypeLoc TL = TInfo->getTypeLoc();
5298 // Look through typedefs.
5299 const TypedefTypeLoc *TTL = dyn_cast<TypedefTypeLoc>(&TL);
5300 if (TTL) {
5301 const TypedefNameDecl *TDL = TTL->getTypedefNameDecl();
5302 TInfo = TDL->getTypeSourceInfo();
5303 continue;
5304 }
5305 ConstantArrayTypeLoc CTL = cast<ConstantArrayTypeLoc>(TL);
5306 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Sean Callanand2cf3482012-05-04 18:22:53 +00005307 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
5308 return false;
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00005309 break;
Sean Callanand2cf3482012-05-04 18:22:53 +00005310 }
Chandler Carruthc2684342011-08-05 09:10:50 +00005311
5312 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gay381711c2011-11-29 22:43:53 +00005313 if (!RD) return false;
5314 if (RD->isUnion()) return false;
5315 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
5316 if (!CRD->isStandardLayout()) return false;
5317 }
Chandler Carruthc2684342011-08-05 09:10:50 +00005318
Benjamin Kramer22d4fed2011-08-06 03:04:42 +00005319 // See if this is the last field decl in the record.
5320 const Decl *D = FD;
5321 while ((D = D->getNextDeclInContext()))
5322 if (isa<FieldDecl>(D))
5323 return false;
5324 return true;
Chandler Carruthc2684342011-08-05 09:10:50 +00005325}
5326
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005327void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005328 const ArraySubscriptExpr *ASE,
Richard Smith25b009a2011-12-16 19:31:14 +00005329 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman92b670e2012-02-27 21:21:40 +00005330 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005331 if (IndexExpr->isValueDependent())
5332 return;
5333
Matt Beaumont-Gay8ef8f432011-12-12 22:35:02 +00005334 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005335 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00005336 const ConstantArrayType *ArrayTy =
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005337 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00005338 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00005339 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00005340
Chandler Carruth34064582011-02-17 20:55:08 +00005341 llvm::APSInt index;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005342 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00005343 return;
Richard Smith25b009a2011-12-16 19:31:14 +00005344 if (IndexNegated)
5345 index = -index;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00005346
Chandler Carruthba447122011-08-05 08:07:29 +00005347 const NamedDecl *ND = NULL;
Chandler Carruthba447122011-08-05 08:07:29 +00005348 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
5349 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruthc2684342011-08-05 09:10:50 +00005350 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruthba447122011-08-05 08:07:29 +00005351 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruthba447122011-08-05 08:07:29 +00005352
Ted Kremenek9e060ca2011-02-23 23:06:04 +00005353 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00005354 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00005355 if (!size.isStrictlyPositive())
5356 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005357
5358 const Type* BaseType = getElementType(BaseExpr);
Nico Weberde5998f2011-09-17 22:59:41 +00005359 if (BaseType != EffectiveType) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005360 // Make sure we're comparing apples to apples when comparing index to size
5361 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
5362 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhraind10f4bc2011-08-10 19:47:25 +00005363 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhrain18f16972011-08-10 18:49:28 +00005364 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005365 if (ptrarith_typesize != array_typesize) {
5366 // There's a cast to a different size type involved
5367 uint64_t ratio = array_typesize / ptrarith_typesize;
5368 // TODO: Be smarter about handling cases where array_typesize is not a
5369 // multiple of ptrarith_typesize
5370 if (ptrarith_typesize * ratio == array_typesize)
5371 size *= llvm::APInt(size.getBitWidth(), ratio);
5372 }
5373 }
5374
Chandler Carruth34064582011-02-17 20:55:08 +00005375 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00005376 index = index.zext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00005377 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00005378 size = size.zext(index.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00005379
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005380 // For array subscripting the index must be less than size, but for pointer
5381 // arithmetic also allow the index (offset) to be equal to size since
5382 // computing the next address after the end of the array is legal and
5383 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman92b670e2012-02-27 21:21:40 +00005384 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruthba447122011-08-05 08:07:29 +00005385 return;
5386
5387 // Also don't warn for arrays of size 1 which are members of some
5388 // structure. These are often used to approximate flexible arrays in C89
5389 // code.
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005390 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00005391 return;
Chandler Carruth34064582011-02-17 20:55:08 +00005392
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005393 // Suppress the warning if the subscript expression (as identified by the
5394 // ']' location) and the index expression are both from macro expansions
5395 // within a system header.
5396 if (ASE) {
5397 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
5398 ASE->getRBracketLoc());
5399 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
5400 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
5401 IndexExpr->getLocStart());
5402 if (SourceMgr.isFromSameFile(RBracketLoc, IndexLoc))
5403 return;
5404 }
5405 }
5406
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005407 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005408 if (ASE)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005409 DiagID = diag::warn_array_index_exceeds_bounds;
5410
5411 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
5412 PDiag(DiagID) << index.toString(10, true)
5413 << size.toString(10, true)
5414 << (unsigned)size.getLimitedValue(~0U)
5415 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00005416 } else {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005417 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005418 if (!ASE) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005419 DiagID = diag::warn_ptr_arith_precedes_bounds;
5420 if (index.isNegative()) index = -index;
5421 }
5422
5423 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
5424 PDiag(DiagID) << index.toString(10, true)
5425 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00005426 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00005427
Matt Beaumont-Gaycfbc5b52011-11-29 19:27:11 +00005428 if (!ND) {
5429 // Try harder to find a NamedDecl to point at in the note.
5430 while (const ArraySubscriptExpr *ASE =
5431 dyn_cast<ArraySubscriptExpr>(BaseExpr))
5432 BaseExpr = ASE->getBase()->IgnoreParenCasts();
5433 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
5434 ND = dyn_cast<NamedDecl>(DRE->getDecl());
5435 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
5436 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
5437 }
5438
Chandler Carruth35001ca2011-02-17 21:10:52 +00005439 if (ND)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005440 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
5441 PDiag(diag::note_array_index_out_of_bounds)
5442 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00005443}
5444
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005445void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005446 int AllowOnePastEnd = 0;
5447 while (expr) {
5448 expr = expr->IgnoreParenImpCasts();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005449 switch (expr->getStmtClass()) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005450 case Stmt::ArraySubscriptExprClass: {
5451 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005452 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005453 AllowOnePastEnd > 0);
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005454 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005455 }
5456 case Stmt::UnaryOperatorClass: {
5457 // Only unwrap the * and & unary operators
5458 const UnaryOperator *UO = cast<UnaryOperator>(expr);
5459 expr = UO->getSubExpr();
5460 switch (UO->getOpcode()) {
5461 case UO_AddrOf:
5462 AllowOnePastEnd++;
5463 break;
5464 case UO_Deref:
5465 AllowOnePastEnd--;
5466 break;
5467 default:
5468 return;
5469 }
5470 break;
5471 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005472 case Stmt::ConditionalOperatorClass: {
5473 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
5474 if (const Expr *lhs = cond->getLHS())
5475 CheckArrayAccess(lhs);
5476 if (const Expr *rhs = cond->getRHS())
5477 CheckArrayAccess(rhs);
5478 return;
5479 }
5480 default:
5481 return;
5482 }
Peter Collingbournef111d932011-04-15 00:35:48 +00005483 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005484}
John McCallf85e1932011-06-15 23:02:42 +00005485
5486//===--- CHECK: Objective-C retain cycles ----------------------------------//
5487
5488namespace {
5489 struct RetainCycleOwner {
5490 RetainCycleOwner() : Variable(0), Indirect(false) {}
5491 VarDecl *Variable;
5492 SourceRange Range;
5493 SourceLocation Loc;
5494 bool Indirect;
5495
5496 void setLocsFrom(Expr *e) {
5497 Loc = e->getExprLoc();
5498 Range = e->getSourceRange();
5499 }
5500 };
5501}
5502
5503/// Consider whether capturing the given variable can possibly lead to
5504/// a retain cycle.
5505static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledruf3477c12012-09-27 10:16:10 +00005506 // In ARC, it's captured strongly iff the variable has __strong
John McCallf85e1932011-06-15 23:02:42 +00005507 // lifetime. In MRR, it's captured strongly if the variable is
5508 // __block and has an appropriate type.
5509 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
5510 return false;
5511
5512 owner.Variable = var;
Jordan Rosee10f4d32012-09-15 02:48:31 +00005513 if (ref)
5514 owner.setLocsFrom(ref);
John McCallf85e1932011-06-15 23:02:42 +00005515 return true;
5516}
5517
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00005518static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCallf85e1932011-06-15 23:02:42 +00005519 while (true) {
5520 e = e->IgnoreParens();
5521 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
5522 switch (cast->getCastKind()) {
5523 case CK_BitCast:
5524 case CK_LValueBitCast:
5525 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00005526 case CK_ARCReclaimReturnedObject:
John McCallf85e1932011-06-15 23:02:42 +00005527 e = cast->getSubExpr();
5528 continue;
5529
John McCallf85e1932011-06-15 23:02:42 +00005530 default:
5531 return false;
5532 }
5533 }
5534
5535 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
5536 ObjCIvarDecl *ivar = ref->getDecl();
5537 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
5538 return false;
5539
5540 // Try to find a retain cycle in the base.
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00005541 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCallf85e1932011-06-15 23:02:42 +00005542 return false;
5543
5544 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
5545 owner.Indirect = true;
5546 return true;
5547 }
5548
5549 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
5550 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
5551 if (!var) return false;
5552 return considerVariable(var, ref, owner);
5553 }
5554
John McCallf85e1932011-06-15 23:02:42 +00005555 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
5556 if (member->isArrow()) return false;
5557
5558 // Don't count this as an indirect ownership.
5559 e = member->getBase();
5560 continue;
5561 }
5562
John McCall4b9c2d22011-11-06 09:01:30 +00005563 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
5564 // Only pay attention to pseudo-objects on property references.
5565 ObjCPropertyRefExpr *pre
5566 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
5567 ->IgnoreParens());
5568 if (!pre) return false;
5569 if (pre->isImplicitProperty()) return false;
5570 ObjCPropertyDecl *property = pre->getExplicitProperty();
5571 if (!property->isRetaining() &&
5572 !(property->getPropertyIvarDecl() &&
5573 property->getPropertyIvarDecl()->getType()
5574 .getObjCLifetime() == Qualifiers::OCL_Strong))
5575 return false;
5576
5577 owner.Indirect = true;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00005578 if (pre->isSuperReceiver()) {
5579 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
5580 if (!owner.Variable)
5581 return false;
5582 owner.Loc = pre->getLocation();
5583 owner.Range = pre->getSourceRange();
5584 return true;
5585 }
John McCall4b9c2d22011-11-06 09:01:30 +00005586 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
5587 ->getSourceExpr());
5588 continue;
5589 }
5590
John McCallf85e1932011-06-15 23:02:42 +00005591 // Array ivars?
5592
5593 return false;
5594 }
5595}
5596
5597namespace {
5598 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
5599 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
5600 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
5601 Variable(variable), Capturer(0) {}
5602
5603 VarDecl *Variable;
5604 Expr *Capturer;
5605
5606 void VisitDeclRefExpr(DeclRefExpr *ref) {
5607 if (ref->getDecl() == Variable && !Capturer)
5608 Capturer = ref;
5609 }
5610
John McCallf85e1932011-06-15 23:02:42 +00005611 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
5612 if (Capturer) return;
5613 Visit(ref->getBase());
5614 if (Capturer && ref->isFreeIvar())
5615 Capturer = ref;
5616 }
5617
5618 void VisitBlockExpr(BlockExpr *block) {
5619 // Look inside nested blocks
5620 if (block->getBlockDecl()->capturesVariable(Variable))
5621 Visit(block->getBlockDecl()->getBody());
5622 }
Fariborz Jahanian7e2e4c32012-08-31 20:04:47 +00005623
5624 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
5625 if (Capturer) return;
5626 if (OVE->getSourceExpr())
5627 Visit(OVE->getSourceExpr());
5628 }
John McCallf85e1932011-06-15 23:02:42 +00005629 };
5630}
5631
5632/// Check whether the given argument is a block which captures a
5633/// variable.
5634static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
5635 assert(owner.Variable && owner.Loc.isValid());
5636
5637 e = e->IgnoreParenCasts();
Jordan Rose1fac58a2012-09-17 17:54:30 +00005638
5639 // Look through [^{...} copy] and Block_copy(^{...}).
5640 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
5641 Selector Cmd = ME->getSelector();
5642 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
5643 e = ME->getInstanceReceiver();
5644 if (!e)
5645 return 0;
5646 e = e->IgnoreParenCasts();
5647 }
5648 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
5649 if (CE->getNumArgs() == 1) {
5650 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekd13eff62012-10-02 04:36:54 +00005651 if (Fn) {
5652 const IdentifierInfo *FnI = Fn->getIdentifier();
5653 if (FnI && FnI->isStr("_Block_copy")) {
5654 e = CE->getArg(0)->IgnoreParenCasts();
5655 }
5656 }
Jordan Rose1fac58a2012-09-17 17:54:30 +00005657 }
5658 }
5659
John McCallf85e1932011-06-15 23:02:42 +00005660 BlockExpr *block = dyn_cast<BlockExpr>(e);
5661 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
5662 return 0;
5663
5664 FindCaptureVisitor visitor(S.Context, owner.Variable);
5665 visitor.Visit(block->getBlockDecl()->getBody());
5666 return visitor.Capturer;
5667}
5668
5669static void diagnoseRetainCycle(Sema &S, Expr *capturer,
5670 RetainCycleOwner &owner) {
5671 assert(capturer);
5672 assert(owner.Variable && owner.Loc.isValid());
5673
5674 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
5675 << owner.Variable << capturer->getSourceRange();
5676 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
5677 << owner.Indirect << owner.Range;
5678}
5679
5680/// Check for a keyword selector that starts with the word 'add' or
5681/// 'set'.
5682static bool isSetterLikeSelector(Selector sel) {
5683 if (sel.isUnarySelector()) return false;
5684
Chris Lattner5f9e2722011-07-23 10:55:15 +00005685 StringRef str = sel.getNameForSlot(0);
John McCallf85e1932011-06-15 23:02:42 +00005686 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00005687 if (str.startswith("set"))
John McCallf85e1932011-06-15 23:02:42 +00005688 str = str.substr(3);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00005689 else if (str.startswith("add")) {
5690 // Specially whitelist 'addOperationWithBlock:'.
5691 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
5692 return false;
5693 str = str.substr(3);
5694 }
John McCallf85e1932011-06-15 23:02:42 +00005695 else
5696 return false;
5697
5698 if (str.empty()) return true;
5699 return !islower(str.front());
5700}
5701
5702/// Check a message send to see if it's likely to cause a retain cycle.
5703void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
5704 // Only check instance methods whose selector looks like a setter.
5705 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
5706 return;
5707
5708 // Try to find a variable that the receiver is strongly owned by.
5709 RetainCycleOwner owner;
5710 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00005711 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCallf85e1932011-06-15 23:02:42 +00005712 return;
5713 } else {
5714 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
5715 owner.Variable = getCurMethodDecl()->getSelfDecl();
5716 owner.Loc = msg->getSuperLoc();
5717 owner.Range = msg->getSuperLoc();
5718 }
5719
5720 // Check whether the receiver is captured by any of the arguments.
5721 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
5722 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
5723 return diagnoseRetainCycle(*this, capturer, owner);
5724}
5725
5726/// Check a property assign to see if it's likely to cause a retain cycle.
5727void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
5728 RetainCycleOwner owner;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00005729 if (!findRetainCycleOwner(*this, receiver, owner))
John McCallf85e1932011-06-15 23:02:42 +00005730 return;
5731
5732 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
5733 diagnoseRetainCycle(*this, capturer, owner);
5734}
5735
Jordan Rosee10f4d32012-09-15 02:48:31 +00005736void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
5737 RetainCycleOwner Owner;
5738 if (!considerVariable(Var, /*DeclRefExpr=*/0, Owner))
5739 return;
5740
5741 // Because we don't have an expression for the variable, we have to set the
5742 // location explicitly here.
5743 Owner.Loc = Var->getLocation();
5744 Owner.Range = Var->getSourceRange();
5745
5746 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
5747 diagnoseRetainCycle(*this, Capturer, Owner);
5748}
5749
Ted Kremenekb1ea5102012-12-21 08:04:20 +00005750static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
5751 Qualifiers::ObjCLifetime LT,
5752 Expr *RHS, bool isProperty) {
5753 // Strip off any implicit cast added to get to the one ARC-specific.
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005754 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00005755 if (cast->getCastKind() == CK_ARCConsumeObject) {
Ted Kremenekb1ea5102012-12-21 08:04:20 +00005756 S.Diag(Loc, diag::warn_arc_retained_assign)
5757 << (LT == Qualifiers::OCL_ExplicitNone)
5758 << (isProperty ? 0 : 1)
John McCallf85e1932011-06-15 23:02:42 +00005759 << RHS->getSourceRange();
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005760 return true;
5761 }
5762 RHS = cast->getSubExpr();
5763 }
5764 return false;
John McCallf85e1932011-06-15 23:02:42 +00005765}
5766
Ted Kremenek9d084012012-12-21 08:04:28 +00005767static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
5768 Expr *RHS, bool isProperty) {
5769 // Check if RHS is an Objective-C object literal, which also can get
5770 // immediately zapped in a weak reference. Note that we explicitly
5771 // allow ObjCStringLiterals, since those are designed to never really die.
5772 RHS = RHS->IgnoreParenImpCasts();
5773 unsigned kind = 4;
5774 switch (RHS->getStmtClass()) {
5775 default:
5776 break;
5777 case Stmt::ObjCDictionaryLiteralClass:
5778 kind = 0;
5779 break;
5780 case Stmt::ObjCArrayLiteralClass:
5781 kind = 1;
5782 break;
5783 case Stmt::BlockExprClass:
5784 kind = 2;
5785 break;
5786 case Stmt::ObjCBoxedExprClass:
5787 kind = 3;
5788 break;
5789 }
5790 if (kind < 4) {
5791 S.Diag(Loc, diag::warn_arc_literal_assign)
5792 << kind
5793 << (isProperty ? 0 : 1)
5794 << RHS->getSourceRange();
5795 return true;
5796 }
5797 return false;
5798}
5799
Ted Kremenekb1ea5102012-12-21 08:04:20 +00005800bool Sema::checkUnsafeAssigns(SourceLocation Loc,
5801 QualType LHS, Expr *RHS) {
5802 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
5803
5804 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
5805 return false;
5806
5807 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
5808 return true;
5809
Ted Kremenek9d084012012-12-21 08:04:28 +00005810 if (LT == Qualifiers::OCL_Weak &&
5811 checkUnsafeAssignLiteral(*this, Loc, RHS, false))
5812 return true;
5813
Ted Kremenekb1ea5102012-12-21 08:04:20 +00005814 return false;
5815}
5816
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005817void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
5818 Expr *LHS, Expr *RHS) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00005819 QualType LHSType;
5820 // PropertyRef on LHS type need be directly obtained from
5821 // its declaration as it has a PsuedoType.
5822 ObjCPropertyRefExpr *PRE
5823 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
5824 if (PRE && !PRE->isImplicitProperty()) {
5825 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
5826 if (PD)
5827 LHSType = PD->getType();
5828 }
5829
5830 if (LHSType.isNull())
5831 LHSType = LHS->getType();
Jordan Rose7a270482012-09-28 22:21:35 +00005832
5833 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
5834
5835 if (LT == Qualifiers::OCL_Weak) {
5836 DiagnosticsEngine::Level Level =
5837 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
5838 if (Level != DiagnosticsEngine::Ignored)
5839 getCurFunction()->markSafeWeakUse(LHS);
5840 }
5841
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005842 if (checkUnsafeAssigns(Loc, LHSType, RHS))
5843 return;
Jordan Rose7a270482012-09-28 22:21:35 +00005844
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005845 // FIXME. Check for other life times.
5846 if (LT != Qualifiers::OCL_None)
5847 return;
5848
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00005849 if (PRE) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005850 if (PRE->isImplicitProperty())
5851 return;
5852 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
5853 if (!PD)
5854 return;
5855
Bill Wendlingad017fa2012-12-20 19:22:21 +00005856 unsigned Attributes = PD->getPropertyAttributes();
5857 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00005858 // when 'assign' attribute was not explicitly specified
5859 // by user, ignore it and rely on property type itself
5860 // for lifetime info.
5861 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
5862 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
5863 LHSType->isObjCRetainableType())
5864 return;
5865
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005866 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00005867 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005868 Diag(Loc, diag::warn_arc_retained_property_assign)
5869 << RHS->getSourceRange();
5870 return;
5871 }
5872 RHS = cast->getSubExpr();
5873 }
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00005874 }
Bill Wendlingad017fa2012-12-20 19:22:21 +00005875 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb1ea5102012-12-21 08:04:20 +00005876 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
5877 return;
Ted Kremenek9d084012012-12-21 08:04:28 +00005878 if (checkUnsafeAssignLiteral(*this, Loc, RHS, true))
5879 return;
Fariborz Jahanianbd2e27e2012-07-06 21:09:27 +00005880 }
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005881 }
5882}
Dmitri Gribenko625bb562012-02-14 22:14:32 +00005883
5884//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
5885
5886namespace {
5887bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
5888 SourceLocation StmtLoc,
5889 const NullStmt *Body) {
5890 // Do not warn if the body is a macro that expands to nothing, e.g:
5891 //
5892 // #define CALL(x)
5893 // if (condition)
5894 // CALL(0);
5895 //
5896 if (Body->hasLeadingEmptyMacro())
5897 return false;
5898
5899 // Get line numbers of statement and body.
5900 bool StmtLineInvalid;
5901 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
5902 &StmtLineInvalid);
5903 if (StmtLineInvalid)
5904 return false;
5905
5906 bool BodyLineInvalid;
5907 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
5908 &BodyLineInvalid);
5909 if (BodyLineInvalid)
5910 return false;
5911
5912 // Warn if null statement and body are on the same line.
5913 if (StmtLine != BodyLine)
5914 return false;
5915
5916 return true;
5917}
5918} // Unnamed namespace
5919
5920void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
5921 const Stmt *Body,
5922 unsigned DiagID) {
5923 // Since this is a syntactic check, don't emit diagnostic for template
5924 // instantiations, this just adds noise.
5925 if (CurrentInstantiationScope)
5926 return;
5927
5928 // The body should be a null statement.
5929 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
5930 if (!NBody)
5931 return;
5932
5933 // Do the usual checks.
5934 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
5935 return;
5936
5937 Diag(NBody->getSemiLoc(), DiagID);
5938 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
5939}
5940
5941void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
5942 const Stmt *PossibleBody) {
5943 assert(!CurrentInstantiationScope); // Ensured by caller
5944
5945 SourceLocation StmtLoc;
5946 const Stmt *Body;
5947 unsigned DiagID;
5948 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
5949 StmtLoc = FS->getRParenLoc();
5950 Body = FS->getBody();
5951 DiagID = diag::warn_empty_for_body;
5952 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
5953 StmtLoc = WS->getCond()->getSourceRange().getEnd();
5954 Body = WS->getBody();
5955 DiagID = diag::warn_empty_while_body;
5956 } else
5957 return; // Neither `for' nor `while'.
5958
5959 // The body should be a null statement.
5960 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
5961 if (!NBody)
5962 return;
5963
5964 // Skip expensive checks if diagnostic is disabled.
5965 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
5966 DiagnosticsEngine::Ignored)
5967 return;
5968
5969 // Do the usual checks.
5970 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
5971 return;
5972
5973 // `for(...);' and `while(...);' are popular idioms, so in order to keep
5974 // noise level low, emit diagnostics only if for/while is followed by a
5975 // CompoundStmt, e.g.:
5976 // for (int i = 0; i < n; i++);
5977 // {
5978 // a(i);
5979 // }
5980 // or if for/while is followed by a statement with more indentation
5981 // than for/while itself:
5982 // for (int i = 0; i < n; i++);
5983 // a(i);
5984 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
5985 if (!ProbableTypo) {
5986 bool BodyColInvalid;
5987 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
5988 PossibleBody->getLocStart(),
5989 &BodyColInvalid);
5990 if (BodyColInvalid)
5991 return;
5992
5993 bool StmtColInvalid;
5994 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
5995 S->getLocStart(),
5996 &StmtColInvalid);
5997 if (StmtColInvalid)
5998 return;
5999
6000 if (BodyCol > StmtCol)
6001 ProbableTypo = true;
6002 }
6003
6004 if (ProbableTypo) {
6005 Diag(NBody->getSemiLoc(), DiagID);
6006 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
6007 }
6008}
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00006009
6010//===--- Layout compatibility ----------------------------------------------//
6011
6012namespace {
6013
6014bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
6015
6016/// \brief Check if two enumeration types are layout-compatible.
6017bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
6018 // C++11 [dcl.enum] p8:
6019 // Two enumeration types are layout-compatible if they have the same
6020 // underlying type.
6021 return ED1->isComplete() && ED2->isComplete() &&
6022 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
6023}
6024
6025/// \brief Check if two fields are layout-compatible.
6026bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
6027 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
6028 return false;
6029
6030 if (Field1->isBitField() != Field2->isBitField())
6031 return false;
6032
6033 if (Field1->isBitField()) {
6034 // Make sure that the bit-fields are the same length.
6035 unsigned Bits1 = Field1->getBitWidthValue(C);
6036 unsigned Bits2 = Field2->getBitWidthValue(C);
6037
6038 if (Bits1 != Bits2)
6039 return false;
6040 }
6041
6042 return true;
6043}
6044
6045/// \brief Check if two standard-layout structs are layout-compatible.
6046/// (C++11 [class.mem] p17)
6047bool isLayoutCompatibleStruct(ASTContext &C,
6048 RecordDecl *RD1,
6049 RecordDecl *RD2) {
6050 // If both records are C++ classes, check that base classes match.
6051 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
6052 // If one of records is a CXXRecordDecl we are in C++ mode,
6053 // thus the other one is a CXXRecordDecl, too.
6054 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
6055 // Check number of base classes.
6056 if (D1CXX->getNumBases() != D2CXX->getNumBases())
6057 return false;
6058
6059 // Check the base classes.
6060 for (CXXRecordDecl::base_class_const_iterator
6061 Base1 = D1CXX->bases_begin(),
6062 BaseEnd1 = D1CXX->bases_end(),
6063 Base2 = D2CXX->bases_begin();
6064 Base1 != BaseEnd1;
6065 ++Base1, ++Base2) {
6066 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
6067 return false;
6068 }
6069 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
6070 // If only RD2 is a C++ class, it should have zero base classes.
6071 if (D2CXX->getNumBases() > 0)
6072 return false;
6073 }
6074
6075 // Check the fields.
6076 RecordDecl::field_iterator Field2 = RD2->field_begin(),
6077 Field2End = RD2->field_end(),
6078 Field1 = RD1->field_begin(),
6079 Field1End = RD1->field_end();
6080 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
6081 if (!isLayoutCompatible(C, *Field1, *Field2))
6082 return false;
6083 }
6084 if (Field1 != Field1End || Field2 != Field2End)
6085 return false;
6086
6087 return true;
6088}
6089
6090/// \brief Check if two standard-layout unions are layout-compatible.
6091/// (C++11 [class.mem] p18)
6092bool isLayoutCompatibleUnion(ASTContext &C,
6093 RecordDecl *RD1,
6094 RecordDecl *RD2) {
6095 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
6096 for (RecordDecl::field_iterator Field2 = RD2->field_begin(),
6097 Field2End = RD2->field_end();
6098 Field2 != Field2End; ++Field2) {
6099 UnmatchedFields.insert(*Field2);
6100 }
6101
6102 for (RecordDecl::field_iterator Field1 = RD1->field_begin(),
6103 Field1End = RD1->field_end();
6104 Field1 != Field1End; ++Field1) {
6105 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
6106 I = UnmatchedFields.begin(),
6107 E = UnmatchedFields.end();
6108
6109 for ( ; I != E; ++I) {
6110 if (isLayoutCompatible(C, *Field1, *I)) {
6111 bool Result = UnmatchedFields.erase(*I);
6112 (void) Result;
6113 assert(Result);
6114 break;
6115 }
6116 }
6117 if (I == E)
6118 return false;
6119 }
6120
6121 return UnmatchedFields.empty();
6122}
6123
6124bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
6125 if (RD1->isUnion() != RD2->isUnion())
6126 return false;
6127
6128 if (RD1->isUnion())
6129 return isLayoutCompatibleUnion(C, RD1, RD2);
6130 else
6131 return isLayoutCompatibleStruct(C, RD1, RD2);
6132}
6133
6134/// \brief Check if two types are layout-compatible in C++11 sense.
6135bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
6136 if (T1.isNull() || T2.isNull())
6137 return false;
6138
6139 // C++11 [basic.types] p11:
6140 // If two types T1 and T2 are the same type, then T1 and T2 are
6141 // layout-compatible types.
6142 if (C.hasSameType(T1, T2))
6143 return true;
6144
6145 T1 = T1.getCanonicalType().getUnqualifiedType();
6146 T2 = T2.getCanonicalType().getUnqualifiedType();
6147
6148 const Type::TypeClass TC1 = T1->getTypeClass();
6149 const Type::TypeClass TC2 = T2->getTypeClass();
6150
6151 if (TC1 != TC2)
6152 return false;
6153
6154 if (TC1 == Type::Enum) {
6155 return isLayoutCompatible(C,
6156 cast<EnumType>(T1)->getDecl(),
6157 cast<EnumType>(T2)->getDecl());
6158 } else if (TC1 == Type::Record) {
6159 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
6160 return false;
6161
6162 return isLayoutCompatible(C,
6163 cast<RecordType>(T1)->getDecl(),
6164 cast<RecordType>(T2)->getDecl());
6165 }
6166
6167 return false;
6168}
6169}
6170
6171//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
6172
6173namespace {
6174/// \brief Given a type tag expression find the type tag itself.
6175///
6176/// \param TypeExpr Type tag expression, as it appears in user's code.
6177///
6178/// \param VD Declaration of an identifier that appears in a type tag.
6179///
6180/// \param MagicValue Type tag magic value.
6181bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
6182 const ValueDecl **VD, uint64_t *MagicValue) {
6183 while(true) {
6184 if (!TypeExpr)
6185 return false;
6186
6187 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
6188
6189 switch (TypeExpr->getStmtClass()) {
6190 case Stmt::UnaryOperatorClass: {
6191 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
6192 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
6193 TypeExpr = UO->getSubExpr();
6194 continue;
6195 }
6196 return false;
6197 }
6198
6199 case Stmt::DeclRefExprClass: {
6200 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
6201 *VD = DRE->getDecl();
6202 return true;
6203 }
6204
6205 case Stmt::IntegerLiteralClass: {
6206 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
6207 llvm::APInt MagicValueAPInt = IL->getValue();
6208 if (MagicValueAPInt.getActiveBits() <= 64) {
6209 *MagicValue = MagicValueAPInt.getZExtValue();
6210 return true;
6211 } else
6212 return false;
6213 }
6214
6215 case Stmt::BinaryConditionalOperatorClass:
6216 case Stmt::ConditionalOperatorClass: {
6217 const AbstractConditionalOperator *ACO =
6218 cast<AbstractConditionalOperator>(TypeExpr);
6219 bool Result;
6220 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
6221 if (Result)
6222 TypeExpr = ACO->getTrueExpr();
6223 else
6224 TypeExpr = ACO->getFalseExpr();
6225 continue;
6226 }
6227 return false;
6228 }
6229
6230 case Stmt::BinaryOperatorClass: {
6231 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
6232 if (BO->getOpcode() == BO_Comma) {
6233 TypeExpr = BO->getRHS();
6234 continue;
6235 }
6236 return false;
6237 }
6238
6239 default:
6240 return false;
6241 }
6242 }
6243}
6244
6245/// \brief Retrieve the C type corresponding to type tag TypeExpr.
6246///
6247/// \param TypeExpr Expression that specifies a type tag.
6248///
6249/// \param MagicValues Registered magic values.
6250///
6251/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
6252/// kind.
6253///
6254/// \param TypeInfo Information about the corresponding C type.
6255///
6256/// \returns true if the corresponding C type was found.
6257bool GetMatchingCType(
6258 const IdentifierInfo *ArgumentKind,
6259 const Expr *TypeExpr, const ASTContext &Ctx,
6260 const llvm::DenseMap<Sema::TypeTagMagicValue,
6261 Sema::TypeTagData> *MagicValues,
6262 bool &FoundWrongKind,
6263 Sema::TypeTagData &TypeInfo) {
6264 FoundWrongKind = false;
6265
6266 // Variable declaration that has type_tag_for_datatype attribute.
6267 const ValueDecl *VD = NULL;
6268
6269 uint64_t MagicValue;
6270
6271 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
6272 return false;
6273
6274 if (VD) {
6275 for (specific_attr_iterator<TypeTagForDatatypeAttr>
6276 I = VD->specific_attr_begin<TypeTagForDatatypeAttr>(),
6277 E = VD->specific_attr_end<TypeTagForDatatypeAttr>();
6278 I != E; ++I) {
6279 if (I->getArgumentKind() != ArgumentKind) {
6280 FoundWrongKind = true;
6281 return false;
6282 }
6283 TypeInfo.Type = I->getMatchingCType();
6284 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
6285 TypeInfo.MustBeNull = I->getMustBeNull();
6286 return true;
6287 }
6288 return false;
6289 }
6290
6291 if (!MagicValues)
6292 return false;
6293
6294 llvm::DenseMap<Sema::TypeTagMagicValue,
6295 Sema::TypeTagData>::const_iterator I =
6296 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
6297 if (I == MagicValues->end())
6298 return false;
6299
6300 TypeInfo = I->second;
6301 return true;
6302}
6303} // unnamed namespace
6304
6305void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
6306 uint64_t MagicValue, QualType Type,
6307 bool LayoutCompatible,
6308 bool MustBeNull) {
6309 if (!TypeTagForDatatypeMagicValues)
6310 TypeTagForDatatypeMagicValues.reset(
6311 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
6312
6313 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
6314 (*TypeTagForDatatypeMagicValues)[Magic] =
6315 TypeTagData(Type, LayoutCompatible, MustBeNull);
6316}
6317
6318namespace {
6319bool IsSameCharType(QualType T1, QualType T2) {
6320 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
6321 if (!BT1)
6322 return false;
6323
6324 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
6325 if (!BT2)
6326 return false;
6327
6328 BuiltinType::Kind T1Kind = BT1->getKind();
6329 BuiltinType::Kind T2Kind = BT2->getKind();
6330
6331 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
6332 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
6333 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
6334 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
6335}
6336} // unnamed namespace
6337
6338void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
6339 const Expr * const *ExprArgs) {
6340 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
6341 bool IsPointerAttr = Attr->getIsPointer();
6342
6343 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
6344 bool FoundWrongKind;
6345 TypeTagData TypeInfo;
6346 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
6347 TypeTagForDatatypeMagicValues.get(),
6348 FoundWrongKind, TypeInfo)) {
6349 if (FoundWrongKind)
6350 Diag(TypeTagExpr->getExprLoc(),
6351 diag::warn_type_tag_for_datatype_wrong_kind)
6352 << TypeTagExpr->getSourceRange();
6353 return;
6354 }
6355
6356 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
6357 if (IsPointerAttr) {
6358 // Skip implicit cast of pointer to `void *' (as a function argument).
6359 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5a249802012-11-03 16:07:49 +00006360 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkob57ce4e2012-11-03 22:10:18 +00006361 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00006362 ArgumentExpr = ICE->getSubExpr();
6363 }
6364 QualType ArgumentType = ArgumentExpr->getType();
6365
6366 // Passing a `void*' pointer shouldn't trigger a warning.
6367 if (IsPointerAttr && ArgumentType->isVoidPointerType())
6368 return;
6369
6370 if (TypeInfo.MustBeNull) {
6371 // Type tag with matching void type requires a null pointer.
6372 if (!ArgumentExpr->isNullPointerConstant(Context,
6373 Expr::NPC_ValueDependentIsNotNull)) {
6374 Diag(ArgumentExpr->getExprLoc(),
6375 diag::warn_type_safety_null_pointer_required)
6376 << ArgumentKind->getName()
6377 << ArgumentExpr->getSourceRange()
6378 << TypeTagExpr->getSourceRange();
6379 }
6380 return;
6381 }
6382
6383 QualType RequiredType = TypeInfo.Type;
6384 if (IsPointerAttr)
6385 RequiredType = Context.getPointerType(RequiredType);
6386
6387 bool mismatch = false;
6388 if (!TypeInfo.LayoutCompatible) {
6389 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
6390
6391 // C++11 [basic.fundamental] p1:
6392 // Plain char, signed char, and unsigned char are three distinct types.
6393 //
6394 // But we treat plain `char' as equivalent to `signed char' or `unsigned
6395 // char' depending on the current char signedness mode.
6396 if (mismatch)
6397 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
6398 RequiredType->getPointeeType())) ||
6399 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
6400 mismatch = false;
6401 } else
6402 if (IsPointerAttr)
6403 mismatch = !isLayoutCompatible(Context,
6404 ArgumentType->getPointeeType(),
6405 RequiredType->getPointeeType());
6406 else
6407 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
6408
6409 if (mismatch)
6410 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
6411 << ArgumentType << ArgumentKind->getName()
6412 << TypeInfo.LayoutCompatible << RequiredType
6413 << ArgumentExpr->getSourceRange()
6414 << TypeTagExpr->getSourceRange();
6415}