blob: 729de0d1cd891ce8c4ef44a669cbcbac5da7fec1 [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"
Jordan Rose3f6f51e2013-02-08 22:30:41 +000027#include "clang/Basic/CharInfo.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"
Dmitri Gribenkocb5620c2013-01-30 12:06:08 +000038#include "llvm/Support/ConvertUTF.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000039#include "llvm/Support/raw_ostream.h"
Zhongxing Xua1f3dba2009-05-20 01:55:10 +000040#include <limits>
Chris Lattner59907c42007-08-10 20:18:51 +000041using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000042using namespace sema;
Chris Lattner59907c42007-08-10 20:18:51 +000043
Chris Lattner60800082009-02-18 17:49:48 +000044SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
45 unsigned ByteNo) const {
Chris Lattner08f92e32010-11-17 07:37:15 +000046 return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +000047 PP.getLangOpts(), PP.getTargetInfo());
Chris Lattner60800082009-02-18 17:49:48 +000048}
49
John McCall8e10f3b2011-02-26 05:39:39 +000050/// Checks that a call expression's argument count is the desired number.
51/// This is useful when doing custom type-checking. Returns true on error.
52static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
53 unsigned argCount = call->getNumArgs();
54 if (argCount == desiredArgCount) return false;
55
56 if (argCount < desiredArgCount)
57 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
58 << 0 /*function call*/ << desiredArgCount << argCount
59 << call->getSourceRange();
60
61 // Highlight all the excess arguments.
62 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
63 call->getArg(argCount - 1)->getLocEnd());
64
65 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
66 << 0 /*function call*/ << desiredArgCount << argCount
67 << call->getArg(1)->getSourceRange();
68}
69
Julien Lerougee5939212012-04-28 17:39:16 +000070/// Check that the first argument to __builtin_annotation is an integer
71/// and the second argument is a non-wide string literal.
72static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
73 if (checkArgCount(S, TheCall, 2))
74 return true;
75
76 // First argument should be an integer.
77 Expr *ValArg = TheCall->getArg(0);
78 QualType Ty = ValArg->getType();
79 if (!Ty->isIntegerType()) {
80 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
81 << ValArg->getSourceRange();
Julien Lerouge77f68bb2011-09-09 22:41:49 +000082 return true;
83 }
Julien Lerougee5939212012-04-28 17:39:16 +000084
85 // Second argument should be a constant string.
86 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
87 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
88 if (!Literal || !Literal->isAscii()) {
89 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
90 << StrArg->getSourceRange();
91 return true;
92 }
93
94 TheCall->setType(Ty);
Julien Lerouge77f68bb2011-09-09 22:41:49 +000095 return false;
96}
97
John McCall60d7b3a2010-08-24 06:29:42 +000098ExprResult
Anders Carlssond406bf02009-08-16 01:56:34 +000099Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
John McCall60d7b3a2010-08-24 06:29:42 +0000100 ExprResult TheCallResult(Owned(TheCall));
Douglas Gregor2def4832008-11-17 20:34:05 +0000101
Chris Lattner946928f2010-10-01 23:23:24 +0000102 // Find out if any arguments are required to be integer constant expressions.
103 unsigned ICEArguments = 0;
104 ASTContext::GetBuiltinTypeError Error;
105 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
106 if (Error != ASTContext::GE_None)
107 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
108
109 // If any arguments are required to be ICE's, check and diagnose.
110 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
111 // Skip arguments not required to be ICE's.
112 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
113
114 llvm::APSInt Result;
115 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
116 return true;
117 ICEArguments &= ~(1 << ArgNo);
118 }
119
Anders Carlssond406bf02009-08-16 01:56:34 +0000120 switch (BuiltinID) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000121 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000122 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000123 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000124 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000125 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000126 break;
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000127 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000128 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000129 if (SemaBuiltinVAStart(TheCall))
130 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000131 break;
Chris Lattner1b9a0792007-12-20 00:26:33 +0000132 case Builtin::BI__builtin_isgreater:
133 case Builtin::BI__builtin_isgreaterequal:
134 case Builtin::BI__builtin_isless:
135 case Builtin::BI__builtin_islessequal:
136 case Builtin::BI__builtin_islessgreater:
137 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000138 if (SemaBuiltinUnorderedCompare(TheCall))
139 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000140 break;
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000141 case Builtin::BI__builtin_fpclassify:
142 if (SemaBuiltinFPClassification(TheCall, 6))
143 return ExprError();
144 break;
Eli Friedman9ac6f622009-08-31 20:06:00 +0000145 case Builtin::BI__builtin_isfinite:
146 case Builtin::BI__builtin_isinf:
147 case Builtin::BI__builtin_isinf_sign:
148 case Builtin::BI__builtin_isnan:
149 case Builtin::BI__builtin_isnormal:
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000150 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman9ac6f622009-08-31 20:06:00 +0000151 return ExprError();
152 break;
Eli Friedmand38617c2008-05-14 19:38:39 +0000153 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000154 return SemaBuiltinShuffleVector(TheCall);
155 // TheCall will be freed by the smart pointer here, but that's fine, since
156 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000157 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000158 if (SemaBuiltinPrefetch(TheCall))
159 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000160 break;
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000161 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000162 if (SemaBuiltinObjectSize(TheCall))
163 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000164 break;
Eli Friedmand875fed2009-05-03 04:46:36 +0000165 case Builtin::BI__builtin_longjmp:
166 if (SemaBuiltinLongjmp(TheCall))
167 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000168 break;
John McCall8e10f3b2011-02-26 05:39:39 +0000169
170 case Builtin::BI__builtin_classify_type:
171 if (checkArgCount(*this, TheCall, 1)) return true;
172 TheCall->setType(Context.IntTy);
173 break;
Chris Lattner75c29a02010-10-12 17:47:42 +0000174 case Builtin::BI__builtin_constant_p:
John McCall8e10f3b2011-02-26 05:39:39 +0000175 if (checkArgCount(*this, TheCall, 1)) return true;
176 TheCall->setType(Context.IntTy);
Chris Lattner75c29a02010-10-12 17:47:42 +0000177 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000178 case Builtin::BI__sync_fetch_and_add:
Douglas Gregora9766412011-11-28 16:30:08 +0000179 case Builtin::BI__sync_fetch_and_add_1:
180 case Builtin::BI__sync_fetch_and_add_2:
181 case Builtin::BI__sync_fetch_and_add_4:
182 case Builtin::BI__sync_fetch_and_add_8:
183 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000184 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregora9766412011-11-28 16:30:08 +0000185 case Builtin::BI__sync_fetch_and_sub_1:
186 case Builtin::BI__sync_fetch_and_sub_2:
187 case Builtin::BI__sync_fetch_and_sub_4:
188 case Builtin::BI__sync_fetch_and_sub_8:
189 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000190 case Builtin::BI__sync_fetch_and_or:
Douglas Gregora9766412011-11-28 16:30:08 +0000191 case Builtin::BI__sync_fetch_and_or_1:
192 case Builtin::BI__sync_fetch_and_or_2:
193 case Builtin::BI__sync_fetch_and_or_4:
194 case Builtin::BI__sync_fetch_and_or_8:
195 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000196 case Builtin::BI__sync_fetch_and_and:
Douglas Gregora9766412011-11-28 16:30:08 +0000197 case Builtin::BI__sync_fetch_and_and_1:
198 case Builtin::BI__sync_fetch_and_and_2:
199 case Builtin::BI__sync_fetch_and_and_4:
200 case Builtin::BI__sync_fetch_and_and_8:
201 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000202 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregora9766412011-11-28 16:30:08 +0000203 case Builtin::BI__sync_fetch_and_xor_1:
204 case Builtin::BI__sync_fetch_and_xor_2:
205 case Builtin::BI__sync_fetch_and_xor_4:
206 case Builtin::BI__sync_fetch_and_xor_8:
207 case Builtin::BI__sync_fetch_and_xor_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000208 case Builtin::BI__sync_add_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000209 case Builtin::BI__sync_add_and_fetch_1:
210 case Builtin::BI__sync_add_and_fetch_2:
211 case Builtin::BI__sync_add_and_fetch_4:
212 case Builtin::BI__sync_add_and_fetch_8:
213 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000214 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000215 case Builtin::BI__sync_sub_and_fetch_1:
216 case Builtin::BI__sync_sub_and_fetch_2:
217 case Builtin::BI__sync_sub_and_fetch_4:
218 case Builtin::BI__sync_sub_and_fetch_8:
219 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000220 case Builtin::BI__sync_and_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000221 case Builtin::BI__sync_and_and_fetch_1:
222 case Builtin::BI__sync_and_and_fetch_2:
223 case Builtin::BI__sync_and_and_fetch_4:
224 case Builtin::BI__sync_and_and_fetch_8:
225 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000226 case Builtin::BI__sync_or_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000227 case Builtin::BI__sync_or_and_fetch_1:
228 case Builtin::BI__sync_or_and_fetch_2:
229 case Builtin::BI__sync_or_and_fetch_4:
230 case Builtin::BI__sync_or_and_fetch_8:
231 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000232 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000233 case Builtin::BI__sync_xor_and_fetch_1:
234 case Builtin::BI__sync_xor_and_fetch_2:
235 case Builtin::BI__sync_xor_and_fetch_4:
236 case Builtin::BI__sync_xor_and_fetch_8:
237 case Builtin::BI__sync_xor_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000238 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000239 case Builtin::BI__sync_val_compare_and_swap_1:
240 case Builtin::BI__sync_val_compare_and_swap_2:
241 case Builtin::BI__sync_val_compare_and_swap_4:
242 case Builtin::BI__sync_val_compare_and_swap_8:
243 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000244 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000245 case Builtin::BI__sync_bool_compare_and_swap_1:
246 case Builtin::BI__sync_bool_compare_and_swap_2:
247 case Builtin::BI__sync_bool_compare_and_swap_4:
248 case Builtin::BI__sync_bool_compare_and_swap_8:
249 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000250 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregora9766412011-11-28 16:30:08 +0000251 case Builtin::BI__sync_lock_test_and_set_1:
252 case Builtin::BI__sync_lock_test_and_set_2:
253 case Builtin::BI__sync_lock_test_and_set_4:
254 case Builtin::BI__sync_lock_test_and_set_8:
255 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000256 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +0000257 case Builtin::BI__sync_lock_release_1:
258 case Builtin::BI__sync_lock_release_2:
259 case Builtin::BI__sync_lock_release_4:
260 case Builtin::BI__sync_lock_release_8:
261 case Builtin::BI__sync_lock_release_16:
Chris Lattner23aa9c82011-04-09 03:57:26 +0000262 case Builtin::BI__sync_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000263 case Builtin::BI__sync_swap_1:
264 case Builtin::BI__sync_swap_2:
265 case Builtin::BI__sync_swap_4:
266 case Builtin::BI__sync_swap_8:
267 case Builtin::BI__sync_swap_16:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000268 return SemaBuiltinAtomicOverloaded(TheCallResult);
Richard Smithff34d402012-04-12 05:08:17 +0000269#define BUILTIN(ID, TYPE, ATTRS)
270#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
271 case Builtin::BI##ID: \
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000272 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithff34d402012-04-12 05:08:17 +0000273#include "clang/Basic/Builtins.def"
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000274 case Builtin::BI__builtin_annotation:
Julien Lerougee5939212012-04-28 17:39:16 +0000275 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000276 return ExprError();
277 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000278 }
279
280 // Since the target specific builtins for each arch overlap, only check those
281 // of the arch we are compiling for.
282 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000283 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman26a31422010-06-08 02:47:44 +0000284 case llvm::Triple::arm:
285 case llvm::Triple::thumb:
286 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
287 return ExprError();
288 break;
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000289 case llvm::Triple::mips:
290 case llvm::Triple::mipsel:
291 case llvm::Triple::mips64:
292 case llvm::Triple::mips64el:
293 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
294 return ExprError();
295 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000296 default:
297 break;
298 }
299 }
300
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000301 return TheCallResult;
Nate Begeman26a31422010-06-08 02:47:44 +0000302}
303
Nate Begeman61eecf52010-06-14 05:21:25 +0000304// Get the valid immediate range for the specified NEON type code.
305static unsigned RFT(unsigned t, bool shift = false) {
Bob Wilsonda95f732011-11-08 01:16:11 +0000306 NeonTypeFlags Type(t);
307 int IsQuad = Type.isQuad();
308 switch (Type.getEltType()) {
309 case NeonTypeFlags::Int8:
310 case NeonTypeFlags::Poly8:
311 return shift ? 7 : (8 << IsQuad) - 1;
312 case NeonTypeFlags::Int16:
313 case NeonTypeFlags::Poly16:
314 return shift ? 15 : (4 << IsQuad) - 1;
315 case NeonTypeFlags::Int32:
316 return shift ? 31 : (2 << IsQuad) - 1;
317 case NeonTypeFlags::Int64:
318 return shift ? 63 : (1 << IsQuad) - 1;
319 case NeonTypeFlags::Float16:
320 assert(!shift && "cannot shift float types!");
321 return (4 << IsQuad) - 1;
322 case NeonTypeFlags::Float32:
323 assert(!shift && "cannot shift float types!");
324 return (2 << IsQuad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000325 }
David Blaikie7530c032012-01-17 06:56:22 +0000326 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman61eecf52010-06-14 05:21:25 +0000327}
328
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000329/// getNeonEltType - Return the QualType corresponding to the elements of
330/// the vector type specified by the NeonTypeFlags. This is used to check
331/// the pointer arguments for Neon load/store intrinsics.
332static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context) {
333 switch (Flags.getEltType()) {
334 case NeonTypeFlags::Int8:
335 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
336 case NeonTypeFlags::Int16:
337 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
338 case NeonTypeFlags::Int32:
339 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
340 case NeonTypeFlags::Int64:
341 return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy;
342 case NeonTypeFlags::Poly8:
343 return Context.SignedCharTy;
344 case NeonTypeFlags::Poly16:
345 return Context.ShortTy;
346 case NeonTypeFlags::Float16:
347 return Context.UnsignedShortTy;
348 case NeonTypeFlags::Float32:
349 return Context.FloatTy;
350 }
David Blaikie7530c032012-01-17 06:56:22 +0000351 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000352}
353
Nate Begeman26a31422010-06-08 02:47:44 +0000354bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000355 llvm::APSInt Result;
356
Richard Smithf8ee6bc2012-08-14 01:28:02 +0000357 uint64_t mask = 0;
Nate Begeman61eecf52010-06-14 05:21:25 +0000358 unsigned TV = 0;
Bob Wilson46482552011-11-16 21:32:23 +0000359 int PtrArgNum = -1;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000360 bool HasConstPtr = false;
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000361 switch (BuiltinID) {
Nate Begemana23326b2010-06-17 04:17:01 +0000362#define GET_NEON_OVERLOAD_CHECK
363#include "clang/Basic/arm_neon.inc"
364#undef GET_NEON_OVERLOAD_CHECK
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000365 }
366
Nate Begeman0d15c532010-06-13 04:47:52 +0000367 // For NEON intrinsics which are overloaded on vector element type, validate
368 // the immediate which specifies which variant to emit.
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000369 unsigned ImmArg = TheCall->getNumArgs()-1;
Nate Begeman0d15c532010-06-13 04:47:52 +0000370 if (mask) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000371 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
Nate Begeman0d15c532010-06-13 04:47:52 +0000372 return true;
373
Bob Wilsonda95f732011-11-08 01:16:11 +0000374 TV = Result.getLimitedValue(64);
Richard Smithf8ee6bc2012-08-14 01:28:02 +0000375 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
Nate Begeman0d15c532010-06-13 04:47:52 +0000376 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000377 << TheCall->getArg(ImmArg)->getSourceRange();
378 }
379
Bob Wilson46482552011-11-16 21:32:23 +0000380 if (PtrArgNum >= 0) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000381 // Check that pointer arguments have the specified type.
Bob Wilson46482552011-11-16 21:32:23 +0000382 Expr *Arg = TheCall->getArg(PtrArgNum);
383 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
384 Arg = ICE->getSubExpr();
385 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
386 QualType RHSTy = RHS.get()->getType();
387 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context);
388 if (HasConstPtr)
389 EltTy = EltTy.withConst();
390 QualType LHSTy = Context.getPointerType(EltTy);
391 AssignConvertType ConvTy;
392 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
393 if (RHS.isInvalid())
394 return true;
395 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
396 RHS.get(), AA_Assigning))
397 return true;
Nate Begeman0d15c532010-06-13 04:47:52 +0000398 }
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000399
Nate Begeman0d15c532010-06-13 04:47:52 +0000400 // For NEON intrinsics which take an immediate value as part of the
401 // instruction, range check them here.
Nate Begeman61eecf52010-06-14 05:21:25 +0000402 unsigned i = 0, l = 0, u = 0;
Nate Begeman0d15c532010-06-13 04:47:52 +0000403 switch (BuiltinID) {
404 default: return false;
Nate Begemanbb37f502010-07-29 22:48:34 +0000405 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
406 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begeman99c40bb2010-08-03 21:32:34 +0000407 case ARM::BI__builtin_arm_vcvtr_f:
408 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Nate Begemana23326b2010-06-17 04:17:01 +0000409#define GET_NEON_IMMEDIATE_CHECK
410#include "clang/Basic/arm_neon.inc"
411#undef GET_NEON_IMMEDIATE_CHECK
Nate Begeman0d15c532010-06-13 04:47:52 +0000412 };
413
Douglas Gregor592a4232012-06-29 01:05:22 +0000414 // We can't check the value of a dependent argument.
415 if (TheCall->getArg(i)->isTypeDependent() ||
416 TheCall->getArg(i)->isValueDependent())
417 return false;
418
Nate Begeman61eecf52010-06-14 05:21:25 +0000419 // Check that the immediate argument is actually a constant.
Nate Begeman0d15c532010-06-13 04:47:52 +0000420 if (SemaBuiltinConstantArg(TheCall, i, Result))
421 return true;
422
Nate Begeman61eecf52010-06-14 05:21:25 +0000423 // Range check against the upper/lower values for this isntruction.
Nate Begeman0d15c532010-06-13 04:47:52 +0000424 unsigned Val = Result.getZExtValue();
Nate Begeman61eecf52010-06-14 05:21:25 +0000425 if (Val < l || Val > (u + l))
Nate Begeman0d15c532010-06-13 04:47:52 +0000426 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramer476d8b82010-08-11 14:47:12 +0000427 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begeman0d15c532010-06-13 04:47:52 +0000428
Nate Begeman99c40bb2010-08-03 21:32:34 +0000429 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman26a31422010-06-08 02:47:44 +0000430 return false;
Anders Carlssond406bf02009-08-16 01:56:34 +0000431}
Daniel Dunbarde454282008-10-02 18:44:07 +0000432
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000433bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
434 unsigned i = 0, l = 0, u = 0;
435 switch (BuiltinID) {
436 default: return false;
437 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
438 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyanbe22cb82012-08-27 12:29:20 +0000439 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
440 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
441 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
442 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
443 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000444 };
445
446 // We can't check the value of a dependent argument.
447 if (TheCall->getArg(i)->isTypeDependent() ||
448 TheCall->getArg(i)->isValueDependent())
449 return false;
450
451 // Check that the immediate argument is actually a constant.
452 llvm::APSInt Result;
453 if (SemaBuiltinConstantArg(TheCall, i, Result))
454 return true;
455
456 // Range check against the upper/lower values for this instruction.
457 unsigned Val = Result.getZExtValue();
458 if (Val < l || Val > u)
459 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
460 << l << u << TheCall->getArg(i)->getSourceRange();
461
462 return false;
463}
464
Richard Smith831421f2012-06-25 20:30:08 +0000465/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
466/// parameter with the FormatAttr's correct format_idx and firstDataArg.
467/// Returns true when the format fits the function and the FormatStringInfo has
468/// been populated.
469bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
470 FormatStringInfo *FSI) {
471 FSI->HasVAListArg = Format->getFirstArg() == 0;
472 FSI->FormatIdx = Format->getFormatIdx() - 1;
473 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssond406bf02009-08-16 01:56:34 +0000474
Richard Smith831421f2012-06-25 20:30:08 +0000475 // The way the format attribute works in GCC, the implicit this argument
476 // of member functions is counted. However, it doesn't appear in our own
477 // lists, so decrement format_idx in that case.
478 if (IsCXXMember) {
479 if(FSI->FormatIdx == 0)
480 return false;
481 --FSI->FormatIdx;
482 if (FSI->FirstDataArg != 0)
483 --FSI->FirstDataArg;
484 }
485 return true;
486}
Mike Stump1eb44332009-09-09 15:08:12 +0000487
Richard Smith831421f2012-06-25 20:30:08 +0000488/// Handles the checks for format strings, non-POD arguments to vararg
489/// functions, and NULL arguments passed to non-NULL parameters.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000490void Sema::checkCall(NamedDecl *FDecl,
491 ArrayRef<const Expr *> Args,
Richard Smith831421f2012-06-25 20:30:08 +0000492 unsigned NumProtoArgs,
493 bool IsMemberFunction,
494 SourceLocation Loc,
495 SourceRange Range,
496 VariadicCallType CallType) {
Jordan Rose66360e22012-10-02 01:49:54 +0000497 if (CurContext->isDependentContext())
498 return;
Daniel Dunbarde454282008-10-02 18:44:07 +0000499
Ted Kremenekc82faca2010-09-09 04:33:05 +0000500 // Printf and scanf checking.
Richard Smith831421f2012-06-25 20:30:08 +0000501 bool HandledFormatString = false;
Ted Kremenekc82faca2010-09-09 04:33:05 +0000502 for (specific_attr_iterator<FormatAttr>
Richard Smith831421f2012-06-25 20:30:08 +0000503 I = FDecl->specific_attr_begin<FormatAttr>(),
504 E = FDecl->specific_attr_end<FormatAttr>(); I != E ; ++I)
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000505 if (CheckFormatArguments(*I, Args, IsMemberFunction, CallType, 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)
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000511 for (unsigned ArgIdx = NumProtoArgs; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek0234bfa2012-10-11 19:06:43 +0000512 // Args[ArgIdx] can be null in malformed code.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000513 if (const Expr *Arg = Args[ArgIdx])
Ted Kremenek0234bfa2012-10-11 19:06:43 +0000514 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)
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000520 CheckNonNullArguments(*I, Args.data(), 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) {
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000526 CheckArgumentWithTypeTag(*i, Args.data());
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +0000527 }
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.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000532void Sema::CheckConstructorCall(FunctionDecl *FDecl,
533 ArrayRef<const Expr *> Args,
Richard Smith831421f2012-06-25 20:30:08 +0000534 const FunctionProtoType *Proto,
535 SourceLocation Loc) {
536 VariadicCallType CallType =
537 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000538 checkCall(FDecl, Args, Proto->getNumArgs(),
Richard Smith831421f2012-06-25 20:30:08 +0000539 /*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 }
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000562 checkCall(FDecl, llvm::makeArrayRef<const Expr *>(Args, NumArgs),
563 NumProtoArgs,
Richard Smith831421f2012-06-25 20:30:08 +0000564 IsMemberFunction, TheCall->getRParenLoc(),
565 TheCall->getCallee()->getSourceRange(), CallType);
566
567 IdentifierInfo *FnInfo = FDecl->getIdentifier();
568 // None of the checks below are needed for functions that don't have
569 // simple names (e.g., C++ conversion functions).
570 if (!FnInfo)
571 return false;
Sebastian Redl0eb23302009-01-19 00:08:26 +0000572
Anna Zaks0a151a12012-01-17 00:37:07 +0000573 unsigned CMId = FDecl->getMemoryFunctionKind();
574 if (CMId == 0)
Anna Zaksd9b859a2012-01-13 21:52:01 +0000575 return false;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000576
Anna Zaksd9b859a2012-01-13 21:52:01 +0000577 // Handle memory setting and copying functions.
Anna Zaks0a151a12012-01-17 00:37:07 +0000578 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000579 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaksc36bedc2012-02-01 19:08:57 +0000580 else if (CMId == Builtin::BIstrncat)
581 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaksd9b859a2012-01-13 21:52:01 +0000582 else
Anna Zaks0a151a12012-01-17 00:37:07 +0000583 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth7ccc95b2011-04-27 07:05:31 +0000584
Anders Carlssond406bf02009-08-16 01:56:34 +0000585 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000586}
587
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000588bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko287f24d2013-05-05 19:42:09 +0000589 ArrayRef<const Expr *> Args) {
Richard Smith831421f2012-06-25 20:30:08 +0000590 VariadicCallType CallType =
591 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000592
Dmitri Gribenko287f24d2013-05-05 19:42:09 +0000593 checkCall(Method, Args, Method->param_size(),
Richard Smith831421f2012-06-25 20:30:08 +0000594 /*IsMemberFunction=*/false,
595 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000596
597 return false;
598}
599
Richard Trieuf462b012013-06-20 21:03:13 +0000600bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
601 const FunctionProtoType *Proto) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000602 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
603 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000604 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000605
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000606 QualType Ty = V->getType();
Richard Trieuf462b012013-06-20 21:03:13 +0000607 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000608 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000609
Richard Trieuf462b012013-06-20 21:03:13 +0000610 VariadicCallType CallType;
611 if (!Proto) {
612 CallType = VariadicDoesNotApply;
613 } else if (Ty->isBlockPointerType()) {
614 CallType = VariadicBlock;
615 } else { // Ty->isFunctionPointerType()
616 CallType = VariadicFunction;
617 }
Richard Smith831421f2012-06-25 20:30:08 +0000618 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
Anders Carlssond406bf02009-08-16 01:56:34 +0000619
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000620 checkCall(NDecl,
621 llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
622 TheCall->getNumArgs()),
Richard Smith831421f2012-06-25 20:30:08 +0000623 NumProtoArgs, /*IsMemberFunction=*/false,
624 TheCall->getRParenLoc(),
625 TheCall->getCallee()->getSourceRange(), CallType);
626
Anders Carlssond406bf02009-08-16 01:56:34 +0000627 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000628}
629
Richard Smithff34d402012-04-12 05:08:17 +0000630ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
631 AtomicExpr::AtomicOp Op) {
Eli Friedman276b0612011-10-11 02:20:01 +0000632 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
633 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedman276b0612011-10-11 02:20:01 +0000634
Richard Smithff34d402012-04-12 05:08:17 +0000635 // All these operations take one of the following forms:
636 enum {
637 // C __c11_atomic_init(A *, C)
638 Init,
639 // C __c11_atomic_load(A *, int)
640 Load,
641 // void __atomic_load(A *, CP, int)
642 Copy,
643 // C __c11_atomic_add(A *, M, int)
644 Arithmetic,
645 // C __atomic_exchange_n(A *, CP, int)
646 Xchg,
647 // void __atomic_exchange(A *, C *, CP, int)
648 GNUXchg,
649 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
650 C11CmpXchg,
651 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
652 GNUCmpXchg
653 } Form = Init;
654 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
655 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
656 // where:
657 // C is an appropriate type,
658 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
659 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
660 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
661 // the int parameters are for orderings.
Eli Friedman276b0612011-10-11 02:20:01 +0000662
Richard Smithff34d402012-04-12 05:08:17 +0000663 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
664 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
665 && "need to update code for modified C11 atomics");
666 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
667 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
668 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
669 Op == AtomicExpr::AO__atomic_store_n ||
670 Op == AtomicExpr::AO__atomic_exchange_n ||
671 Op == AtomicExpr::AO__atomic_compare_exchange_n;
672 bool IsAddSub = false;
673
674 switch (Op) {
675 case AtomicExpr::AO__c11_atomic_init:
676 Form = Init;
677 break;
678
679 case AtomicExpr::AO__c11_atomic_load:
680 case AtomicExpr::AO__atomic_load_n:
681 Form = Load;
682 break;
683
684 case AtomicExpr::AO__c11_atomic_store:
685 case AtomicExpr::AO__atomic_load:
686 case AtomicExpr::AO__atomic_store:
687 case AtomicExpr::AO__atomic_store_n:
688 Form = Copy;
689 break;
690
691 case AtomicExpr::AO__c11_atomic_fetch_add:
692 case AtomicExpr::AO__c11_atomic_fetch_sub:
693 case AtomicExpr::AO__atomic_fetch_add:
694 case AtomicExpr::AO__atomic_fetch_sub:
695 case AtomicExpr::AO__atomic_add_fetch:
696 case AtomicExpr::AO__atomic_sub_fetch:
697 IsAddSub = true;
698 // Fall through.
699 case AtomicExpr::AO__c11_atomic_fetch_and:
700 case AtomicExpr::AO__c11_atomic_fetch_or:
701 case AtomicExpr::AO__c11_atomic_fetch_xor:
702 case AtomicExpr::AO__atomic_fetch_and:
703 case AtomicExpr::AO__atomic_fetch_or:
704 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smith51b92402012-04-13 06:31:38 +0000705 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithff34d402012-04-12 05:08:17 +0000706 case AtomicExpr::AO__atomic_and_fetch:
707 case AtomicExpr::AO__atomic_or_fetch:
708 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smith51b92402012-04-13 06:31:38 +0000709 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithff34d402012-04-12 05:08:17 +0000710 Form = Arithmetic;
711 break;
712
713 case AtomicExpr::AO__c11_atomic_exchange:
714 case AtomicExpr::AO__atomic_exchange_n:
715 Form = Xchg;
716 break;
717
718 case AtomicExpr::AO__atomic_exchange:
719 Form = GNUXchg;
720 break;
721
722 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
723 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
724 Form = C11CmpXchg;
725 break;
726
727 case AtomicExpr::AO__atomic_compare_exchange:
728 case AtomicExpr::AO__atomic_compare_exchange_n:
729 Form = GNUCmpXchg;
730 break;
731 }
732
733 // Check we have the right number of arguments.
734 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedman276b0612011-10-11 02:20:01 +0000735 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithff34d402012-04-12 05:08:17 +0000736 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +0000737 << TheCall->getCallee()->getSourceRange();
738 return ExprError();
Richard Smithff34d402012-04-12 05:08:17 +0000739 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
740 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedman276b0612011-10-11 02:20:01 +0000741 diag::err_typecheck_call_too_many_args)
Richard Smithff34d402012-04-12 05:08:17 +0000742 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +0000743 << TheCall->getCallee()->getSourceRange();
744 return ExprError();
745 }
746
Richard Smithff34d402012-04-12 05:08:17 +0000747 // Inspect the first argument of the atomic operation.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000748 Expr *Ptr = TheCall->getArg(0);
Eli Friedman276b0612011-10-11 02:20:01 +0000749 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
750 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
751 if (!pointerType) {
Richard Smithff34d402012-04-12 05:08:17 +0000752 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedman276b0612011-10-11 02:20:01 +0000753 << Ptr->getType() << Ptr->getSourceRange();
754 return ExprError();
755 }
756
Richard Smithff34d402012-04-12 05:08:17 +0000757 // For a __c11 builtin, this should be a pointer to an _Atomic type.
758 QualType AtomTy = pointerType->getPointeeType(); // 'A'
759 QualType ValType = AtomTy; // 'C'
760 if (IsC11) {
761 if (!AtomTy->isAtomicType()) {
762 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
763 << Ptr->getType() << Ptr->getSourceRange();
764 return ExprError();
765 }
Richard Smithbc57b102012-09-15 06:09:58 +0000766 if (AtomTy.isConstQualified()) {
767 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
768 << Ptr->getType() << Ptr->getSourceRange();
769 return ExprError();
770 }
Richard Smithff34d402012-04-12 05:08:17 +0000771 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedman276b0612011-10-11 02:20:01 +0000772 }
Eli Friedman276b0612011-10-11 02:20:01 +0000773
Richard Smithff34d402012-04-12 05:08:17 +0000774 // For an arithmetic operation, the implied arithmetic must be well-formed.
775 if (Form == Arithmetic) {
776 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
777 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
778 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
779 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
780 return ExprError();
781 }
782 if (!IsAddSub && !ValType->isIntegerType()) {
783 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
784 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
785 return ExprError();
786 }
787 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
788 // For __atomic_*_n operations, the value type must be a scalar integral or
789 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedman276b0612011-10-11 02:20:01 +0000790 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithff34d402012-04-12 05:08:17 +0000791 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
792 return ExprError();
793 }
794
795 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context)) {
796 // For GNU atomics, require a trivially-copyable type. This is not part of
797 // the GNU atomics specification, but we enforce it for sanity.
798 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedman276b0612011-10-11 02:20:01 +0000799 << Ptr->getType() << Ptr->getSourceRange();
800 return ExprError();
801 }
802
Richard Smithff34d402012-04-12 05:08:17 +0000803 // FIXME: For any builtin other than a load, the ValType must not be
804 // const-qualified.
Eli Friedman276b0612011-10-11 02:20:01 +0000805
806 switch (ValType.getObjCLifetime()) {
807 case Qualifiers::OCL_None:
808 case Qualifiers::OCL_ExplicitNone:
809 // okay
810 break;
811
812 case Qualifiers::OCL_Weak:
813 case Qualifiers::OCL_Strong:
814 case Qualifiers::OCL_Autoreleasing:
Richard Smithff34d402012-04-12 05:08:17 +0000815 // FIXME: Can this happen? By this point, ValType should be known
816 // to be trivially copyable.
Eli Friedman276b0612011-10-11 02:20:01 +0000817 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
818 << ValType << Ptr->getSourceRange();
819 return ExprError();
820 }
821
822 QualType ResultType = ValType;
Richard Smithff34d402012-04-12 05:08:17 +0000823 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedman276b0612011-10-11 02:20:01 +0000824 ResultType = Context.VoidTy;
Richard Smithff34d402012-04-12 05:08:17 +0000825 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedman276b0612011-10-11 02:20:01 +0000826 ResultType = Context.BoolTy;
827
Richard Smithff34d402012-04-12 05:08:17 +0000828 // The type of a parameter passed 'by value'. In the GNU atomics, such
829 // arguments are actually passed as pointers.
830 QualType ByValType = ValType; // 'CP'
831 if (!IsC11 && !IsN)
832 ByValType = Ptr->getType();
833
Eli Friedman276b0612011-10-11 02:20:01 +0000834 // The first argument --- the pointer --- has a fixed type; we
835 // deduce the types of the rest of the arguments accordingly. Walk
836 // the remaining arguments, converting them to the deduced value type.
Richard Smithff34d402012-04-12 05:08:17 +0000837 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedman276b0612011-10-11 02:20:01 +0000838 QualType Ty;
Richard Smithff34d402012-04-12 05:08:17 +0000839 if (i < NumVals[Form] + 1) {
840 switch (i) {
841 case 1:
842 // The second argument is the non-atomic operand. For arithmetic, this
843 // is always passed by value, and for a compare_exchange it is always
844 // passed by address. For the rest, GNU uses by-address and C11 uses
845 // by-value.
846 assert(Form != Load);
847 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
848 Ty = ValType;
849 else if (Form == Copy || Form == Xchg)
850 Ty = ByValType;
851 else if (Form == Arithmetic)
852 Ty = Context.getPointerDiffType();
853 else
854 Ty = Context.getPointerType(ValType.getUnqualifiedType());
855 break;
856 case 2:
857 // The third argument to compare_exchange / GNU exchange is a
858 // (pointer to a) desired value.
859 Ty = ByValType;
860 break;
861 case 3:
862 // The fourth argument to GNU compare_exchange is a 'weak' flag.
863 Ty = Context.BoolTy;
864 break;
865 }
Eli Friedman276b0612011-10-11 02:20:01 +0000866 } else {
867 // The order(s) are always converted to int.
868 Ty = Context.IntTy;
869 }
Richard Smithff34d402012-04-12 05:08:17 +0000870
Eli Friedman276b0612011-10-11 02:20:01 +0000871 InitializedEntity Entity =
872 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithff34d402012-04-12 05:08:17 +0000873 ExprResult Arg = TheCall->getArg(i);
Eli Friedman276b0612011-10-11 02:20:01 +0000874 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
875 if (Arg.isInvalid())
876 return true;
877 TheCall->setArg(i, Arg.get());
878 }
879
Richard Smithff34d402012-04-12 05:08:17 +0000880 // Permute the arguments into a 'consistent' order.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000881 SmallVector<Expr*, 5> SubExprs;
882 SubExprs.push_back(Ptr);
Richard Smithff34d402012-04-12 05:08:17 +0000883 switch (Form) {
884 case Init:
885 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnall7a7ee302012-01-16 17:27:18 +0000886 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +0000887 break;
888 case Load:
889 SubExprs.push_back(TheCall->getArg(1)); // Order
890 break;
891 case Copy:
892 case Arithmetic:
893 case Xchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000894 SubExprs.push_back(TheCall->getArg(2)); // Order
895 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +0000896 break;
897 case GNUXchg:
898 // Note, AtomicExpr::getVal2() has a special case for this atomic.
899 SubExprs.push_back(TheCall->getArg(3)); // Order
900 SubExprs.push_back(TheCall->getArg(1)); // Val1
901 SubExprs.push_back(TheCall->getArg(2)); // Val2
902 break;
903 case C11CmpXchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000904 SubExprs.push_back(TheCall->getArg(3)); // Order
905 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000906 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall2ebb98a2012-03-29 17:58:59 +0000907 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithff34d402012-04-12 05:08:17 +0000908 break;
909 case GNUCmpXchg:
910 SubExprs.push_back(TheCall->getArg(4)); // Order
911 SubExprs.push_back(TheCall->getArg(1)); // Val1
912 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
913 SubExprs.push_back(TheCall->getArg(2)); // Val2
914 SubExprs.push_back(TheCall->getArg(3)); // Weak
915 break;
Eli Friedman276b0612011-10-11 02:20:01 +0000916 }
Fariborz Jahanian538bbe52013-05-28 17:37:39 +0000917
918 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
919 SubExprs, ResultType, Op,
920 TheCall->getRParenLoc());
921
922 if ((Op == AtomicExpr::AO__c11_atomic_load ||
923 (Op == AtomicExpr::AO__c11_atomic_store)) &&
924 Context.AtomicUsesUnsupportedLibcall(AE))
925 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
926 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000927
Fariborz Jahanian538bbe52013-05-28 17:37:39 +0000928 return Owned(AE);
Eli Friedman276b0612011-10-11 02:20:01 +0000929}
930
931
John McCall5f8d6042011-08-27 01:09:30 +0000932/// checkBuiltinArgument - Given a call to a builtin function, perform
933/// normal type-checking on the given argument, updating the call in
934/// place. This is useful when a builtin function requires custom
935/// type-checking for some of its arguments but not necessarily all of
936/// them.
937///
938/// Returns true on error.
939static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
940 FunctionDecl *Fn = E->getDirectCallee();
941 assert(Fn && "builtin call without direct callee!");
942
943 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
944 InitializedEntity Entity =
945 InitializedEntity::InitializeParameter(S.Context, Param);
946
947 ExprResult Arg = E->getArg(0);
948 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
949 if (Arg.isInvalid())
950 return true;
951
952 E->setArg(ArgIndex, Arg.take());
953 return false;
954}
955
Chris Lattner5caa3702009-05-08 06:58:22 +0000956/// SemaBuiltinAtomicOverloaded - We have a call to a function like
957/// __sync_fetch_and_add, which is an overloaded function based on the pointer
958/// type of its first argument. The main ActOnCallExpr routines have already
959/// promoted the types of arguments because all of these calls are prototyped as
960/// void(...).
961///
962/// This function goes through and does final semantic checking for these
963/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +0000964ExprResult
965Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000966 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +0000967 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
968 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
969
970 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +0000971 if (TheCall->getNumArgs() < 1) {
972 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
973 << 0 << 1 << TheCall->getNumArgs()
974 << TheCall->getCallee()->getSourceRange();
975 return ExprError();
976 }
Mike Stump1eb44332009-09-09 15:08:12 +0000977
Chris Lattner5caa3702009-05-08 06:58:22 +0000978 // Inspect the first argument of the atomic builtin. This should always be
979 // a pointer type, whose element is an integral scalar or pointer type.
980 // Because it is a pointer type, we don't have to worry about any implicit
981 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +0000982 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +0000983 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman8c382062012-01-23 02:35:22 +0000984 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
985 if (FirstArgResult.isInvalid())
986 return ExprError();
987 FirstArg = FirstArgResult.take();
988 TheCall->setArg(0, FirstArg);
989
John McCallf85e1932011-06-15 23:02:42 +0000990 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
991 if (!pointerType) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000992 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
993 << FirstArg->getType() << FirstArg->getSourceRange();
994 return ExprError();
995 }
Mike Stump1eb44332009-09-09 15:08:12 +0000996
John McCallf85e1932011-06-15 23:02:42 +0000997 QualType ValType = pointerType->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +0000998 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +0000999 !ValType->isBlockPointerType()) {
1000 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1001 << FirstArg->getType() << FirstArg->getSourceRange();
1002 return ExprError();
1003 }
Chris Lattner5caa3702009-05-08 06:58:22 +00001004
John McCallf85e1932011-06-15 23:02:42 +00001005 switch (ValType.getObjCLifetime()) {
1006 case Qualifiers::OCL_None:
1007 case Qualifiers::OCL_ExplicitNone:
1008 // okay
1009 break;
1010
1011 case Qualifiers::OCL_Weak:
1012 case Qualifiers::OCL_Strong:
1013 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00001014 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCallf85e1932011-06-15 23:02:42 +00001015 << ValType << FirstArg->getSourceRange();
1016 return ExprError();
1017 }
1018
John McCallb45ae252011-10-05 07:41:44 +00001019 // Strip any qualifiers off ValType.
1020 ValType = ValType.getUnqualifiedType();
1021
Chandler Carruth8d13d222010-07-18 20:54:12 +00001022 // The majority of builtins return a value, but a few have special return
1023 // types, so allow them to override appropriately below.
1024 QualType ResultType = ValType;
1025
Chris Lattner5caa3702009-05-08 06:58:22 +00001026 // We need to figure out which concrete builtin this maps onto. For example,
1027 // __sync_fetch_and_add with a 2 byte object turns into
1028 // __sync_fetch_and_add_2.
1029#define BUILTIN_ROW(x) \
1030 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1031 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +00001032
Chris Lattner5caa3702009-05-08 06:58:22 +00001033 static const unsigned BuiltinIndices[][5] = {
1034 BUILTIN_ROW(__sync_fetch_and_add),
1035 BUILTIN_ROW(__sync_fetch_and_sub),
1036 BUILTIN_ROW(__sync_fetch_and_or),
1037 BUILTIN_ROW(__sync_fetch_and_and),
1038 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +00001039
Chris Lattner5caa3702009-05-08 06:58:22 +00001040 BUILTIN_ROW(__sync_add_and_fetch),
1041 BUILTIN_ROW(__sync_sub_and_fetch),
1042 BUILTIN_ROW(__sync_and_and_fetch),
1043 BUILTIN_ROW(__sync_or_and_fetch),
1044 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +00001045
Chris Lattner5caa3702009-05-08 06:58:22 +00001046 BUILTIN_ROW(__sync_val_compare_and_swap),
1047 BUILTIN_ROW(__sync_bool_compare_and_swap),
1048 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +00001049 BUILTIN_ROW(__sync_lock_release),
1050 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +00001051 };
Mike Stump1eb44332009-09-09 15:08:12 +00001052#undef BUILTIN_ROW
1053
Chris Lattner5caa3702009-05-08 06:58:22 +00001054 // Determine the index of the size.
1055 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +00001056 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +00001057 case 1: SizeIndex = 0; break;
1058 case 2: SizeIndex = 1; break;
1059 case 4: SizeIndex = 2; break;
1060 case 8: SizeIndex = 3; break;
1061 case 16: SizeIndex = 4; break;
1062 default:
Chandler Carruthd2014572010-07-09 18:59:35 +00001063 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1064 << FirstArg->getType() << FirstArg->getSourceRange();
1065 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +00001066 }
Mike Stump1eb44332009-09-09 15:08:12 +00001067
Chris Lattner5caa3702009-05-08 06:58:22 +00001068 // Each of these builtins has one pointer argument, followed by some number of
1069 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1070 // that we ignore. Find out which row of BuiltinIndices to read from as well
1071 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00001072 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +00001073 unsigned BuiltinIndex, NumFixed = 1;
1074 switch (BuiltinID) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001075 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregora9766412011-11-28 16:30:08 +00001076 case Builtin::BI__sync_fetch_and_add:
1077 case Builtin::BI__sync_fetch_and_add_1:
1078 case Builtin::BI__sync_fetch_and_add_2:
1079 case Builtin::BI__sync_fetch_and_add_4:
1080 case Builtin::BI__sync_fetch_and_add_8:
1081 case Builtin::BI__sync_fetch_and_add_16:
1082 BuiltinIndex = 0;
1083 break;
1084
1085 case Builtin::BI__sync_fetch_and_sub:
1086 case Builtin::BI__sync_fetch_and_sub_1:
1087 case Builtin::BI__sync_fetch_and_sub_2:
1088 case Builtin::BI__sync_fetch_and_sub_4:
1089 case Builtin::BI__sync_fetch_and_sub_8:
1090 case Builtin::BI__sync_fetch_and_sub_16:
1091 BuiltinIndex = 1;
1092 break;
1093
1094 case Builtin::BI__sync_fetch_and_or:
1095 case Builtin::BI__sync_fetch_and_or_1:
1096 case Builtin::BI__sync_fetch_and_or_2:
1097 case Builtin::BI__sync_fetch_and_or_4:
1098 case Builtin::BI__sync_fetch_and_or_8:
1099 case Builtin::BI__sync_fetch_and_or_16:
1100 BuiltinIndex = 2;
1101 break;
1102
1103 case Builtin::BI__sync_fetch_and_and:
1104 case Builtin::BI__sync_fetch_and_and_1:
1105 case Builtin::BI__sync_fetch_and_and_2:
1106 case Builtin::BI__sync_fetch_and_and_4:
1107 case Builtin::BI__sync_fetch_and_and_8:
1108 case Builtin::BI__sync_fetch_and_and_16:
1109 BuiltinIndex = 3;
1110 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001111
Douglas Gregora9766412011-11-28 16:30:08 +00001112 case Builtin::BI__sync_fetch_and_xor:
1113 case Builtin::BI__sync_fetch_and_xor_1:
1114 case Builtin::BI__sync_fetch_and_xor_2:
1115 case Builtin::BI__sync_fetch_and_xor_4:
1116 case Builtin::BI__sync_fetch_and_xor_8:
1117 case Builtin::BI__sync_fetch_and_xor_16:
1118 BuiltinIndex = 4;
1119 break;
1120
1121 case Builtin::BI__sync_add_and_fetch:
1122 case Builtin::BI__sync_add_and_fetch_1:
1123 case Builtin::BI__sync_add_and_fetch_2:
1124 case Builtin::BI__sync_add_and_fetch_4:
1125 case Builtin::BI__sync_add_and_fetch_8:
1126 case Builtin::BI__sync_add_and_fetch_16:
1127 BuiltinIndex = 5;
1128 break;
1129
1130 case Builtin::BI__sync_sub_and_fetch:
1131 case Builtin::BI__sync_sub_and_fetch_1:
1132 case Builtin::BI__sync_sub_and_fetch_2:
1133 case Builtin::BI__sync_sub_and_fetch_4:
1134 case Builtin::BI__sync_sub_and_fetch_8:
1135 case Builtin::BI__sync_sub_and_fetch_16:
1136 BuiltinIndex = 6;
1137 break;
1138
1139 case Builtin::BI__sync_and_and_fetch:
1140 case Builtin::BI__sync_and_and_fetch_1:
1141 case Builtin::BI__sync_and_and_fetch_2:
1142 case Builtin::BI__sync_and_and_fetch_4:
1143 case Builtin::BI__sync_and_and_fetch_8:
1144 case Builtin::BI__sync_and_and_fetch_16:
1145 BuiltinIndex = 7;
1146 break;
1147
1148 case Builtin::BI__sync_or_and_fetch:
1149 case Builtin::BI__sync_or_and_fetch_1:
1150 case Builtin::BI__sync_or_and_fetch_2:
1151 case Builtin::BI__sync_or_and_fetch_4:
1152 case Builtin::BI__sync_or_and_fetch_8:
1153 case Builtin::BI__sync_or_and_fetch_16:
1154 BuiltinIndex = 8;
1155 break;
1156
1157 case Builtin::BI__sync_xor_and_fetch:
1158 case Builtin::BI__sync_xor_and_fetch_1:
1159 case Builtin::BI__sync_xor_and_fetch_2:
1160 case Builtin::BI__sync_xor_and_fetch_4:
1161 case Builtin::BI__sync_xor_and_fetch_8:
1162 case Builtin::BI__sync_xor_and_fetch_16:
1163 BuiltinIndex = 9;
1164 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001165
Chris Lattner5caa3702009-05-08 06:58:22 +00001166 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001167 case Builtin::BI__sync_val_compare_and_swap_1:
1168 case Builtin::BI__sync_val_compare_and_swap_2:
1169 case Builtin::BI__sync_val_compare_and_swap_4:
1170 case Builtin::BI__sync_val_compare_and_swap_8:
1171 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001172 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +00001173 NumFixed = 2;
1174 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001175
Chris Lattner5caa3702009-05-08 06:58:22 +00001176 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001177 case Builtin::BI__sync_bool_compare_and_swap_1:
1178 case Builtin::BI__sync_bool_compare_and_swap_2:
1179 case Builtin::BI__sync_bool_compare_and_swap_4:
1180 case Builtin::BI__sync_bool_compare_and_swap_8:
1181 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001182 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +00001183 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001184 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001185 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001186
1187 case Builtin::BI__sync_lock_test_and_set:
1188 case Builtin::BI__sync_lock_test_and_set_1:
1189 case Builtin::BI__sync_lock_test_and_set_2:
1190 case Builtin::BI__sync_lock_test_and_set_4:
1191 case Builtin::BI__sync_lock_test_and_set_8:
1192 case Builtin::BI__sync_lock_test_and_set_16:
1193 BuiltinIndex = 12;
1194 break;
1195
Chris Lattner5caa3702009-05-08 06:58:22 +00001196 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +00001197 case Builtin::BI__sync_lock_release_1:
1198 case Builtin::BI__sync_lock_release_2:
1199 case Builtin::BI__sync_lock_release_4:
1200 case Builtin::BI__sync_lock_release_8:
1201 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001202 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +00001203 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001204 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001205 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001206
1207 case Builtin::BI__sync_swap:
1208 case Builtin::BI__sync_swap_1:
1209 case Builtin::BI__sync_swap_2:
1210 case Builtin::BI__sync_swap_4:
1211 case Builtin::BI__sync_swap_8:
1212 case Builtin::BI__sync_swap_16:
1213 BuiltinIndex = 14;
1214 break;
Chris Lattner5caa3702009-05-08 06:58:22 +00001215 }
Mike Stump1eb44332009-09-09 15:08:12 +00001216
Chris Lattner5caa3702009-05-08 06:58:22 +00001217 // Now that we know how many fixed arguments we expect, first check that we
1218 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +00001219 if (TheCall->getNumArgs() < 1+NumFixed) {
1220 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1221 << 0 << 1+NumFixed << TheCall->getNumArgs()
1222 << TheCall->getCallee()->getSourceRange();
1223 return ExprError();
1224 }
Mike Stump1eb44332009-09-09 15:08:12 +00001225
Chris Lattnere7ac0a92009-05-08 15:36:58 +00001226 // Get the decl for the concrete builtin from this, we can tell what the
1227 // concrete integer type we should convert to is.
1228 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1229 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara2ad11cd2012-09-22 09:05:22 +00001230 FunctionDecl *NewBuiltinDecl;
1231 if (NewBuiltinID == BuiltinID)
1232 NewBuiltinDecl = FDecl;
1233 else {
1234 // Perform builtin lookup to avoid redeclaring it.
1235 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1236 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1237 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1238 assert(Res.getFoundDecl());
1239 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
1240 if (NewBuiltinDecl == 0)
1241 return ExprError();
1242 }
Chandler Carruthd2014572010-07-09 18:59:35 +00001243
John McCallf871d0c2010-08-07 06:22:56 +00001244 // The first argument --- the pointer --- has a fixed type; we
1245 // deduce the types of the rest of the arguments accordingly. Walk
1246 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +00001247 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +00001248 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +00001249
Chris Lattner5caa3702009-05-08 06:58:22 +00001250 // GCC does an implicit conversion to the pointer or integer ValType. This
1251 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb45ae252011-10-05 07:41:44 +00001252 // Initialize the argument.
1253 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1254 ValType, /*consume*/ false);
1255 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley429bb272011-04-08 18:41:53 +00001256 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +00001257 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001258
Chris Lattner5caa3702009-05-08 06:58:22 +00001259 // Okay, we have something that *can* be converted to the right type. Check
1260 // to see if there is a potentially weird extension going on here. This can
1261 // happen when you do an atomic operation on something like an char* and
1262 // pass in 42. The 42 gets converted to char. This is even more strange
1263 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +00001264 // FIXME: Do this check.
John McCallb45ae252011-10-05 07:41:44 +00001265 TheCall->setArg(i+1, Arg.take());
Chris Lattner5caa3702009-05-08 06:58:22 +00001266 }
Mike Stump1eb44332009-09-09 15:08:12 +00001267
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001268 ASTContext& Context = this->getASTContext();
1269
1270 // Create a new DeclRefExpr to refer to the new decl.
1271 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1272 Context,
1273 DRE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001274 SourceLocation(),
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001275 NewBuiltinDecl,
John McCallf4b88a42012-03-10 09:33:50 +00001276 /*enclosing*/ false,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001277 DRE->getLocation(),
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001278 Context.BuiltinFnTy,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001279 DRE->getValueKind());
Mike Stump1eb44332009-09-09 15:08:12 +00001280
Chris Lattner5caa3702009-05-08 06:58:22 +00001281 // Set the callee in the CallExpr.
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001282 // FIXME: This loses syntactic information.
1283 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1284 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1285 CK_BuiltinFnToFnPtr);
John Wiegley429bb272011-04-08 18:41:53 +00001286 TheCall->setCallee(PromotedCall.take());
Mike Stump1eb44332009-09-09 15:08:12 +00001287
Chandler Carruthdb4325b2010-07-18 07:23:17 +00001288 // Change the result type of the call to match the original value type. This
1289 // is arbitrary, but the codegen for these builtins ins design to handle it
1290 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +00001291 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +00001292
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001293 return TheCallResult;
Chris Lattner5caa3702009-05-08 06:58:22 +00001294}
1295
Chris Lattner69039812009-02-18 06:01:06 +00001296/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +00001297/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +00001298/// Note: It might also make sense to do the UTF-16 conversion here (would
1299/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +00001300bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +00001301 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +00001302 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1303
Douglas Gregor5cee1192011-07-27 05:40:30 +00001304 if (!Literal || !Literal->isAscii()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001305 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1306 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001307 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +00001308 }
Mike Stump1eb44332009-09-09 15:08:12 +00001309
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001310 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001311 StringRef String = Literal->getString();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001312 unsigned NumBytes = String.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001313 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divacky31ba6132012-09-06 15:59:27 +00001314 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001315 UTF16 *ToPtr = &ToBuf[0];
1316
1317 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1318 &ToPtr, ToPtr + NumBytes,
1319 strictConversion);
1320 // Check for conversion failure.
1321 if (Result != conversionOK)
1322 Diag(Arg->getLocStart(),
1323 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1324 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001325 return false;
Chris Lattner59907c42007-08-10 20:18:51 +00001326}
1327
Chris Lattnerc27c6652007-12-20 00:05:45 +00001328/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1329/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +00001330bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1331 Expr *Fn = TheCall->getCallee();
1332 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +00001333 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001334 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001335 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1336 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +00001337 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001338 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +00001339 return true;
1340 }
Eli Friedman56f20ae2008-12-15 22:05:35 +00001341
1342 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +00001343 return Diag(TheCall->getLocEnd(),
1344 diag::err_typecheck_call_too_few_args_at_least)
1345 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +00001346 }
1347
John McCall5f8d6042011-08-27 01:09:30 +00001348 // Type-check the first argument normally.
1349 if (checkBuiltinArgument(*this, TheCall, 0))
1350 return true;
1351
Chris Lattnerc27c6652007-12-20 00:05:45 +00001352 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001353 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +00001354 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001355 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +00001356 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +00001357 else if (FunctionDecl *FD = getCurFunctionDecl())
1358 isVariadic = FD->isVariadic();
1359 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001360 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +00001361
Chris Lattnerc27c6652007-12-20 00:05:45 +00001362 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001363 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1364 return true;
1365 }
Mike Stump1eb44332009-09-09 15:08:12 +00001366
Chris Lattner30ce3442007-12-19 23:59:04 +00001367 // Verify that the second argument to the builtin is the last argument of the
1368 // current function or method.
1369 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +00001370 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001371
Nico Weberb07d4482013-05-24 23:31:57 +00001372 // These are valid if SecondArgIsLastNamedArgument is false after the next
1373 // block.
1374 QualType Type;
1375 SourceLocation ParamLoc;
1376
Anders Carlsson88cf2262008-02-11 04:20:54 +00001377 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1378 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001379 // FIXME: This isn't correct for methods (results in bogus warning).
1380 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +00001381 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001382 if (CurBlock)
1383 LastArg = *(CurBlock->TheDecl->param_end()-1);
1384 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +00001385 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001386 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001387 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001388 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weberb07d4482013-05-24 23:31:57 +00001389
1390 Type = PV->getType();
1391 ParamLoc = PV->getLocation();
Chris Lattner30ce3442007-12-19 23:59:04 +00001392 }
1393 }
Mike Stump1eb44332009-09-09 15:08:12 +00001394
Chris Lattner30ce3442007-12-19 23:59:04 +00001395 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001396 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +00001397 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weberb07d4482013-05-24 23:31:57 +00001398 else if (Type->isReferenceType()) {
1399 Diag(Arg->getLocStart(),
1400 diag::warn_va_start_of_reference_type_is_undefined);
1401 Diag(ParamLoc, diag::note_parameter_type) << Type;
1402 }
1403
Chris Lattner30ce3442007-12-19 23:59:04 +00001404 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +00001405}
Chris Lattner30ce3442007-12-19 23:59:04 +00001406
Chris Lattner1b9a0792007-12-20 00:26:33 +00001407/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1408/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +00001409bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1410 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +00001411 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001412 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +00001413 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +00001414 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001415 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001416 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001417 << SourceRange(TheCall->getArg(2)->getLocStart(),
1418 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001419
John Wiegley429bb272011-04-08 18:41:53 +00001420 ExprResult OrigArg0 = TheCall->getArg(0);
1421 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +00001422
Chris Lattner1b9a0792007-12-20 00:26:33 +00001423 // Do standard promotions between the two arguments, returning their common
1424 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +00001425 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +00001426 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1427 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +00001428
1429 // Make sure any conversions are pushed back into the call; this is
1430 // type safe since unordered compare builtins are declared as "_Bool
1431 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +00001432 TheCall->setArg(0, OrigArg0.get());
1433 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001434
John Wiegley429bb272011-04-08 18:41:53 +00001435 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +00001436 return false;
1437
Chris Lattner1b9a0792007-12-20 00:26:33 +00001438 // If the common type isn't a real floating type, then the arguments were
1439 // invalid for this operation.
Eli Friedman860a3192012-06-16 02:19:17 +00001440 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +00001441 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001442 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +00001443 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1444 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001445
Chris Lattner1b9a0792007-12-20 00:26:33 +00001446 return false;
1447}
1448
Benjamin Kramere771a7a2010-02-15 22:42:31 +00001449/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1450/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001451/// to check everything. We expect the last argument to be a floating point
1452/// value.
1453bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1454 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +00001455 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001456 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001457 if (TheCall->getNumArgs() > NumArgs)
1458 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001459 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001460 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001461 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001462 (*(TheCall->arg_end()-1))->getLocEnd());
1463
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001464 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001465
Eli Friedman9ac6f622009-08-31 20:06:00 +00001466 if (OrigArg->isTypeDependent())
1467 return false;
1468
Chris Lattner81368fb2010-05-06 05:50:07 +00001469 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +00001470 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +00001471 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001472 diag::err_typecheck_call_invalid_unary_fp)
1473 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001474
Chris Lattner81368fb2010-05-06 05:50:07 +00001475 // If this is an implicit conversion from float -> double, remove it.
1476 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1477 Expr *CastArg = Cast->getSubExpr();
1478 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1479 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1480 "promotion from float to double is the only expected cast here");
1481 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +00001482 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner81368fb2010-05-06 05:50:07 +00001483 }
1484 }
1485
Eli Friedman9ac6f622009-08-31 20:06:00 +00001486 return false;
1487}
1488
Eli Friedmand38617c2008-05-14 19:38:39 +00001489/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1490// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +00001491ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001492 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001493 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +00001494 diag::err_typecheck_call_too_few_args_at_least)
Nate Begeman37b6a572010-06-08 00:16:34 +00001495 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherd77b9a22010-04-16 04:48:22 +00001496 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001497
Nate Begeman37b6a572010-06-08 00:16:34 +00001498 // Determine which of the following types of shufflevector we're checking:
1499 // 1) unary, vector mask: (lhs, mask)
1500 // 2) binary, vector mask: (lhs, rhs, mask)
1501 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1502 QualType resType = TheCall->getArg(0)->getType();
1503 unsigned numElements = 0;
1504
Douglas Gregorcde01732009-05-19 22:10:17 +00001505 if (!TheCall->getArg(0)->isTypeDependent() &&
1506 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001507 QualType LHSType = TheCall->getArg(0)->getType();
1508 QualType RHSType = TheCall->getArg(1)->getType();
1509
1510 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001511 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001512 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001513 TheCall->getArg(1)->getLocEnd());
1514 return ExprError();
1515 }
Nate Begeman37b6a572010-06-08 00:16:34 +00001516
1517 numElements = LHSType->getAs<VectorType>()->getNumElements();
1518 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +00001519
Nate Begeman37b6a572010-06-08 00:16:34 +00001520 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1521 // with mask. If so, verify that RHS is an integer vector type with the
1522 // same number of elts as lhs.
1523 if (TheCall->getNumArgs() == 2) {
Douglas Gregorf6094622010-07-23 15:58:24 +00001524 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +00001525 RHSType->getAs<VectorType>()->getNumElements() != numElements)
1526 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1527 << SourceRange(TheCall->getArg(1)->getLocStart(),
1528 TheCall->getArg(1)->getLocEnd());
1529 numResElements = numElements;
1530 }
1531 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001532 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001533 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001534 TheCall->getArg(1)->getLocEnd());
1535 return ExprError();
Nate Begeman37b6a572010-06-08 00:16:34 +00001536 } else if (numElements != numResElements) {
1537 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +00001538 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001539 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +00001540 }
Eli Friedmand38617c2008-05-14 19:38:39 +00001541 }
1542
1543 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001544 if (TheCall->getArg(i)->isTypeDependent() ||
1545 TheCall->getArg(i)->isValueDependent())
1546 continue;
1547
Nate Begeman37b6a572010-06-08 00:16:34 +00001548 llvm::APSInt Result(32);
1549 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1550 return ExprError(Diag(TheCall->getLocStart(),
1551 diag::err_shufflevector_nonconstant_argument)
1552 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001553
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001554 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001555 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001556 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001557 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001558 }
1559
Chris Lattner5f9e2722011-07-23 10:55:15 +00001560 SmallVector<Expr*, 32> exprs;
Eli Friedmand38617c2008-05-14 19:38:39 +00001561
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001562 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +00001563 exprs.push_back(TheCall->getArg(i));
1564 TheCall->setArg(i, 0);
1565 }
1566
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001567 return Owned(new (Context) ShuffleVectorExpr(Context, exprs, resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001568 TheCall->getCallee()->getLocStart(),
1569 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +00001570}
Chris Lattner30ce3442007-12-19 23:59:04 +00001571
Daniel Dunbar4493f792008-07-21 22:59:13 +00001572/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1573// This is declared to take (const void*, ...) and can take two
1574// optional constant int args.
1575bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001576 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001577
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001578 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +00001579 return Diag(TheCall->getLocEnd(),
1580 diag::err_typecheck_call_too_many_args_at_most)
1581 << 0 /*function call*/ << 3 << NumArgs
1582 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001583
1584 // Argument 0 is checked for us and the remaining arguments must be
1585 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001586 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +00001587 Expr *Arg = TheCall->getArg(i);
Douglas Gregor592a4232012-06-29 01:05:22 +00001588
1589 // We can't check the value of a dependent argument.
1590 if (Arg->isTypeDependent() || Arg->isValueDependent())
1591 continue;
1592
Eli Friedman9aef7262009-12-04 00:30:06 +00001593 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +00001594 if (SemaBuiltinConstantArg(TheCall, i, Result))
1595 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001596
Daniel Dunbar4493f792008-07-21 22:59:13 +00001597 // FIXME: gcc issues a warning and rewrites these to 0. These
1598 // seems especially odd for the third argument since the default
1599 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001600 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +00001601 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001602 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001603 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001604 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +00001605 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001606 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001607 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001608 }
1609 }
1610
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001611 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +00001612}
1613
Eric Christopher691ebc32010-04-17 02:26:23 +00001614/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1615/// TheCall is a constant expression.
1616bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1617 llvm::APSInt &Result) {
1618 Expr *Arg = TheCall->getArg(ArgNum);
1619 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1620 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1621
1622 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1623
1624 if (!Arg->isIntegerConstantExpr(Result, Context))
1625 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +00001626 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +00001627
Chris Lattner21fb98e2009-09-23 06:06:36 +00001628 return false;
1629}
1630
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001631/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1632/// int type). This simply type checks that type is one of the defined
1633/// constants (0-3).
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001634// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001635bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +00001636 llvm::APSInt Result;
Douglas Gregor592a4232012-06-29 01:05:22 +00001637
1638 // We can't check the value of a dependent argument.
1639 if (TheCall->getArg(1)->isTypeDependent() ||
1640 TheCall->getArg(1)->isValueDependent())
1641 return false;
1642
Eric Christopher691ebc32010-04-17 02:26:23 +00001643 // Check constant-ness first.
1644 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1645 return true;
1646
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001647 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001648 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001649 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1650 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001651 }
1652
1653 return false;
1654}
1655
Eli Friedman586d6a82009-05-03 06:04:26 +00001656/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +00001657/// This checks that val is a constant 1.
1658bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1659 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +00001660 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +00001661
Eric Christopher691ebc32010-04-17 02:26:23 +00001662 // TODO: This is less than ideal. Overload this to take a value.
1663 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1664 return true;
1665
1666 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +00001667 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1668 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1669
1670 return false;
1671}
1672
Richard Smith831421f2012-06-25 20:30:08 +00001673// Determine if an expression is a string literal or constant string.
1674// If this function returns false on the arguments to a function expecting a
1675// format string, we will usually need to emit a warning.
1676// True string literals are then checked by CheckFormatString.
1677Sema::StringLiteralCheckType
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001678Sema::checkFormatStringExpr(const Expr *E, ArrayRef<const Expr *> Args,
1679 bool HasVAListArg,
Richard Smith831421f2012-06-25 20:30:08 +00001680 unsigned format_idx, unsigned firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001681 FormatStringType Type, VariadicCallType CallType,
1682 bool inFunctionCall) {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001683 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +00001684 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith831421f2012-06-25 20:30:08 +00001685 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001686
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001687 E = E->IgnoreParenCasts();
Peter Collingbournef111d932011-04-15 00:35:48 +00001688
David Blaikiea73cdcb2012-02-10 21:07:25 +00001689 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
1690 // Technically -Wformat-nonliteral does not warn about this case.
1691 // The behavior of printf and friends in this case is implementation
1692 // dependent. Ideally if the format string cannot be null then
1693 // it should have a 'nonnull' attribute in the function prototype.
Richard Smith831421f2012-06-25 20:30:08 +00001694 return SLCT_CheckedLiteral;
David Blaikiea73cdcb2012-02-10 21:07:25 +00001695
Ted Kremenekd30ef872009-01-12 23:09:09 +00001696 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +00001697 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +00001698 case Stmt::ConditionalOperatorClass: {
Richard Smith831421f2012-06-25 20:30:08 +00001699 // The expression is a literal if both sub-expressions were, and it was
1700 // completely checked only if both sub-expressions were checked.
1701 const AbstractConditionalOperator *C =
1702 cast<AbstractConditionalOperator>(E);
1703 StringLiteralCheckType Left =
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001704 checkFormatStringExpr(C->getTrueExpr(), Args,
Richard Smith831421f2012-06-25 20:30:08 +00001705 HasVAListArg, format_idx, firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001706 Type, CallType, inFunctionCall);
Richard Smith831421f2012-06-25 20:30:08 +00001707 if (Left == SLCT_NotALiteral)
1708 return SLCT_NotALiteral;
1709 StringLiteralCheckType Right =
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001710 checkFormatStringExpr(C->getFalseExpr(), Args,
Richard Smith831421f2012-06-25 20:30:08 +00001711 HasVAListArg, format_idx, firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001712 Type, CallType, inFunctionCall);
Richard Smith831421f2012-06-25 20:30:08 +00001713 return Left < Right ? Left : Right;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001714 }
1715
1716 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001717 E = cast<ImplicitCastExpr>(E)->getSubExpr();
1718 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001719 }
1720
John McCall56ca35d2011-02-17 10:25:35 +00001721 case Stmt::OpaqueValueExprClass:
1722 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
1723 E = src;
1724 goto tryAgain;
1725 }
Richard Smith831421f2012-06-25 20:30:08 +00001726 return SLCT_NotALiteral;
John McCall56ca35d2011-02-17 10:25:35 +00001727
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001728 case Stmt::PredefinedExprClass:
1729 // While __func__, etc., are technically not string literals, they
1730 // cannot contain format specifiers and thus are not a security
1731 // liability.
Richard Smith831421f2012-06-25 20:30:08 +00001732 return SLCT_UncheckedLiteral;
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001733
Ted Kremenek082d9362009-03-20 21:35:28 +00001734 case Stmt::DeclRefExprClass: {
1735 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001736
Ted Kremenek082d9362009-03-20 21:35:28 +00001737 // As an exception, do not flag errors for variables binding to
1738 // const string literals.
1739 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1740 bool isConstant = false;
1741 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001742
Ted Kremenek082d9362009-03-20 21:35:28 +00001743 if (const ArrayType *AT = Context.getAsArrayType(T)) {
1744 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001745 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001746 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +00001747 PT->getPointeeType().isConstant(Context);
Jean-Daniel Dupase98e5b52012-01-25 10:35:33 +00001748 } else if (T->isObjCObjectPointerType()) {
1749 // In ObjC, there is usually no "const ObjectPointer" type,
1750 // so don't check if the pointee type is constant.
1751 isConstant = T.isConstant(Context);
Ted Kremenek082d9362009-03-20 21:35:28 +00001752 }
Mike Stump1eb44332009-09-09 15:08:12 +00001753
Ted Kremenek082d9362009-03-20 21:35:28 +00001754 if (isConstant) {
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00001755 if (const Expr *Init = VD->getAnyInitializer()) {
1756 // Look through initializers like const char c[] = { "foo" }
1757 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
1758 if (InitList->isStringLiteralInit())
1759 Init = InitList->getInit(0)->IgnoreParenImpCasts();
1760 }
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001761 return checkFormatStringExpr(Init, Args,
Richard Smith831421f2012-06-25 20:30:08 +00001762 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001763 firstDataArg, Type, CallType,
Richard Smith831421f2012-06-25 20:30:08 +00001764 /*inFunctionCall*/false);
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00001765 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001766 }
Mike Stump1eb44332009-09-09 15:08:12 +00001767
Anders Carlssond966a552009-06-28 19:55:58 +00001768 // For vprintf* functions (i.e., HasVAListArg==true), we add a
1769 // special check to see if the format string is a function parameter
1770 // of the function calling the printf function. If the function
1771 // has an attribute indicating it is a printf-like function, then we
1772 // should suppress warnings concerning non-literals being used in a call
1773 // to a vprintf function. For example:
1774 //
1775 // void
1776 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1777 // va_list ap;
1778 // va_start(ap, fmt);
1779 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
1780 // ...
1781 //
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00001782 if (HasVAListArg) {
1783 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
1784 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
1785 int PVIndex = PV->getFunctionScopeIndex() + 1;
1786 for (specific_attr_iterator<FormatAttr>
1787 i = ND->specific_attr_begin<FormatAttr>(),
1788 e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) {
1789 FormatAttr *PVFormat = *i;
1790 // adjust for implicit parameter
1791 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1792 if (MD->isInstance())
1793 ++PVIndex;
1794 // We also check if the formats are compatible.
1795 // We can't pass a 'scanf' string to a 'printf' function.
1796 if (PVIndex == PVFormat->getFormatIdx() &&
1797 Type == GetFormatStringType(PVFormat))
Richard Smith831421f2012-06-25 20:30:08 +00001798 return SLCT_UncheckedLiteral;
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00001799 }
1800 }
1801 }
1802 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001803 }
Mike Stump1eb44332009-09-09 15:08:12 +00001804
Richard Smith831421f2012-06-25 20:30:08 +00001805 return SLCT_NotALiteral;
Ted Kremenek082d9362009-03-20 21:35:28 +00001806 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00001807
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001808 case Stmt::CallExprClass:
1809 case Stmt::CXXMemberCallExprClass: {
Anders Carlsson8f031b32009-06-27 04:05:33 +00001810 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001811 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
1812 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
1813 unsigned ArgIndex = FA->getFormatIdx();
1814 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1815 if (MD->isInstance())
1816 --ArgIndex;
1817 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001818
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001819 return checkFormatStringExpr(Arg, Args,
Richard Smith831421f2012-06-25 20:30:08 +00001820 HasVAListArg, format_idx, firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001821 Type, CallType, inFunctionCall);
Jordan Rose50687312012-06-04 23:52:23 +00001822 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
1823 unsigned BuiltinID = FD->getBuiltinID();
1824 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
1825 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
1826 const Expr *Arg = CE->getArg(0);
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001827 return checkFormatStringExpr(Arg, Args,
Richard Smith831421f2012-06-25 20:30:08 +00001828 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001829 firstDataArg, Type, CallType,
1830 inFunctionCall);
Jordan Rose50687312012-06-04 23:52:23 +00001831 }
Anders Carlsson8f031b32009-06-27 04:05:33 +00001832 }
1833 }
Mike Stump1eb44332009-09-09 15:08:12 +00001834
Richard Smith831421f2012-06-25 20:30:08 +00001835 return SLCT_NotALiteral;
Anders Carlsson8f031b32009-06-27 04:05:33 +00001836 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001837 case Stmt::ObjCStringLiteralClass:
1838 case Stmt::StringLiteralClass: {
1839 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001840
Ted Kremenek082d9362009-03-20 21:35:28 +00001841 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00001842 StrE = ObjCFExpr->getString();
1843 else
Ted Kremenek082d9362009-03-20 21:35:28 +00001844 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001845
Ted Kremenekd30ef872009-01-12 23:09:09 +00001846 if (StrE) {
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001847 CheckFormatString(StrE, E, Args, HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001848 firstDataArg, Type, inFunctionCall, CallType);
Richard Smith831421f2012-06-25 20:30:08 +00001849 return SLCT_CheckedLiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001850 }
Mike Stump1eb44332009-09-09 15:08:12 +00001851
Richard Smith831421f2012-06-25 20:30:08 +00001852 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001853 }
Mike Stump1eb44332009-09-09 15:08:12 +00001854
Ted Kremenek082d9362009-03-20 21:35:28 +00001855 default:
Richard Smith831421f2012-06-25 20:30:08 +00001856 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001857 }
1858}
1859
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001860void
Mike Stump1eb44332009-09-09 15:08:12 +00001861Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewycky909a70d2011-03-25 01:44:32 +00001862 const Expr * const *ExprArgs,
1863 SourceLocation CallSiteLoc) {
Sean Huntcf807c42010-08-18 23:23:40 +00001864 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1865 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001866 i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +00001867 const Expr *ArgExpr = ExprArgs[*i];
Nick Lewycky3edf3872013-01-23 05:08:29 +00001868
1869 // As a special case, transparent unions initialized with zero are
1870 // considered null for the purposes of the nonnull attribute.
1871 if (const RecordType *UT = ArgExpr->getType()->getAsUnionType()) {
1872 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
1873 if (const CompoundLiteralExpr *CLE =
1874 dyn_cast<CompoundLiteralExpr>(ArgExpr))
1875 if (const InitListExpr *ILE =
1876 dyn_cast<InitListExpr>(CLE->getInitializer()))
1877 ArgExpr = ILE->getInit(0);
1878 }
1879
1880 bool Result;
1881 if (ArgExpr->EvaluateAsBooleanCondition(Result, Context) && !Result)
Nick Lewycky909a70d2011-03-25 01:44:32 +00001882 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001883 }
1884}
Ted Kremenekd30ef872009-01-12 23:09:09 +00001885
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001886Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
1887 return llvm::StringSwitch<FormatStringType>(Format->getType())
1888 .Case("scanf", FST_Scanf)
1889 .Cases("printf", "printf0", FST_Printf)
1890 .Cases("NSString", "CFString", FST_NSString)
1891 .Case("strftime", FST_Strftime)
1892 .Case("strfmon", FST_Strfmon)
1893 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
1894 .Default(FST_Unknown);
1895}
1896
Jordan Roseddcfbc92012-07-19 18:10:23 +00001897/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek826a3452010-07-16 02:11:22 +00001898/// functions) for correct use of format strings.
Richard Smith831421f2012-06-25 20:30:08 +00001899/// Returns true if a format string has been fully checked.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001900bool Sema::CheckFormatArguments(const FormatAttr *Format,
1901 ArrayRef<const Expr *> Args,
1902 bool IsCXXMember,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001903 VariadicCallType CallType,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001904 SourceLocation Loc, SourceRange Range) {
Richard Smith831421f2012-06-25 20:30:08 +00001905 FormatStringInfo FSI;
1906 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001907 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith831421f2012-06-25 20:30:08 +00001908 FSI.FirstDataArg, GetFormatStringType(Format),
Jordan Roseddcfbc92012-07-19 18:10:23 +00001909 CallType, Loc, Range);
Richard Smith831421f2012-06-25 20:30:08 +00001910 return false;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001911}
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001912
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001913bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001914 bool HasVAListArg, unsigned format_idx,
1915 unsigned firstDataArg, FormatStringType Type,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001916 VariadicCallType CallType,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001917 SourceLocation Loc, SourceRange Range) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001918 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001919 if (format_idx >= Args.size()) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001920 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith831421f2012-06-25 20:30:08 +00001921 return false;
Ted Kremenek71895b92007-08-14 17:39:48 +00001922 }
Mike Stump1eb44332009-09-09 15:08:12 +00001923
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001924 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001925
Chris Lattner59907c42007-08-10 20:18:51 +00001926 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001927 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001928 // Dynamically generated format strings are difficult to
1929 // automatically vet at compile time. Requiring that format strings
1930 // are string literals: (1) permits the checking of format strings by
1931 // the compiler and thereby (2) can practically remove the source of
1932 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001933
Mike Stump1eb44332009-09-09 15:08:12 +00001934 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001935 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001936 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001937 // the same format string checking logic for both ObjC and C strings.
Richard Smith831421f2012-06-25 20:30:08 +00001938 StringLiteralCheckType CT =
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001939 checkFormatStringExpr(OrigFormatExpr, Args, HasVAListArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001940 format_idx, firstDataArg, Type, CallType);
Richard Smith831421f2012-06-25 20:30:08 +00001941 if (CT != SLCT_NotALiteral)
1942 // Literal format string found, check done!
1943 return CT == SLCT_CheckedLiteral;
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001944
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00001945 // Strftime is particular as it always uses a single 'time' argument,
1946 // so it is safe to pass a non-literal string.
1947 if (Type == FST_Strftime)
Richard Smith831421f2012-06-25 20:30:08 +00001948 return false;
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00001949
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00001950 // Do not emit diag when the string param is a macro expansion and the
1951 // format is either NSString or CFString. This is a hack to prevent
1952 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
1953 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupasdc170202012-05-04 21:08:08 +00001954 if (Type == FST_NSString &&
1955 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith831421f2012-06-25 20:30:08 +00001956 return false;
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00001957
Chris Lattner655f1412009-04-29 04:59:47 +00001958 // If there are no arguments specified, warn with -Wformat-security, otherwise
1959 // warn only with -Wformat-nonliteral.
Eli Friedman2243e782013-06-18 18:10:01 +00001960 if (Args.size() == firstDataArg)
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001961 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001962 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00001963 << OrigFormatExpr->getSourceRange();
1964 else
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001965 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001966 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00001967 << OrigFormatExpr->getSourceRange();
Richard Smith831421f2012-06-25 20:30:08 +00001968 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001969}
Ted Kremenek71895b92007-08-14 17:39:48 +00001970
Ted Kremeneke0e53132010-01-28 23:39:18 +00001971namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00001972class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1973protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001974 Sema &S;
1975 const StringLiteral *FExpr;
1976 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001977 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001978 const unsigned NumDataArgs;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001979 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001980 const bool HasVAListArg;
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001981 ArrayRef<const Expr *> Args;
Ted Kremenek0d277352010-01-29 01:06:55 +00001982 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001983 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00001984 bool usesPositionalArgs;
1985 bool atFirstArg;
Richard Trieu55733de2011-10-28 00:41:25 +00001986 bool inFunctionCall;
Jordan Roseddcfbc92012-07-19 18:10:23 +00001987 Sema::VariadicCallType CallType;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001988public:
Ted Kremenek826a3452010-07-16 02:11:22 +00001989 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00001990 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00001991 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001992 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001993 unsigned formatIdx, bool inFunctionCall,
1994 Sema::VariadicCallType callType)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001995 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose50687312012-06-04 23:52:23 +00001996 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
1997 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001998 Args(Args), FormatIdx(formatIdx),
Richard Trieu55733de2011-10-28 00:41:25 +00001999 usesPositionalArgs(false), atFirstArg(true),
Jordan Roseddcfbc92012-07-19 18:10:23 +00002000 inFunctionCall(inFunctionCall), CallType(callType) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002001 CoveredArgs.resize(numDataArgs);
2002 CoveredArgs.reset();
2003 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002004
Ted Kremenek07d161f2010-01-29 01:50:07 +00002005 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002006
Ted Kremenek826a3452010-07-16 02:11:22 +00002007 void HandleIncompleteSpecifier(const char *startSpecifier,
2008 unsigned specifierLen);
Hans Wennborg76517422012-02-22 10:17:01 +00002009
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002010 void HandleInvalidLengthModifier(
2011 const analyze_format_string::FormatSpecifier &FS,
2012 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose8be066e2012-09-08 04:00:12 +00002013 const char *startSpecifier, unsigned specifierLen, unsigned DiagID);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002014
Hans Wennborg76517422012-02-22 10:17:01 +00002015 void HandleNonStandardLengthModifier(
Jordan Rose8be066e2012-09-08 04:00:12 +00002016 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborg76517422012-02-22 10:17:01 +00002017 const char *startSpecifier, unsigned specifierLen);
2018
2019 void HandleNonStandardConversionSpecifier(
2020 const analyze_format_string::ConversionSpecifier &CS,
2021 const char *startSpecifier, unsigned specifierLen);
2022
Hans Wennborgf8562642012-03-09 10:10:54 +00002023 virtual void HandlePosition(const char *startPos, unsigned posLen);
2024
Ted Kremenekefaff192010-02-27 01:41:03 +00002025 virtual void HandleInvalidPosition(const char *startSpecifier,
2026 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00002027 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00002028
2029 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
2030
Ted Kremeneke0e53132010-01-28 23:39:18 +00002031 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002032
Richard Trieu55733de2011-10-28 00:41:25 +00002033 template <typename Range>
2034 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2035 const Expr *ArgumentExpr,
2036 PartialDiagnostic PDiag,
2037 SourceLocation StringLoc,
2038 bool IsStringLocation, Range StringRange,
Dmitri Gribenko55431692013-05-05 00:41:58 +00002039 ArrayRef<FixItHint> Fixit = None);
Richard Trieu55733de2011-10-28 00:41:25 +00002040
Ted Kremenek826a3452010-07-16 02:11:22 +00002041protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002042 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2043 const char *startSpec,
2044 unsigned specifierLen,
2045 const char *csStart, unsigned csLen);
Richard Trieu55733de2011-10-28 00:41:25 +00002046
2047 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2048 const char *startSpec,
2049 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002050
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002051 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00002052 CharSourceRange getSpecifierRange(const char *startSpecifier,
2053 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002054 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002055
Ted Kremenek0d277352010-01-29 01:06:55 +00002056 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00002057
2058 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2059 const analyze_format_string::ConversionSpecifier &CS,
2060 const char *startSpecifier, unsigned specifierLen,
2061 unsigned argIndex);
Richard Trieu55733de2011-10-28 00:41:25 +00002062
2063 template <typename Range>
2064 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2065 bool IsStringLocation, Range StringRange,
Dmitri Gribenko55431692013-05-05 00:41:58 +00002066 ArrayRef<FixItHint> Fixit = None);
Richard Trieu55733de2011-10-28 00:41:25 +00002067
2068 void CheckPositionalAndNonpositionalArgs(
2069 const analyze_format_string::FormatSpecifier *FS);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002070};
2071}
2072
Ted Kremenek826a3452010-07-16 02:11:22 +00002073SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00002074 return OrigFormatExpr->getSourceRange();
2075}
2076
Ted Kremenek826a3452010-07-16 02:11:22 +00002077CharSourceRange CheckFormatHandler::
2078getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002079 SourceLocation Start = getLocationOfByte(startSpecifier);
2080 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2081
2082 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002083 End = End.getLocWithOffset(1);
Tom Care45f9b7e2010-06-21 21:21:01 +00002084
2085 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002086}
2087
Ted Kremenek826a3452010-07-16 02:11:22 +00002088SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002089 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002090}
2091
Ted Kremenek826a3452010-07-16 02:11:22 +00002092void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2093 unsigned specifierLen){
Richard Trieu55733de2011-10-28 00:41:25 +00002094 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2095 getLocationOfByte(startSpecifier),
2096 /*IsStringLocation*/true,
2097 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek808015a2010-01-29 03:16:21 +00002098}
2099
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002100void CheckFormatHandler::HandleInvalidLengthModifier(
2101 const analyze_format_string::FormatSpecifier &FS,
2102 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose8be066e2012-09-08 04:00:12 +00002103 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002104 using namespace analyze_format_string;
2105
2106 const LengthModifier &LM = FS.getLengthModifier();
2107 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2108
2109 // See if we know how to fix this length modifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002110 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002111 if (FixedLM) {
Jordan Rose8be066e2012-09-08 04:00:12 +00002112 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002113 getLocationOfByte(LM.getStart()),
2114 /*IsStringLocation*/true,
2115 getSpecifierRange(startSpecifier, specifierLen));
2116
2117 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2118 << FixedLM->toString()
2119 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2120
2121 } else {
Jordan Rose8be066e2012-09-08 04:00:12 +00002122 FixItHint Hint;
2123 if (DiagID == diag::warn_format_nonsensical_length)
2124 Hint = FixItHint::CreateRemoval(LMRange);
2125
2126 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002127 getLocationOfByte(LM.getStart()),
2128 /*IsStringLocation*/true,
2129 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose8be066e2012-09-08 04:00:12 +00002130 Hint);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002131 }
2132}
2133
Hans Wennborg76517422012-02-22 10:17:01 +00002134void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose8be066e2012-09-08 04:00:12 +00002135 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborg76517422012-02-22 10:17:01 +00002136 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose8be066e2012-09-08 04:00:12 +00002137 using namespace analyze_format_string;
2138
2139 const LengthModifier &LM = FS.getLengthModifier();
2140 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2141
2142 // See if we know how to fix this length modifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002143 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose8be066e2012-09-08 04:00:12 +00002144 if (FixedLM) {
2145 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2146 << LM.toString() << 0,
2147 getLocationOfByte(LM.getStart()),
2148 /*IsStringLocation*/true,
2149 getSpecifierRange(startSpecifier, specifierLen));
2150
2151 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2152 << FixedLM->toString()
2153 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2154
2155 } else {
2156 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2157 << LM.toString() << 0,
2158 getLocationOfByte(LM.getStart()),
2159 /*IsStringLocation*/true,
2160 getSpecifierRange(startSpecifier, specifierLen));
2161 }
Hans Wennborg76517422012-02-22 10:17:01 +00002162}
2163
2164void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2165 const analyze_format_string::ConversionSpecifier &CS,
2166 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose670941c2012-09-13 02:11:15 +00002167 using namespace analyze_format_string;
2168
2169 // See if we know how to fix this conversion specifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002170 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose670941c2012-09-13 02:11:15 +00002171 if (FixedCS) {
2172 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2173 << CS.toString() << /*conversion specifier*/1,
2174 getLocationOfByte(CS.getStart()),
2175 /*IsStringLocation*/true,
2176 getSpecifierRange(startSpecifier, specifierLen));
2177
2178 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2179 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2180 << FixedCS->toString()
2181 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2182 } else {
2183 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2184 << CS.toString() << /*conversion specifier*/1,
2185 getLocationOfByte(CS.getStart()),
2186 /*IsStringLocation*/true,
2187 getSpecifierRange(startSpecifier, specifierLen));
2188 }
Hans Wennborg76517422012-02-22 10:17:01 +00002189}
2190
Hans Wennborgf8562642012-03-09 10:10:54 +00002191void CheckFormatHandler::HandlePosition(const char *startPos,
2192 unsigned posLen) {
2193 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2194 getLocationOfByte(startPos),
2195 /*IsStringLocation*/true,
2196 getSpecifierRange(startPos, posLen));
2197}
2198
Ted Kremenekefaff192010-02-27 01:41:03 +00002199void
Ted Kremenek826a3452010-07-16 02:11:22 +00002200CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2201 analyze_format_string::PositionContext p) {
Richard Trieu55733de2011-10-28 00:41:25 +00002202 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2203 << (unsigned) p,
2204 getLocationOfByte(startPos), /*IsStringLocation*/true,
2205 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002206}
2207
Ted Kremenek826a3452010-07-16 02:11:22 +00002208void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00002209 unsigned posLen) {
Richard Trieu55733de2011-10-28 00:41:25 +00002210 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2211 getLocationOfByte(startPos),
2212 /*IsStringLocation*/true,
2213 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002214}
2215
Ted Kremenek826a3452010-07-16 02:11:22 +00002216void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose50687312012-06-04 23:52:23 +00002217 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0c069442011-03-15 21:18:48 +00002218 // The presence of a null character is likely an error.
Richard Trieu55733de2011-10-28 00:41:25 +00002219 EmitFormatDiagnostic(
2220 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2221 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2222 getFormatStringRange());
Ted Kremenek0c069442011-03-15 21:18:48 +00002223 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002224}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002225
Jordan Rose48716662012-07-19 18:10:08 +00002226// Note that this may return NULL if there was an error parsing or building
2227// one of the argument expressions.
Ted Kremenek826a3452010-07-16 02:11:22 +00002228const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002229 return Args[FirstDataArg + i];
Ted Kremenek826a3452010-07-16 02:11:22 +00002230}
2231
2232void CheckFormatHandler::DoneProcessing() {
2233 // Does the number of data arguments exceed the number of
2234 // format conversions in the format string?
2235 if (!HasVAListArg) {
2236 // Find any arguments that weren't covered.
2237 CoveredArgs.flip();
2238 signed notCoveredArg = CoveredArgs.find_first();
2239 if (notCoveredArg >= 0) {
2240 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose48716662012-07-19 18:10:08 +00002241 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2242 SourceLocation Loc = E->getLocStart();
2243 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2244 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2245 Loc, /*IsStringLocation*/false,
2246 getFormatStringRange());
2247 }
Bob Wilsonc03f2df2012-05-03 19:47:19 +00002248 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002249 }
2250 }
2251}
2252
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002253bool
2254CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2255 SourceLocation Loc,
2256 const char *startSpec,
2257 unsigned specifierLen,
2258 const char *csStart,
2259 unsigned csLen) {
2260
2261 bool keepGoing = true;
2262 if (argIndex < NumDataArgs) {
2263 // Consider the argument coverered, even though the specifier doesn't
2264 // make sense.
2265 CoveredArgs.set(argIndex);
2266 }
2267 else {
2268 // If argIndex exceeds the number of data arguments we
2269 // don't issue a warning because that is just a cascade of warnings (and
2270 // they may have intended '%%' anyway). We don't want to continue processing
2271 // the format string after this point, however, as we will like just get
2272 // gibberish when trying to match arguments.
2273 keepGoing = false;
2274 }
2275
Richard Trieu55733de2011-10-28 00:41:25 +00002276 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2277 << StringRef(csStart, csLen),
2278 Loc, /*IsStringLocation*/true,
2279 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002280
2281 return keepGoing;
2282}
2283
Richard Trieu55733de2011-10-28 00:41:25 +00002284void
2285CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2286 const char *startSpec,
2287 unsigned specifierLen) {
2288 EmitFormatDiagnostic(
2289 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2290 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2291}
2292
Ted Kremenek666a1972010-07-26 19:45:42 +00002293bool
2294CheckFormatHandler::CheckNumArgs(
2295 const analyze_format_string::FormatSpecifier &FS,
2296 const analyze_format_string::ConversionSpecifier &CS,
2297 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2298
2299 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002300 PartialDiagnostic PDiag = FS.usesPositionalArg()
2301 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2302 << (argIndex+1) << NumDataArgs)
2303 : S.PDiag(diag::warn_printf_insufficient_data_args);
2304 EmitFormatDiagnostic(
2305 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2306 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek666a1972010-07-26 19:45:42 +00002307 return false;
2308 }
2309 return true;
2310}
2311
Richard Trieu55733de2011-10-28 00:41:25 +00002312template<typename Range>
2313void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2314 SourceLocation Loc,
2315 bool IsStringLocation,
2316 Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002317 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002318 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu55733de2011-10-28 00:41:25 +00002319 Loc, IsStringLocation, StringRange, FixIt);
2320}
2321
2322/// \brief If the format string is not within the funcion call, emit a note
2323/// so that the function call and string are in diagnostic messages.
2324///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00002325/// \param InFunctionCall if true, the format string is within the function
Richard Trieu55733de2011-10-28 00:41:25 +00002326/// call and only one diagnostic message will be produced. Otherwise, an
2327/// extra note will be emitted pointing to location of the format string.
2328///
2329/// \param ArgumentExpr the expression that is passed as the format string
2330/// argument in the function call. Used for getting locations when two
2331/// diagnostics are emitted.
2332///
2333/// \param PDiag the callee should already have provided any strings for the
2334/// diagnostic message. This function only adds locations and fixits
2335/// to diagnostics.
2336///
2337/// \param Loc primary location for diagnostic. If two diagnostics are
2338/// required, one will be at Loc and a new SourceLocation will be created for
2339/// the other one.
2340///
2341/// \param IsStringLocation if true, Loc points to the format string should be
2342/// used for the note. Otherwise, Loc points to the argument list and will
2343/// be used with PDiag.
2344///
2345/// \param StringRange some or all of the string to highlight. This is
2346/// templated so it can accept either a CharSourceRange or a SourceRange.
2347///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00002348/// \param FixIt optional fix it hint for the format string.
Richard Trieu55733de2011-10-28 00:41:25 +00002349template<typename Range>
2350void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2351 const Expr *ArgumentExpr,
2352 PartialDiagnostic PDiag,
2353 SourceLocation Loc,
2354 bool IsStringLocation,
2355 Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002356 ArrayRef<FixItHint> FixIt) {
2357 if (InFunctionCall) {
2358 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2359 D << StringRange;
2360 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2361 I != E; ++I) {
2362 D << *I;
2363 }
2364 } else {
Richard Trieu55733de2011-10-28 00:41:25 +00002365 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2366 << ArgumentExpr->getSourceRange();
Jordan Roseec087352012-09-05 22:56:26 +00002367
2368 const Sema::SemaDiagnosticBuilder &Note =
2369 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2370 diag::note_format_string_defined);
2371
2372 Note << StringRange;
2373 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2374 I != E; ++I) {
2375 Note << *I;
2376 }
Richard Trieu55733de2011-10-28 00:41:25 +00002377 }
2378}
2379
Ted Kremenek826a3452010-07-16 02:11:22 +00002380//===--- CHECK: Printf format string checking ------------------------------===//
2381
2382namespace {
2383class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose50687312012-06-04 23:52:23 +00002384 bool ObjCContext;
Ted Kremenek826a3452010-07-16 02:11:22 +00002385public:
2386 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2387 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002388 unsigned numDataArgs, bool isObjC,
Ted Kremenek826a3452010-07-16 02:11:22 +00002389 const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002390 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002391 unsigned formatIdx, bool inFunctionCall,
2392 Sema::VariadicCallType CallType)
Ted Kremenek826a3452010-07-16 02:11:22 +00002393 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002394 numDataArgs, beg, hasVAListArg, Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002395 formatIdx, inFunctionCall, CallType), ObjCContext(isObjC)
2396 {}
2397
Ted Kremenek826a3452010-07-16 02:11:22 +00002398
2399 bool HandleInvalidPrintfConversionSpecifier(
2400 const analyze_printf::PrintfSpecifier &FS,
2401 const char *startSpecifier,
2402 unsigned specifierLen);
2403
2404 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2405 const char *startSpecifier,
2406 unsigned specifierLen);
Richard Smith831421f2012-06-25 20:30:08 +00002407 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2408 const char *StartSpecifier,
2409 unsigned SpecifierLen,
2410 const Expr *E);
2411
Ted Kremenek826a3452010-07-16 02:11:22 +00002412 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2413 const char *startSpecifier, unsigned specifierLen);
2414 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2415 const analyze_printf::OptionalAmount &Amt,
2416 unsigned type,
2417 const char *startSpecifier, unsigned specifierLen);
2418 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2419 const analyze_printf::OptionalFlag &flag,
2420 const char *startSpecifier, unsigned specifierLen);
2421 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2422 const analyze_printf::OptionalFlag &ignoredFlag,
2423 const analyze_printf::OptionalFlag &flag,
2424 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgf3749f42012-08-07 08:11:26 +00002425 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith831421f2012-06-25 20:30:08 +00002426 const Expr *E, const CharSourceRange &CSR);
2427
Ted Kremenek826a3452010-07-16 02:11:22 +00002428};
2429}
2430
2431bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2432 const analyze_printf::PrintfSpecifier &FS,
2433 const char *startSpecifier,
2434 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002435 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002436 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002437
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002438 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2439 getLocationOfByte(CS.getStart()),
2440 startSpecifier, specifierLen,
2441 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00002442}
2443
Ted Kremenek826a3452010-07-16 02:11:22 +00002444bool CheckPrintfHandler::HandleAmount(
2445 const analyze_format_string::OptionalAmount &Amt,
2446 unsigned k, const char *startSpecifier,
2447 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002448
2449 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002450 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002451 unsigned argIndex = Amt.getArgIndex();
2452 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002453 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2454 << k,
2455 getLocationOfByte(Amt.getStart()),
2456 /*IsStringLocation*/true,
2457 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002458 // Don't do any more checking. We will just emit
2459 // spurious errors.
2460 return false;
2461 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002462
Ted Kremenek0d277352010-01-29 01:06:55 +00002463 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00002464 // Although not in conformance with C99, we also allow the argument to be
2465 // an 'unsigned int' as that is a reasonably safe case. GCC also
2466 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002467 CoveredArgs.set(argIndex);
2468 const Expr *Arg = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00002469 if (!Arg)
2470 return false;
2471
Ted Kremenek0d277352010-01-29 01:06:55 +00002472 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002473
Hans Wennborgf3749f42012-08-07 08:11:26 +00002474 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
2475 assert(AT.isValid());
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002476
Hans Wennborgf3749f42012-08-07 08:11:26 +00002477 if (!AT.matchesType(S.Context, T)) {
Richard Trieu55733de2011-10-28 00:41:25 +00002478 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgf3749f42012-08-07 08:11:26 +00002479 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu55733de2011-10-28 00:41:25 +00002480 << T << Arg->getSourceRange(),
2481 getLocationOfByte(Amt.getStart()),
2482 /*IsStringLocation*/true,
2483 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002484 // Don't do any more checking. We will just emit
2485 // spurious errors.
2486 return false;
2487 }
2488 }
2489 }
2490 return true;
2491}
Ted Kremenek0d277352010-01-29 01:06:55 +00002492
Tom Caree4ee9662010-06-17 19:00:27 +00002493void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00002494 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002495 const analyze_printf::OptionalAmount &Amt,
2496 unsigned type,
2497 const char *startSpecifier,
2498 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002499 const analyze_printf::PrintfConversionSpecifier &CS =
2500 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00002501
Richard Trieu55733de2011-10-28 00:41:25 +00002502 FixItHint fixit =
2503 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2504 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2505 Amt.getConstantLength()))
2506 : FixItHint();
2507
2508 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2509 << type << CS.toString(),
2510 getLocationOfByte(Amt.getStart()),
2511 /*IsStringLocation*/true,
2512 getSpecifierRange(startSpecifier, specifierLen),
2513 fixit);
Tom Caree4ee9662010-06-17 19:00:27 +00002514}
2515
Ted Kremenek826a3452010-07-16 02:11:22 +00002516void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002517 const analyze_printf::OptionalFlag &flag,
2518 const char *startSpecifier,
2519 unsigned specifierLen) {
2520 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002521 const analyze_printf::PrintfConversionSpecifier &CS =
2522 FS.getConversionSpecifier();
Richard Trieu55733de2011-10-28 00:41:25 +00002523 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2524 << flag.toString() << CS.toString(),
2525 getLocationOfByte(flag.getPosition()),
2526 /*IsStringLocation*/true,
2527 getSpecifierRange(startSpecifier, specifierLen),
2528 FixItHint::CreateRemoval(
2529 getSpecifierRange(flag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002530}
2531
2532void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00002533 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002534 const analyze_printf::OptionalFlag &ignoredFlag,
2535 const analyze_printf::OptionalFlag &flag,
2536 const char *startSpecifier,
2537 unsigned specifierLen) {
2538 // Warn about ignored flag with a fixit removal.
Richard Trieu55733de2011-10-28 00:41:25 +00002539 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2540 << ignoredFlag.toString() << flag.toString(),
2541 getLocationOfByte(ignoredFlag.getPosition()),
2542 /*IsStringLocation*/true,
2543 getSpecifierRange(startSpecifier, specifierLen),
2544 FixItHint::CreateRemoval(
2545 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002546}
2547
Richard Smith831421f2012-06-25 20:30:08 +00002548// Determines if the specified is a C++ class or struct containing
2549// a member with the specified name and kind (e.g. a CXXMethodDecl named
2550// "c_str()").
2551template<typename MemberKind>
2552static llvm::SmallPtrSet<MemberKind*, 1>
2553CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2554 const RecordType *RT = Ty->getAs<RecordType>();
2555 llvm::SmallPtrSet<MemberKind*, 1> Results;
2556
2557 if (!RT)
2558 return Results;
2559 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
2560 if (!RD)
2561 return Results;
2562
2563 LookupResult R(S, &S.PP.getIdentifierTable().get(Name), SourceLocation(),
2564 Sema::LookupMemberName);
2565
2566 // We just need to include all members of the right kind turned up by the
2567 // filter, at this point.
2568 if (S.LookupQualifiedName(R, RT->getDecl()))
2569 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2570 NamedDecl *decl = (*I)->getUnderlyingDecl();
2571 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
2572 Results.insert(FK);
2573 }
2574 return Results;
2575}
2576
2577// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgf3749f42012-08-07 08:11:26 +00002578// better diagnostic if so. AT is assumed to be valid.
Richard Smith831421f2012-06-25 20:30:08 +00002579// Returns true when a c_str() conversion method is found.
2580bool CheckPrintfHandler::checkForCStrMembers(
Hans Wennborgf3749f42012-08-07 08:11:26 +00002581 const analyze_printf::ArgType &AT, const Expr *E,
Richard Smith831421f2012-06-25 20:30:08 +00002582 const CharSourceRange &CSR) {
2583 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2584
2585 MethodSet Results =
2586 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
2587
2588 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2589 MI != ME; ++MI) {
2590 const CXXMethodDecl *Method = *MI;
2591 if (Method->getNumParams() == 0 &&
Hans Wennborgf3749f42012-08-07 08:11:26 +00002592 AT.matchesType(S.Context, Method->getResultType())) {
Richard Smith831421f2012-06-25 20:30:08 +00002593 // FIXME: Suggest parens if the expression needs them.
2594 SourceLocation EndLoc =
2595 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd());
2596 S.Diag(E->getLocStart(), diag::note_printf_c_str)
2597 << "c_str()"
2598 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
2599 return true;
2600 }
2601 }
2602
2603 return false;
2604}
2605
Ted Kremeneke0e53132010-01-28 23:39:18 +00002606bool
Ted Kremenek826a3452010-07-16 02:11:22 +00002607CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002608 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00002609 const char *startSpecifier,
2610 unsigned specifierLen) {
2611
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002612 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00002613 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002614 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00002615
Ted Kremenekbaa40062010-07-19 22:01:06 +00002616 if (FS.consumesDataArgument()) {
2617 if (atFirstArg) {
2618 atFirstArg = false;
2619 usesPositionalArgs = FS.usesPositionalArg();
2620 }
2621 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002622 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2623 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002624 return false;
2625 }
Ted Kremenek0d277352010-01-29 01:06:55 +00002626 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002627
Ted Kremenekefaff192010-02-27 01:41:03 +00002628 // First check if the field width, precision, and conversion specifier
2629 // have matching data arguments.
2630 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2631 startSpecifier, specifierLen)) {
2632 return false;
2633 }
2634
2635 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2636 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002637 return false;
2638 }
2639
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002640 if (!CS.consumesDataArgument()) {
2641 // FIXME: Technically specifying a precision or field width here
2642 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002643 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002644 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002645
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002646 // Consume the argument.
2647 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00002648 if (argIndex < NumDataArgs) {
2649 // The check to see if the argIndex is valid will come later.
2650 // We set the bit here because we may exit early from this
2651 // function if we encounter some other error.
2652 CoveredArgs.set(argIndex);
2653 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002654
2655 // Check for using an Objective-C specific conversion specifier
2656 // in a non-ObjC literal.
Jordan Rose50687312012-06-04 23:52:23 +00002657 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002658 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2659 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002660 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002661
Tom Caree4ee9662010-06-17 19:00:27 +00002662 // Check for invalid use of field width
2663 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002664 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00002665 startSpecifier, specifierLen);
2666 }
2667
2668 // Check for invalid use of precision
2669 if (!FS.hasValidPrecision()) {
2670 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
2671 startSpecifier, specifierLen);
2672 }
2673
2674 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00002675 if (!FS.hasValidThousandsGroupingPrefix())
2676 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002677 if (!FS.hasValidLeadingZeros())
2678 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
2679 if (!FS.hasValidPlusPrefix())
2680 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00002681 if (!FS.hasValidSpacePrefix())
2682 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002683 if (!FS.hasValidAlternativeForm())
2684 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
2685 if (!FS.hasValidLeftJustified())
2686 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
2687
2688 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00002689 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
2690 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
2691 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002692 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
2693 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
2694 startSpecifier, specifierLen);
2695
2696 // Check the length modifier is valid with the given conversion specifier.
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002697 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose8be066e2012-09-08 04:00:12 +00002698 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
2699 diag::warn_format_nonsensical_length);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002700 else if (!FS.hasStandardLengthModifier())
Jordan Rose8be066e2012-09-08 04:00:12 +00002701 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002702 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose8be066e2012-09-08 04:00:12 +00002703 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
2704 diag::warn_format_non_standard_conversion_spec);
Tom Caree4ee9662010-06-17 19:00:27 +00002705
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002706 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
2707 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
2708
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002709 // The remaining checks depend on the data arguments.
2710 if (HasVAListArg)
2711 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002712
Ted Kremenek666a1972010-07-26 19:45:42 +00002713 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002714 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002715
Jordan Rose48716662012-07-19 18:10:08 +00002716 const Expr *Arg = getDataArg(argIndex);
2717 if (!Arg)
2718 return true;
2719
2720 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith831421f2012-06-25 20:30:08 +00002721}
2722
Jordan Roseec087352012-09-05 22:56:26 +00002723static bool requiresParensToAddCast(const Expr *E) {
2724 // FIXME: We should have a general way to reason about operator
2725 // precedence and whether parens are actually needed here.
2726 // Take care of a few common cases where they aren't.
2727 const Expr *Inside = E->IgnoreImpCasts();
2728 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
2729 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
2730
2731 switch (Inside->getStmtClass()) {
2732 case Stmt::ArraySubscriptExprClass:
2733 case Stmt::CallExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00002734 case Stmt::CharacterLiteralClass:
2735 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00002736 case Stmt::DeclRefExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00002737 case Stmt::FloatingLiteralClass:
2738 case Stmt::IntegerLiteralClass:
Jordan Roseec087352012-09-05 22:56:26 +00002739 case Stmt::MemberExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00002740 case Stmt::ObjCArrayLiteralClass:
2741 case Stmt::ObjCBoolLiteralExprClass:
2742 case Stmt::ObjCBoxedExprClass:
2743 case Stmt::ObjCDictionaryLiteralClass:
2744 case Stmt::ObjCEncodeExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00002745 case Stmt::ObjCIvarRefExprClass:
2746 case Stmt::ObjCMessageExprClass:
2747 case Stmt::ObjCPropertyRefExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00002748 case Stmt::ObjCStringLiteralClass:
2749 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00002750 case Stmt::ParenExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00002751 case Stmt::StringLiteralClass:
Jordan Roseec087352012-09-05 22:56:26 +00002752 case Stmt::UnaryOperatorClass:
2753 return false;
2754 default:
2755 return true;
2756 }
2757}
2758
Richard Smith831421f2012-06-25 20:30:08 +00002759bool
2760CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2761 const char *StartSpecifier,
2762 unsigned SpecifierLen,
2763 const Expr *E) {
2764 using namespace analyze_format_string;
2765 using namespace analyze_printf;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002766 // Now type check the data expression that matches the
2767 // format specifier.
Hans Wennborgf3749f42012-08-07 08:11:26 +00002768 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
2769 ObjCContext);
Jordan Rose614a8652012-09-05 22:56:19 +00002770 if (!AT.isValid())
2771 return true;
Jordan Roseec087352012-09-05 22:56:26 +00002772
Jordan Rose448ac3e2012-12-05 18:44:40 +00002773 QualType ExprTy = E->getType();
Ted Kremenek02be9682013-04-10 06:26:26 +00002774 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
2775 ExprTy = TET->getUnderlyingExpr()->getType();
2776 }
2777
Jordan Rose448ac3e2012-12-05 18:44:40 +00002778 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose614a8652012-09-05 22:56:19 +00002779 return true;
Jordan Roseee0259d2012-06-04 22:48:57 +00002780
Jordan Rose614a8652012-09-05 22:56:19 +00002781 // Look through argument promotions for our error message's reported type.
2782 // This includes the integral and floating promotions, but excludes array
2783 // and function pointer decay; seeing that an argument intended to be a
2784 // string has type 'char [6]' is probably more confusing than 'char *'.
2785 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2786 if (ICE->getCastKind() == CK_IntegralCast ||
2787 ICE->getCastKind() == CK_FloatingCast) {
2788 E = ICE->getSubExpr();
Jordan Rose448ac3e2012-12-05 18:44:40 +00002789 ExprTy = E->getType();
Jordan Rose614a8652012-09-05 22:56:19 +00002790
2791 // Check if we didn't match because of an implicit cast from a 'char'
2792 // or 'short' to an 'int'. This is done because printf is a varargs
2793 // function.
2794 if (ICE->getType() == S.Context.IntTy ||
2795 ICE->getType() == S.Context.UnsignedIntTy) {
2796 // All further checking is done on the subexpression.
Jordan Rose448ac3e2012-12-05 18:44:40 +00002797 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose614a8652012-09-05 22:56:19 +00002798 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00002799 }
Jordan Roseee0259d2012-06-04 22:48:57 +00002800 }
Jordan Rose448ac3e2012-12-05 18:44:40 +00002801 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
2802 // Special case for 'a', which has type 'int' in C.
2803 // Note, however, that we do /not/ want to treat multibyte constants like
2804 // 'MooV' as characters! This form is deprecated but still exists.
2805 if (ExprTy == S.Context.IntTy)
2806 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
2807 ExprTy = S.Context.CharTy;
Jordan Rose614a8652012-09-05 22:56:19 +00002808 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002809
Jordan Rose2cd34402012-12-05 18:44:49 +00002810 // %C in an Objective-C context prints a unichar, not a wchar_t.
2811 // If the argument is an integer of some kind, believe the %C and suggest
2812 // a cast instead of changing the conversion specifier.
Jordan Rose448ac3e2012-12-05 18:44:40 +00002813 QualType IntendedTy = ExprTy;
Jordan Rose2cd34402012-12-05 18:44:49 +00002814 if (ObjCContext &&
2815 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
2816 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
2817 !ExprTy->isCharType()) {
2818 // 'unichar' is defined as a typedef of unsigned short, but we should
2819 // prefer using the typedef if it is visible.
2820 IntendedTy = S.Context.UnsignedShortTy;
2821
2822 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
2823 Sema::LookupOrdinaryName);
2824 if (S.LookupName(Result, S.getCurScope())) {
2825 NamedDecl *ND = Result.getFoundDecl();
2826 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
2827 if (TD->getUnderlyingType() == IntendedTy)
2828 IntendedTy = S.Context.getTypedefType(TD);
2829 }
2830 }
2831 }
2832
2833 // Special-case some of Darwin's platform-independence types by suggesting
2834 // casts to primitive types that are known to be large enough.
2835 bool ShouldNotPrintDirectly = false;
Jordan Roseec087352012-09-05 22:56:26 +00002836 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Ted Kremenek6edb0292013-03-25 22:28:37 +00002837 // Use a 'while' to peel off layers of typedefs.
2838 QualType TyTy = IntendedTy;
2839 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
Jordan Roseec087352012-09-05 22:56:26 +00002840 StringRef Name = UserTy->getDecl()->getName();
Jordan Rose2cd34402012-12-05 18:44:49 +00002841 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Jordan Roseec087352012-09-05 22:56:26 +00002842 .Case("NSInteger", S.Context.LongTy)
2843 .Case("NSUInteger", S.Context.UnsignedLongTy)
2844 .Case("SInt32", S.Context.IntTy)
2845 .Case("UInt32", S.Context.UnsignedIntTy)
Jordan Rose2cd34402012-12-05 18:44:49 +00002846 .Default(QualType());
2847
2848 if (!CastTy.isNull()) {
2849 ShouldNotPrintDirectly = true;
2850 IntendedTy = CastTy;
Ted Kremenek6edb0292013-03-25 22:28:37 +00002851 break;
Jordan Rose2cd34402012-12-05 18:44:49 +00002852 }
Ted Kremenek6edb0292013-03-25 22:28:37 +00002853 TyTy = UserTy->desugar();
Jordan Roseec087352012-09-05 22:56:26 +00002854 }
2855 }
2856
Jordan Rose614a8652012-09-05 22:56:19 +00002857 // We may be able to offer a FixItHint if it is a supported type.
2858 PrintfSpecifier fixedFS = FS;
Jordan Roseec087352012-09-05 22:56:26 +00002859 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose614a8652012-09-05 22:56:19 +00002860 S.Context, ObjCContext);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002861
Jordan Rose614a8652012-09-05 22:56:19 +00002862 if (success) {
2863 // Get the fix string from the fixed format specifier
2864 SmallString<16> buf;
2865 llvm::raw_svector_ostream os(buf);
2866 fixedFS.toString(os);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002867
Jordan Roseec087352012-09-05 22:56:26 +00002868 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
2869
Jordan Rose2cd34402012-12-05 18:44:49 +00002870 if (IntendedTy == ExprTy) {
2871 // In this case, the specifier is wrong and should be changed to match
2872 // the argument.
2873 EmitFormatDiagnostic(
2874 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2875 << AT.getRepresentativeTypeName(S.Context) << IntendedTy
2876 << E->getSourceRange(),
2877 E->getLocStart(),
2878 /*IsStringLocation*/false,
2879 SpecRange,
2880 FixItHint::CreateReplacement(SpecRange, os.str()));
2881
2882 } else {
Jordan Roseec087352012-09-05 22:56:26 +00002883 // The canonical type for formatting this value is different from the
2884 // actual type of the expression. (This occurs, for example, with Darwin's
2885 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
2886 // should be printed as 'long' for 64-bit compatibility.)
2887 // Rather than emitting a normal format/argument mismatch, we want to
2888 // add a cast to the recommended type (and correct the format string
2889 // if necessary).
2890 SmallString<16> CastBuf;
2891 llvm::raw_svector_ostream CastFix(CastBuf);
2892 CastFix << "(";
2893 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
2894 CastFix << ")";
2895
2896 SmallVector<FixItHint,4> Hints;
2897 if (!AT.matchesType(S.Context, IntendedTy))
2898 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
2899
2900 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
2901 // If there's already a cast present, just replace it.
2902 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
2903 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
2904
2905 } else if (!requiresParensToAddCast(E)) {
2906 // If the expression has high enough precedence,
2907 // just write the C-style cast.
2908 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
2909 CastFix.str()));
2910 } else {
2911 // Otherwise, add parens around the expression as well as the cast.
2912 CastFix << "(";
2913 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
2914 CastFix.str()));
2915
2916 SourceLocation After = S.PP.getLocForEndOfToken(E->getLocEnd());
2917 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
2918 }
2919
Jordan Rose2cd34402012-12-05 18:44:49 +00002920 if (ShouldNotPrintDirectly) {
2921 // The expression has a type that should not be printed directly.
2922 // We extract the name from the typedef because we don't want to show
2923 // the underlying type in the diagnostic.
2924 StringRef Name = cast<TypedefType>(ExprTy)->getDecl()->getName();
Jordan Roseec087352012-09-05 22:56:26 +00002925
Jordan Rose2cd34402012-12-05 18:44:49 +00002926 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
2927 << Name << IntendedTy
2928 << E->getSourceRange(),
2929 E->getLocStart(), /*IsStringLocation=*/false,
2930 SpecRange, Hints);
2931 } else {
2932 // In this case, the expression could be printed using a different
2933 // specifier, but we've decided that the specifier is probably correct
2934 // and we should cast instead. Just use the normal warning message.
2935 EmitFormatDiagnostic(
2936 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2937 << AT.getRepresentativeTypeName(S.Context) << ExprTy
2938 << E->getSourceRange(),
2939 E->getLocStart(), /*IsStringLocation*/false,
2940 SpecRange, Hints);
2941 }
Jordan Roseec087352012-09-05 22:56:26 +00002942 }
Jordan Rose614a8652012-09-05 22:56:19 +00002943 } else {
2944 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
2945 SpecifierLen);
2946 // Since the warning for passing non-POD types to variadic functions
2947 // was deferred until now, we emit a warning for non-POD
2948 // arguments here.
Jordan Rose448ac3e2012-12-05 18:44:40 +00002949 if (S.isValidVarArgType(ExprTy) == Sema::VAK_Invalid) {
Jordan Rose614a8652012-09-05 22:56:19 +00002950 unsigned DiagKind;
Jordan Rose448ac3e2012-12-05 18:44:40 +00002951 if (ExprTy->isObjCObjectType())
Jordan Rose614a8652012-09-05 22:56:19 +00002952 DiagKind = diag::err_cannot_pass_objc_interface_to_vararg_format;
2953 else
2954 DiagKind = diag::warn_non_pod_vararg_with_format_string;
2955
2956 EmitFormatDiagnostic(
2957 S.PDiag(DiagKind)
Richard Smith80ad52f2013-01-02 11:42:31 +00002958 << S.getLangOpts().CPlusPlus11
Jordan Rose448ac3e2012-12-05 18:44:40 +00002959 << ExprTy
Jordan Rose614a8652012-09-05 22:56:19 +00002960 << CallType
2961 << AT.getRepresentativeTypeName(S.Context)
2962 << CSR
2963 << E->getSourceRange(),
2964 E->getLocStart(), /*IsStringLocation*/false, CSR);
2965
2966 checkForCStrMembers(AT, E, CSR);
2967 } else
Richard Trieu55733de2011-10-28 00:41:25 +00002968 EmitFormatDiagnostic(
2969 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Jordan Rose448ac3e2012-12-05 18:44:40 +00002970 << AT.getRepresentativeTypeName(S.Context) << ExprTy
Jordan Rose614a8652012-09-05 22:56:19 +00002971 << CSR
Richard Smith831421f2012-06-25 20:30:08 +00002972 << E->getSourceRange(),
Jordan Rose614a8652012-09-05 22:56:19 +00002973 E->getLocStart(), /*IsStringLocation*/false, CSR);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002974 }
2975
Ted Kremeneke0e53132010-01-28 23:39:18 +00002976 return true;
2977}
2978
Ted Kremenek826a3452010-07-16 02:11:22 +00002979//===--- CHECK: Scanf format string checking ------------------------------===//
2980
2981namespace {
2982class CheckScanfHandler : public CheckFormatHandler {
2983public:
2984 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
2985 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002986 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002987 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002988 unsigned formatIdx, bool inFunctionCall,
2989 Sema::VariadicCallType CallType)
Ted Kremenek826a3452010-07-16 02:11:22 +00002990 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002991 numDataArgs, beg, hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002992 Args, formatIdx, inFunctionCall, CallType)
Jordan Roseddcfbc92012-07-19 18:10:23 +00002993 {}
Ted Kremenek826a3452010-07-16 02:11:22 +00002994
2995 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
2996 const char *startSpecifier,
2997 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002998
2999 bool HandleInvalidScanfConversionSpecifier(
3000 const analyze_scanf::ScanfSpecifier &FS,
3001 const char *startSpecifier,
3002 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00003003
3004 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00003005};
Ted Kremenek07d161f2010-01-29 01:50:07 +00003006}
Ted Kremeneke0e53132010-01-28 23:39:18 +00003007
Ted Kremenekb7c21012010-07-16 18:28:03 +00003008void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3009 const char *end) {
Richard Trieu55733de2011-10-28 00:41:25 +00003010 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3011 getLocationOfByte(end), /*IsStringLocation*/true,
3012 getSpecifierRange(start, end - start));
Ted Kremenekb7c21012010-07-16 18:28:03 +00003013}
3014
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003015bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3016 const analyze_scanf::ScanfSpecifier &FS,
3017 const char *startSpecifier,
3018 unsigned specifierLen) {
3019
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003020 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003021 FS.getConversionSpecifier();
3022
3023 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3024 getLocationOfByte(CS.getStart()),
3025 startSpecifier, specifierLen,
3026 CS.getStart(), CS.getLength());
3027}
3028
Ted Kremenek826a3452010-07-16 02:11:22 +00003029bool CheckScanfHandler::HandleScanfSpecifier(
3030 const analyze_scanf::ScanfSpecifier &FS,
3031 const char *startSpecifier,
3032 unsigned specifierLen) {
3033
3034 using namespace analyze_scanf;
3035 using namespace analyze_format_string;
3036
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003037 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00003038
Ted Kremenekbaa40062010-07-19 22:01:06 +00003039 // Handle case where '%' and '*' don't consume an argument. These shouldn't
3040 // be used to decide if we are using positional arguments consistently.
3041 if (FS.consumesDataArgument()) {
3042 if (atFirstArg) {
3043 atFirstArg = false;
3044 usesPositionalArgs = FS.usesPositionalArg();
3045 }
3046 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00003047 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3048 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00003049 return false;
3050 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003051 }
3052
3053 // Check if the field with is non-zero.
3054 const OptionalAmount &Amt = FS.getFieldWidth();
3055 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3056 if (Amt.getConstantAmount() == 0) {
3057 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3058 Amt.getConstantLength());
Richard Trieu55733de2011-10-28 00:41:25 +00003059 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3060 getLocationOfByte(Amt.getStart()),
3061 /*IsStringLocation*/true, R,
3062 FixItHint::CreateRemoval(R));
Ted Kremenek826a3452010-07-16 02:11:22 +00003063 }
3064 }
3065
3066 if (!FS.consumesDataArgument()) {
3067 // FIXME: Technically specifying a precision or field width here
3068 // makes no sense. Worth issuing a warning at some point.
3069 return true;
3070 }
3071
3072 // Consume the argument.
3073 unsigned argIndex = FS.getArgIndex();
3074 if (argIndex < NumDataArgs) {
3075 // The check to see if the argIndex is valid will come later.
3076 // We set the bit here because we may exit early from this
3077 // function if we encounter some other error.
3078 CoveredArgs.set(argIndex);
3079 }
3080
Ted Kremenek1e51c202010-07-20 20:04:47 +00003081 // Check the length modifier is valid with the given conversion specifier.
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003082 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose8be066e2012-09-08 04:00:12 +00003083 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3084 diag::warn_format_nonsensical_length);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003085 else if (!FS.hasStandardLengthModifier())
Jordan Rose8be066e2012-09-08 04:00:12 +00003086 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003087 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose8be066e2012-09-08 04:00:12 +00003088 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3089 diag::warn_format_non_standard_conversion_spec);
Hans Wennborg76517422012-02-22 10:17:01 +00003090
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003091 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3092 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3093
Ted Kremenek826a3452010-07-16 02:11:22 +00003094 // The remaining checks depend on the data arguments.
3095 if (HasVAListArg)
3096 return true;
3097
Ted Kremenek666a1972010-07-26 19:45:42 +00003098 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00003099 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00003100
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003101 // Check that the argument type matches the format specifier.
3102 const Expr *Ex = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00003103 if (!Ex)
3104 return true;
3105
Hans Wennborg58e1e542012-08-07 08:59:46 +00003106 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3107 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003108 ScanfSpecifier fixedFS = FS;
David Blaikie4e4d0842012-03-11 07:00:24 +00003109 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
Hans Wennborgbe6126a2012-02-15 09:59:46 +00003110 S.Context);
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003111
3112 if (success) {
3113 // Get the fix string from the fixed format specifier.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003114 SmallString<128> buf;
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003115 llvm::raw_svector_ostream os(buf);
3116 fixedFS.toString(os);
3117
3118 EmitFormatDiagnostic(
3119 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg58e1e542012-08-07 08:59:46 +00003120 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003121 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00003122 Ex->getLocStart(),
3123 /*IsStringLocation*/false,
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003124 getSpecifierRange(startSpecifier, specifierLen),
3125 FixItHint::CreateReplacement(
3126 getSpecifierRange(startSpecifier, specifierLen),
3127 os.str()));
3128 } else {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003129 EmitFormatDiagnostic(
3130 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg58e1e542012-08-07 08:59:46 +00003131 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003132 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00003133 Ex->getLocStart(),
3134 /*IsStringLocation*/false,
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003135 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003136 }
3137 }
3138
Ted Kremenek826a3452010-07-16 02:11:22 +00003139 return true;
3140}
3141
3142void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00003143 const Expr *OrigFormatExpr,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003144 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003145 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003146 unsigned firstDataArg, FormatStringType Type,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003147 bool inFunctionCall, VariadicCallType CallType) {
Ted Kremenek826a3452010-07-16 02:11:22 +00003148
Ted Kremeneke0e53132010-01-28 23:39:18 +00003149 // CHECK: is the format string a wide literal?
Richard Smithdf9ef1b2012-06-13 05:37:23 +00003150 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu55733de2011-10-28 00:41:25 +00003151 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003152 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00003153 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3154 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00003155 return;
3156 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003157
Ted Kremeneke0e53132010-01-28 23:39:18 +00003158 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner5f9e2722011-07-23 10:55:15 +00003159 StringRef StrRef = FExpr->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00003160 const char *Str = StrRef.data();
3161 unsigned StrLen = StrRef.size();
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003162 const unsigned numDataArgs = Args.size() - firstDataArg;
Ted Kremenek826a3452010-07-16 02:11:22 +00003163
Ted Kremeneke0e53132010-01-28 23:39:18 +00003164 // CHECK: empty format string?
Ted Kremenek4cd57912011-09-29 05:52:16 +00003165 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu55733de2011-10-28 00:41:25 +00003166 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003167 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00003168 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3169 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00003170 return;
3171 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003172
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003173 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek826a3452010-07-16 02:11:22 +00003174 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00003175 numDataArgs, (Type == FST_NSString),
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003176 Str, HasVAListArg, Args, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003177 inFunctionCall, CallType);
Ted Kremenek826a3452010-07-16 02:11:22 +00003178
Hans Wennborgd02deeb2011-12-15 10:25:47 +00003179 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose275b6f52012-09-13 02:11:03 +00003180 getLangOpts(),
3181 Context.getTargetInfo()))
Ted Kremenek826a3452010-07-16 02:11:22 +00003182 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003183 } else if (Type == FST_Scanf) {
Jordan Rose50687312012-06-04 23:52:23 +00003184 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003185 Str, HasVAListArg, Args, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003186 inFunctionCall, CallType);
Ted Kremenek826a3452010-07-16 02:11:22 +00003187
Hans Wennborgd02deeb2011-12-15 10:25:47 +00003188 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose275b6f52012-09-13 02:11:03 +00003189 getLangOpts(),
3190 Context.getTargetInfo()))
Ted Kremenek826a3452010-07-16 02:11:22 +00003191 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003192 } // TODO: handle other formats
Ted Kremenekce7024e2010-01-28 01:18:22 +00003193}
3194
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003195//===--- CHECK: Standard memory functions ---------------------------------===//
3196
Douglas Gregor2a053a32011-05-03 20:05:22 +00003197/// \brief Determine whether the given type is a dynamic class type (e.g.,
3198/// whether it has a vtable).
3199static bool isDynamicClassType(QualType T) {
3200 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3201 if (CXXRecordDecl *Definition = Record->getDefinition())
3202 if (Definition->isDynamicClass())
3203 return true;
3204
3205 return false;
3206}
3207
Chandler Carrutha72a12f2011-06-21 23:04:20 +00003208/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth000d4282011-06-16 09:09:40 +00003209/// otherwise returns NULL.
3210static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Webere4a1c642011-06-14 16:14:58 +00003211 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth000d4282011-06-16 09:09:40 +00003212 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3213 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
3214 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00003215
Chandler Carruth000d4282011-06-16 09:09:40 +00003216 return 0;
3217}
3218
Chandler Carrutha72a12f2011-06-21 23:04:20 +00003219/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth000d4282011-06-16 09:09:40 +00003220static QualType getSizeOfArgType(const Expr* E) {
3221 if (const UnaryExprOrTypeTraitExpr *SizeOf =
3222 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3223 if (SizeOf->getKind() == clang::UETT_SizeOf)
3224 return SizeOf->getTypeOfArgument();
3225
3226 return QualType();
Nico Webere4a1c642011-06-14 16:14:58 +00003227}
3228
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003229/// \brief Check for dangerous or invalid arguments to memset().
3230///
Chandler Carruth929f0132011-06-03 06:23:57 +00003231/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003232/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
3233/// function calls.
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003234///
3235/// \param Call The call expression to diagnose.
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003236void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks0a151a12012-01-17 00:37:07 +00003237 unsigned BId,
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003238 IdentifierInfo *FnName) {
Anna Zaks0a151a12012-01-17 00:37:07 +00003239 assert(BId != 0);
3240
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00003241 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor707a23e2011-06-16 17:56:04 +00003242 // we have enough arguments, and if not, abort further checking.
Anna Zaks0a151a12012-01-17 00:37:07 +00003243 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Webercda57822011-10-13 22:30:23 +00003244 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00003245 return;
3246
Anna Zaks0a151a12012-01-17 00:37:07 +00003247 unsigned LastArg = (BId == Builtin::BImemset ||
3248 BId == Builtin::BIstrndup ? 1 : 2);
3249 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Webercda57822011-10-13 22:30:23 +00003250 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth000d4282011-06-16 09:09:40 +00003251
3252 // We have special checking when the length is a sizeof expression.
3253 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
3254 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
3255 llvm::FoldingSetNodeID SizeOfArgID;
3256
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003257 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
3258 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00003259 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003260
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003261 QualType DestTy = Dest->getType();
3262 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
3263 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00003264
Chandler Carruth000d4282011-06-16 09:09:40 +00003265 // Never warn about void type pointers. This can be used to suppress
3266 // false positives.
3267 if (PointeeTy->isVoidType())
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003268 continue;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003269
Chandler Carruth000d4282011-06-16 09:09:40 +00003270 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
3271 // actually comparing the expressions for equality. Because computing the
3272 // expression IDs can be expensive, we only do this if the diagnostic is
3273 // enabled.
3274 if (SizeOfArg &&
3275 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
3276 SizeOfArg->getExprLoc())) {
3277 // We only compute IDs for expressions if the warning is enabled, and
3278 // cache the sizeof arg's ID.
3279 if (SizeOfArgID == llvm::FoldingSetNodeID())
3280 SizeOfArg->Profile(SizeOfArgID, Context, true);
3281 llvm::FoldingSetNodeID DestID;
3282 Dest->Profile(DestID, Context, true);
3283 if (DestID == SizeOfArgID) {
Nico Webercda57822011-10-13 22:30:23 +00003284 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
3285 // over sizeof(src) as well.
Chandler Carruth000d4282011-06-16 09:09:40 +00003286 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks6fcb3722012-05-30 00:34:21 +00003287 StringRef ReadableName = FnName->getName();
3288
Chandler Carruth000d4282011-06-16 09:09:40 +00003289 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaks90c78322012-05-30 23:14:52 +00003290 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth000d4282011-06-16 09:09:40 +00003291 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian7adf4172013-01-30 01:12:44 +00003292 if (!PointeeTy->isIncompleteType() &&
3293 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth000d4282011-06-16 09:09:40 +00003294 ActionIdx = 2; // If the pointee's size is sizeof(char),
3295 // suggest an explicit length.
Anna Zaks6fcb3722012-05-30 00:34:21 +00003296
3297 // If the function is defined as a builtin macro, do not show macro
3298 // expansion.
3299 SourceLocation SL = SizeOfArg->getExprLoc();
3300 SourceRange DSR = Dest->getSourceRange();
3301 SourceRange SSR = SizeOfArg->getSourceRange();
3302 SourceManager &SM = PP.getSourceManager();
3303
3304 if (SM.isMacroArgExpansion(SL)) {
3305 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
3306 SL = SM.getSpellingLoc(SL);
3307 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
3308 SM.getSpellingLoc(DSR.getEnd()));
3309 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
3310 SM.getSpellingLoc(SSR.getEnd()));
3311 }
3312
Anna Zaks90c78322012-05-30 23:14:52 +00003313 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth000d4282011-06-16 09:09:40 +00003314 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks6fcb3722012-05-30 00:34:21 +00003315 << ReadableName
Anna Zaks90c78322012-05-30 23:14:52 +00003316 << PointeeTy
3317 << DestTy
Anna Zaks6fcb3722012-05-30 00:34:21 +00003318 << DSR
Anna Zaks90c78322012-05-30 23:14:52 +00003319 << SSR);
3320 DiagRuntimeBehavior(SL, SizeOfArg,
3321 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
3322 << ActionIdx
3323 << SSR);
3324
Chandler Carruth000d4282011-06-16 09:09:40 +00003325 break;
3326 }
3327 }
3328
3329 // Also check for cases where the sizeof argument is the exact same
3330 // type as the memory argument, and where it points to a user-defined
3331 // record type.
3332 if (SizeOfArgTy != QualType()) {
3333 if (PointeeTy->isRecordType() &&
3334 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
3335 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
3336 PDiag(diag::warn_sizeof_pointer_type_memaccess)
3337 << FnName << SizeOfArgTy << ArgIdx
3338 << PointeeTy << Dest->getSourceRange()
3339 << LenExpr->getSourceRange());
3340 break;
3341 }
Nico Webere4a1c642011-06-14 16:14:58 +00003342 }
3343
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003344 // Always complain about dynamic classes.
Anna Zaks0a151a12012-01-17 00:37:07 +00003345 if (isDynamicClassType(PointeeTy)) {
3346
3347 unsigned OperationType = 0;
3348 // "overwritten" if we're warning about the destination for any call
3349 // but memcmp; otherwise a verb appropriate to the call.
3350 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
3351 if (BId == Builtin::BImemcpy)
3352 OperationType = 1;
3353 else if(BId == Builtin::BImemmove)
3354 OperationType = 2;
3355 else if (BId == Builtin::BImemcmp)
3356 OperationType = 3;
3357 }
3358
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003359 DiagRuntimeBehavior(
3360 Dest->getExprLoc(), Dest,
3361 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks0a151a12012-01-17 00:37:07 +00003362 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Anna Zaksd9b859a2012-01-13 21:52:01 +00003363 << FnName << PointeeTy
Anna Zaks0a151a12012-01-17 00:37:07 +00003364 << OperationType
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003365 << Call->getCallee()->getSourceRange());
Anna Zaks0a151a12012-01-17 00:37:07 +00003366 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
3367 BId != Builtin::BImemset)
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003368 DiagRuntimeBehavior(
3369 Dest->getExprLoc(), Dest,
3370 PDiag(diag::warn_arc_object_memaccess)
3371 << ArgIdx << FnName << PointeeTy
3372 << Call->getCallee()->getSourceRange());
John McCallf85e1932011-06-15 23:02:42 +00003373 else
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003374 continue;
John McCallf85e1932011-06-15 23:02:42 +00003375
3376 DiagRuntimeBehavior(
3377 Dest->getExprLoc(), Dest,
Chandler Carruth929f0132011-06-03 06:23:57 +00003378 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003379 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
3380 break;
3381 }
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003382 }
3383}
3384
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003385// A little helper routine: ignore addition and subtraction of integer literals.
3386// This intentionally does not ignore all integer constant expressions because
3387// we don't want to remove sizeof().
3388static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
3389 Ex = Ex->IgnoreParenCasts();
3390
3391 for (;;) {
3392 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
3393 if (!BO || !BO->isAdditiveOp())
3394 break;
3395
3396 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
3397 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
3398
3399 if (isa<IntegerLiteral>(RHS))
3400 Ex = LHS;
3401 else if (isa<IntegerLiteral>(LHS))
3402 Ex = RHS;
3403 else
3404 break;
3405 }
3406
3407 return Ex;
3408}
3409
Anna Zaks0f38ace2012-08-08 21:42:23 +00003410static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
3411 ASTContext &Context) {
3412 // Only handle constant-sized or VLAs, but not flexible members.
3413 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
3414 // Only issue the FIXIT for arrays of size > 1.
3415 if (CAT->getSize().getSExtValue() <= 1)
3416 return false;
3417 } else if (!Ty->isVariableArrayType()) {
3418 return false;
3419 }
3420 return true;
3421}
3422
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003423// Warn if the user has made the 'size' argument to strlcpy or strlcat
3424// be the size of the source, instead of the destination.
3425void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
3426 IdentifierInfo *FnName) {
3427
3428 // Don't crash if the user has the wrong number of arguments
3429 if (Call->getNumArgs() != 3)
3430 return;
3431
3432 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
3433 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
3434 const Expr *CompareWithSrc = NULL;
3435
3436 // Look for 'strlcpy(dst, x, sizeof(x))'
3437 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
3438 CompareWithSrc = Ex;
3439 else {
3440 // Look for 'strlcpy(dst, x, strlen(x))'
3441 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Richard Smith180f4792011-11-10 06:34:14 +00003442 if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003443 && SizeCall->getNumArgs() == 1)
3444 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
3445 }
3446 }
3447
3448 if (!CompareWithSrc)
3449 return;
3450
3451 // Determine if the argument to sizeof/strlen is equal to the source
3452 // argument. In principle there's all kinds of things you could do
3453 // here, for instance creating an == expression and evaluating it with
3454 // EvaluateAsBooleanCondition, but this uses a more direct technique:
3455 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
3456 if (!SrcArgDRE)
3457 return;
3458
3459 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
3460 if (!CompareWithSrcDRE ||
3461 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
3462 return;
3463
3464 const Expr *OriginalSizeArg = Call->getArg(2);
3465 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
3466 << OriginalSizeArg->getSourceRange() << FnName;
3467
3468 // Output a FIXIT hint if the destination is an array (rather than a
3469 // pointer to an array). This could be enhanced to handle some
3470 // pointers if we know the actual size, like if DstArg is 'array+2'
3471 // we could say 'sizeof(array)-2'.
3472 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks0f38ace2012-08-08 21:42:23 +00003473 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek8f746222011-08-18 22:48:41 +00003474 return;
Ted Kremenek8f746222011-08-18 22:48:41 +00003475
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003476 SmallString<128> sizeString;
Ted Kremenek8f746222011-08-18 22:48:41 +00003477 llvm::raw_svector_ostream OS(sizeString);
3478 OS << "sizeof(";
Richard Smithd1420c62012-08-16 03:56:14 +00003479 DstArg->printPretty(OS, 0, getPrintingPolicy());
Ted Kremenek8f746222011-08-18 22:48:41 +00003480 OS << ")";
3481
3482 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
3483 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
3484 OS.str());
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003485}
3486
Anna Zaksc36bedc2012-02-01 19:08:57 +00003487/// Check if two expressions refer to the same declaration.
3488static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
3489 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
3490 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
3491 return D1->getDecl() == D2->getDecl();
3492 return false;
3493}
3494
3495static const Expr *getStrlenExprArg(const Expr *E) {
3496 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
3497 const FunctionDecl *FD = CE->getDirectCallee();
3498 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
3499 return 0;
3500 return CE->getArg(0)->IgnoreParenCasts();
3501 }
3502 return 0;
3503}
3504
3505// Warn on anti-patterns as the 'size' argument to strncat.
3506// The correct size argument should look like following:
3507// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
3508void Sema::CheckStrncatArguments(const CallExpr *CE,
3509 IdentifierInfo *FnName) {
3510 // Don't crash if the user has the wrong number of arguments.
3511 if (CE->getNumArgs() < 3)
3512 return;
3513 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
3514 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
3515 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
3516
3517 // Identify common expressions, which are wrongly used as the size argument
3518 // to strncat and may lead to buffer overflows.
3519 unsigned PatternType = 0;
3520 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
3521 // - sizeof(dst)
3522 if (referToTheSameDecl(SizeOfArg, DstArg))
3523 PatternType = 1;
3524 // - sizeof(src)
3525 else if (referToTheSameDecl(SizeOfArg, SrcArg))
3526 PatternType = 2;
3527 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
3528 if (BE->getOpcode() == BO_Sub) {
3529 const Expr *L = BE->getLHS()->IgnoreParenCasts();
3530 const Expr *R = BE->getRHS()->IgnoreParenCasts();
3531 // - sizeof(dst) - strlen(dst)
3532 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
3533 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
3534 PatternType = 1;
3535 // - sizeof(src) - (anything)
3536 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
3537 PatternType = 2;
3538 }
3539 }
3540
3541 if (PatternType == 0)
3542 return;
3543
Anna Zaksafdb0412012-02-03 01:27:37 +00003544 // Generate the diagnostic.
3545 SourceLocation SL = LenArg->getLocStart();
3546 SourceRange SR = LenArg->getSourceRange();
3547 SourceManager &SM = PP.getSourceManager();
3548
3549 // If the function is defined as a builtin macro, do not show macro expansion.
3550 if (SM.isMacroArgExpansion(SL)) {
3551 SL = SM.getSpellingLoc(SL);
3552 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
3553 SM.getSpellingLoc(SR.getEnd()));
3554 }
3555
Anna Zaks0f38ace2012-08-08 21:42:23 +00003556 // Check if the destination is an array (rather than a pointer to an array).
3557 QualType DstTy = DstArg->getType();
3558 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
3559 Context);
3560 if (!isKnownSizeArray) {
3561 if (PatternType == 1)
3562 Diag(SL, diag::warn_strncat_wrong_size) << SR;
3563 else
3564 Diag(SL, diag::warn_strncat_src_size) << SR;
3565 return;
3566 }
3567
Anna Zaksc36bedc2012-02-01 19:08:57 +00003568 if (PatternType == 1)
Anna Zaksafdb0412012-02-03 01:27:37 +00003569 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003570 else
Anna Zaksafdb0412012-02-03 01:27:37 +00003571 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003572
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003573 SmallString<128> sizeString;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003574 llvm::raw_svector_ostream OS(sizeString);
3575 OS << "sizeof(";
Richard Smithd1420c62012-08-16 03:56:14 +00003576 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003577 OS << ") - ";
3578 OS << "strlen(";
Richard Smithd1420c62012-08-16 03:56:14 +00003579 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003580 OS << ") - 1";
3581
Anna Zaksafdb0412012-02-03 01:27:37 +00003582 Diag(SL, diag::note_strncat_wrong_size)
3583 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003584}
3585
Ted Kremenek06de2762007-08-17 16:46:58 +00003586//===--- CHECK: Return Address of Stack Variable --------------------------===//
3587
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003588static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3589 Decl *ParentDecl);
3590static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
3591 Decl *ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003592
3593/// CheckReturnStackAddr - Check if a return statement returns the address
3594/// of a stack variable.
3595void
3596Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
3597 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00003598
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003599 Expr *stackE = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003600 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003601
3602 // Perform checking for returned stack addresses, local blocks,
3603 // label addresses or references to temporaries.
John McCallf85e1932011-06-15 23:02:42 +00003604 if (lhsType->isPointerType() ||
David Blaikie4e4d0842012-03-11 07:00:24 +00003605 (!getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003606 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003607 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003608 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003609 }
3610
3611 if (stackE == 0)
3612 return; // Nothing suspicious was found.
3613
3614 SourceLocation diagLoc;
3615 SourceRange diagRange;
3616 if (refVars.empty()) {
3617 diagLoc = stackE->getLocStart();
3618 diagRange = stackE->getSourceRange();
3619 } else {
3620 // We followed through a reference variable. 'stackE' contains the
3621 // problematic expression but we will warn at the return statement pointing
3622 // at the reference variable. We will later display the "trail" of
3623 // reference variables using notes.
3624 diagLoc = refVars[0]->getLocStart();
3625 diagRange = refVars[0]->getSourceRange();
3626 }
3627
3628 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
3629 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
3630 : diag::warn_ret_stack_addr)
3631 << DR->getDecl()->getDeclName() << diagRange;
3632 } else if (isa<BlockExpr>(stackE)) { // local block.
3633 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
3634 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
3635 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
3636 } else { // local temporary.
3637 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
3638 : diag::warn_ret_local_temp_addr)
3639 << diagRange;
3640 }
3641
3642 // Display the "trail" of reference variables that we followed until we
3643 // found the problematic expression using notes.
3644 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
3645 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
3646 // If this var binds to another reference var, show the range of the next
3647 // var, otherwise the var binds to the problematic expression, in which case
3648 // show the range of the expression.
3649 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
3650 : stackE->getSourceRange();
3651 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
3652 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00003653 }
3654}
3655
3656/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
3657/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003658/// to a location on the stack, a local block, an address of a label, or a
3659/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00003660/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003661/// encounter a subexpression that (1) clearly does not lead to one of the
3662/// above problematic expressions (2) is something we cannot determine leads to
3663/// a problematic expression based on such local checking.
3664///
3665/// Both EvalAddr and EvalVal follow through reference variables to evaluate
3666/// the expression that they point to. Such variables are added to the
3667/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00003668///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00003669/// EvalAddr processes expressions that are pointers that are used as
3670/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003671/// At the base case of the recursion is a check for the above problematic
3672/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00003673///
3674/// This implementation handles:
3675///
3676/// * pointer-to-pointer casts
3677/// * implicit conversions from array references to pointers
3678/// * taking the address of fields
3679/// * arbitrary interplay between "&" and "*" operators
3680/// * pointer arithmetic from an address of a stack variable
3681/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003682static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3683 Decl *ParentDecl) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003684 if (E->isTypeDependent())
3685 return NULL;
3686
Ted Kremenek06de2762007-08-17 16:46:58 +00003687 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00003688 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00003689 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003690 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003691 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00003692
Peter Collingbournef111d932011-04-15 00:35:48 +00003693 E = E->IgnoreParens();
3694
Ted Kremenek06de2762007-08-17 16:46:58 +00003695 // Our "symbolic interpreter" is just a dispatch off the currently
3696 // viewed AST node. We then recursively traverse the AST by calling
3697 // EvalAddr and EvalVal appropriately.
3698 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003699 case Stmt::DeclRefExprClass: {
3700 DeclRefExpr *DR = cast<DeclRefExpr>(E);
3701
3702 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
3703 // If this is a reference variable, follow through to the expression that
3704 // it points to.
3705 if (V->hasLocalStorage() &&
3706 V->getType()->isReferenceType() && V->hasInit()) {
3707 // Add the reference variable to the "trail".
3708 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003709 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003710 }
3711
3712 return NULL;
3713 }
Ted Kremenek06de2762007-08-17 16:46:58 +00003714
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003715 case Stmt::UnaryOperatorClass: {
3716 // The only unary operator that make sense to handle here
3717 // is AddrOf. All others don't make sense as pointers.
3718 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003719
John McCall2de56d12010-08-25 11:45:40 +00003720 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003721 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003722 else
Ted Kremenek06de2762007-08-17 16:46:58 +00003723 return NULL;
3724 }
Mike Stump1eb44332009-09-09 15:08:12 +00003725
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003726 case Stmt::BinaryOperatorClass: {
3727 // Handle pointer arithmetic. All other binary operators are not valid
3728 // in this context.
3729 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00003730 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00003731
John McCall2de56d12010-08-25 11:45:40 +00003732 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003733 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00003734
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003735 Expr *Base = B->getLHS();
3736
3737 // Determine which argument is the real pointer base. It could be
3738 // the RHS argument instead of the LHS.
3739 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00003740
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003741 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003742 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003743 }
Steve Naroff61f40a22008-09-10 19:17:48 +00003744
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003745 // For conditional operators we need to see if either the LHS or RHS are
3746 // valid DeclRefExpr*s. If one of them is valid, we return it.
3747 case Stmt::ConditionalOperatorClass: {
3748 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003749
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003750 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003751 if (Expr *lhsExpr = C->getLHS()) {
3752 // In C++, we can have a throw-expression, which has 'void' type.
3753 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003754 if (Expr* LHS = EvalAddr(lhsExpr, refVars, ParentDecl))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003755 return LHS;
3756 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003757
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003758 // In C++, we can have a throw-expression, which has 'void' type.
3759 if (C->getRHS()->getType()->isVoidType())
3760 return NULL;
3761
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003762 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003763 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003764
3765 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00003766 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003767 return E; // local block.
3768 return NULL;
3769
3770 case Stmt::AddrLabelExprClass:
3771 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00003772
John McCall80ee6e82011-11-10 05:35:25 +00003773 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003774 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
3775 ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00003776
Ted Kremenek54b52742008-08-07 00:49:01 +00003777 // For casts, we need to handle conversions from arrays to
3778 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00003779 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00003780 case Stmt::CStyleCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00003781 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8b9414e2012-02-23 23:04:32 +00003782 case Stmt::ObjCBridgedCastExprClass:
Mike Stump1eb44332009-09-09 15:08:12 +00003783 case Stmt::CXXStaticCastExprClass:
3784 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00003785 case Stmt::CXXConstCastExprClass:
3786 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8b9414e2012-02-23 23:04:32 +00003787 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
3788 switch (cast<CastExpr>(E)->getCastKind()) {
3789 case CK_BitCast:
3790 case CK_LValueToRValue:
3791 case CK_NoOp:
3792 case CK_BaseToDerived:
3793 case CK_DerivedToBase:
3794 case CK_UncheckedDerivedToBase:
3795 case CK_Dynamic:
3796 case CK_CPointerToObjCPointerCast:
3797 case CK_BlockPointerToObjCPointerCast:
3798 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003799 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00003800
3801 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003802 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00003803
3804 default:
3805 return 0;
3806 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003807 }
Mike Stump1eb44332009-09-09 15:08:12 +00003808
Douglas Gregor03e80032011-06-21 17:03:29 +00003809 case Stmt::MaterializeTemporaryExprClass:
3810 if (Expr *Result = EvalAddr(
3811 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003812 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00003813 return Result;
3814
3815 return E;
3816
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003817 // Everything else: we simply don't reason about them.
3818 default:
3819 return NULL;
3820 }
Ted Kremenek06de2762007-08-17 16:46:58 +00003821}
Mike Stump1eb44332009-09-09 15:08:12 +00003822
Ted Kremenek06de2762007-08-17 16:46:58 +00003823
3824/// EvalVal - This function is complements EvalAddr in the mutual recursion.
3825/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003826static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3827 Decl *ParentDecl) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003828do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00003829 // We should only be called for evaluating non-pointer expressions, or
3830 // expressions with a pointer type that are not used as references but instead
3831 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00003832
Ted Kremenek06de2762007-08-17 16:46:58 +00003833 // Our "symbolic interpreter" is just a dispatch off the currently
3834 // viewed AST node. We then recursively traverse the AST by calling
3835 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00003836
3837 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00003838 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003839 case Stmt::ImplicitCastExprClass: {
3840 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00003841 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003842 E = IE->getSubExpr();
3843 continue;
3844 }
3845 return NULL;
3846 }
3847
John McCall80ee6e82011-11-10 05:35:25 +00003848 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003849 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00003850
Douglas Gregora2813ce2009-10-23 18:54:35 +00003851 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003852 // When we hit a DeclRefExpr we are looking at code that refers to a
3853 // variable's name. If it's not a reference variable we check if it has
3854 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00003855 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003856
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003857 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
3858 // Check if it refers to itself, e.g. "int& i = i;".
3859 if (V == ParentDecl)
3860 return DR;
3861
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003862 if (V->hasLocalStorage()) {
3863 if (!V->getType()->isReferenceType())
3864 return DR;
3865
3866 // Reference variable, follow through to the expression that
3867 // it points to.
3868 if (V->hasInit()) {
3869 // Add the reference variable to the "trail".
3870 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003871 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003872 }
3873 }
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003874 }
Mike Stump1eb44332009-09-09 15:08:12 +00003875
Ted Kremenek06de2762007-08-17 16:46:58 +00003876 return NULL;
3877 }
Mike Stump1eb44332009-09-09 15:08:12 +00003878
Ted Kremenek06de2762007-08-17 16:46:58 +00003879 case Stmt::UnaryOperatorClass: {
3880 // The only unary operator that make sense to handle here
3881 // is Deref. All others don't resolve to a "name." This includes
3882 // handling all sorts of rvalues passed to a unary operator.
3883 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003884
John McCall2de56d12010-08-25 11:45:40 +00003885 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003886 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003887
3888 return NULL;
3889 }
Mike Stump1eb44332009-09-09 15:08:12 +00003890
Ted Kremenek06de2762007-08-17 16:46:58 +00003891 case Stmt::ArraySubscriptExprClass: {
3892 // Array subscripts are potential references to data on the stack. We
3893 // retrieve the DeclRefExpr* for the array variable if it indeed
3894 // has local storage.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003895 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003896 }
Mike Stump1eb44332009-09-09 15:08:12 +00003897
Ted Kremenek06de2762007-08-17 16:46:58 +00003898 case Stmt::ConditionalOperatorClass: {
3899 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003900 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00003901 ConditionalOperator *C = cast<ConditionalOperator>(E);
3902
Anders Carlsson39073232007-11-30 19:04:31 +00003903 // Handle the GNU extension for missing LHS.
3904 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003905 if (Expr *LHS = EvalVal(lhsExpr, refVars, ParentDecl))
Anders Carlsson39073232007-11-30 19:04:31 +00003906 return LHS;
3907
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003908 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003909 }
Mike Stump1eb44332009-09-09 15:08:12 +00003910
Ted Kremenek06de2762007-08-17 16:46:58 +00003911 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00003912 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00003913 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003914
Ted Kremenek06de2762007-08-17 16:46:58 +00003915 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00003916 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00003917 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00003918
3919 // Check whether the member type is itself a reference, in which case
3920 // we're not going to refer to the member, but to what the member refers to.
3921 if (M->getMemberDecl()->getType()->isReferenceType())
3922 return NULL;
3923
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003924 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003925 }
Mike Stump1eb44332009-09-09 15:08:12 +00003926
Douglas Gregor03e80032011-06-21 17:03:29 +00003927 case Stmt::MaterializeTemporaryExprClass:
3928 if (Expr *Result = EvalVal(
3929 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003930 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00003931 return Result;
3932
3933 return E;
3934
Ted Kremenek06de2762007-08-17 16:46:58 +00003935 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003936 // Check that we don't return or take the address of a reference to a
3937 // temporary. This is only useful in C++.
3938 if (!E->isTypeDependent() && E->isRValue())
3939 return E;
3940
3941 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00003942 return NULL;
3943 }
Ted Kremenek68957a92010-08-04 20:01:07 +00003944} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00003945}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003946
3947//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
3948
3949/// Check for comparisons of floating point operands using != and ==.
3950/// Issue a warning if these are no self-comparisons, as they are not likely
3951/// to do what the programmer intended.
Richard Trieudd225092011-09-15 21:56:47 +00003952void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieudd225092011-09-15 21:56:47 +00003953 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
3954 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003955
3956 // Special case: check for x == x (which is OK).
3957 // Do not emit warnings for such cases.
3958 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
3959 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
3960 if (DRL->getDecl() == DRR->getDecl())
David Blaikie980343b2012-07-16 20:47:22 +00003961 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003962
3963
Ted Kremenek1b500bb2007-11-29 00:59:04 +00003964 // Special case: check for comparisons against literals that can be exactly
3965 // represented by APFloat. In such cases, do not emit a warning. This
3966 // is a heuristic: often comparison against such literals are used to
3967 // detect if a value in a variable has not changed. This clearly can
3968 // lead to false negatives.
David Blaikie980343b2012-07-16 20:47:22 +00003969 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
3970 if (FLL->isExact())
3971 return;
3972 } else
3973 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
3974 if (FLR->isExact())
3975 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003976
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003977 // Check for comparisons with builtin types.
David Blaikie980343b2012-07-16 20:47:22 +00003978 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
3979 if (CL->isBuiltinCall())
3980 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003981
David Blaikie980343b2012-07-16 20:47:22 +00003982 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
3983 if (CR->isBuiltinCall())
3984 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003985
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003986 // Emit the diagnostic.
David Blaikie980343b2012-07-16 20:47:22 +00003987 Diag(Loc, diag::warn_floatingpoint_eq)
3988 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003989}
John McCallba26e582010-01-04 23:21:16 +00003990
John McCallf2370c92010-01-06 05:24:50 +00003991//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
3992//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00003993
John McCallf2370c92010-01-06 05:24:50 +00003994namespace {
John McCallba26e582010-01-04 23:21:16 +00003995
John McCallf2370c92010-01-06 05:24:50 +00003996/// Structure recording the 'active' range of an integer-valued
3997/// expression.
3998struct IntRange {
3999 /// The number of bits active in the int.
4000 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00004001
John McCallf2370c92010-01-06 05:24:50 +00004002 /// True if the int is known not to have negative values.
4003 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00004004
John McCallf2370c92010-01-06 05:24:50 +00004005 IntRange(unsigned Width, bool NonNegative)
4006 : Width(Width), NonNegative(NonNegative)
4007 {}
John McCallba26e582010-01-04 23:21:16 +00004008
John McCall1844a6e2010-11-10 23:38:19 +00004009 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00004010 static IntRange forBoolType() {
4011 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00004012 }
4013
John McCall1844a6e2010-11-10 23:38:19 +00004014 /// Returns the range of an opaque value of the given integral type.
4015 static IntRange forValueOfType(ASTContext &C, QualType T) {
4016 return forValueOfCanonicalType(C,
4017 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00004018 }
4019
John McCall1844a6e2010-11-10 23:38:19 +00004020 /// Returns the range of an opaque value of a canonical integral type.
4021 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00004022 assert(T->isCanonicalUnqualified());
4023
4024 if (const VectorType *VT = dyn_cast<VectorType>(T))
4025 T = VT->getElementType().getTypePtr();
4026 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4027 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00004028
David Majnemerf9eaf982013-06-07 22:07:20 +00004029 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00004030 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemerf9eaf982013-06-07 22:07:20 +00004031 EnumDecl *Enum = ET->getDecl();
4032 if (!Enum->isCompleteDefinition())
4033 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall091f23f2010-11-09 22:22:12 +00004034
David Majnemerf9eaf982013-06-07 22:07:20 +00004035 unsigned NumPositive = Enum->getNumPositiveBits();
4036 unsigned NumNegative = Enum->getNumNegativeBits();
John McCall323ed742010-05-06 08:58:33 +00004037
David Majnemerf9eaf982013-06-07 22:07:20 +00004038 if (NumNegative == 0)
4039 return IntRange(NumPositive, true/*NonNegative*/);
4040 else
4041 return IntRange(std::max(NumPositive + 1, NumNegative),
4042 false/*NonNegative*/);
John McCall323ed742010-05-06 08:58:33 +00004043 }
John McCallf2370c92010-01-06 05:24:50 +00004044
4045 const BuiltinType *BT = cast<BuiltinType>(T);
4046 assert(BT->isInteger());
4047
4048 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4049 }
4050
John McCall1844a6e2010-11-10 23:38:19 +00004051 /// Returns the "target" range of a canonical integral type, i.e.
4052 /// the range of values expressible in the type.
4053 ///
4054 /// This matches forValueOfCanonicalType except that enums have the
4055 /// full range of their type, not the range of their enumerators.
4056 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
4057 assert(T->isCanonicalUnqualified());
4058
4059 if (const VectorType *VT = dyn_cast<VectorType>(T))
4060 T = VT->getElementType().getTypePtr();
4061 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4062 T = CT->getElementType().getTypePtr();
4063 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor69ff26b2011-09-08 23:29:05 +00004064 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall1844a6e2010-11-10 23:38:19 +00004065
4066 const BuiltinType *BT = cast<BuiltinType>(T);
4067 assert(BT->isInteger());
4068
4069 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4070 }
4071
4072 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00004073 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00004074 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00004075 L.NonNegative && R.NonNegative);
4076 }
4077
John McCall1844a6e2010-11-10 23:38:19 +00004078 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00004079 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00004080 return IntRange(std::min(L.Width, R.Width),
4081 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00004082 }
4083};
4084
Ted Kremenek0692a192012-01-31 05:37:37 +00004085static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
4086 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004087 if (value.isSigned() && value.isNegative())
4088 return IntRange(value.getMinSignedBits(), false);
4089
4090 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00004091 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00004092
4093 // isNonNegative() just checks the sign bit without considering
4094 // signedness.
4095 return IntRange(value.getActiveBits(), true);
4096}
4097
Ted Kremenek0692a192012-01-31 05:37:37 +00004098static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
4099 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004100 if (result.isInt())
4101 return GetValueRange(C, result.getInt(), MaxWidth);
4102
4103 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00004104 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
4105 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
4106 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
4107 R = IntRange::join(R, El);
4108 }
John McCallf2370c92010-01-06 05:24:50 +00004109 return R;
4110 }
4111
4112 if (result.isComplexInt()) {
4113 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
4114 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
4115 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00004116 }
4117
4118 // This can happen with lossless casts to intptr_t of "based" lvalues.
4119 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00004120 // FIXME: The only reason we need to pass the type in here is to get
4121 // the sign right on this one case. It would be nice if APValue
4122 // preserved this.
Eli Friedman65639282012-01-04 23:13:47 +00004123 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00004124 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall51313c32010-01-04 23:31:57 +00004125}
John McCallf2370c92010-01-06 05:24:50 +00004126
4127/// Pseudo-evaluate the given integer expression, estimating the
4128/// range of values it might take.
4129///
4130/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek0692a192012-01-31 05:37:37 +00004131static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004132 E = E->IgnoreParens();
4133
4134 // Try a full evaluation first.
4135 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00004136 if (E->EvaluateAsRValue(result, C))
John McCall0acc3112010-01-06 22:57:21 +00004137 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00004138
4139 // I think we only want to look through implicit casts here; if the
4140 // user has an explicit widening cast, we should treat the value as
4141 // being of the new, wider type.
4142 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedmanb17ee5b2011-12-15 02:41:52 +00004143 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCallf2370c92010-01-06 05:24:50 +00004144 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
4145
John McCall1844a6e2010-11-10 23:38:19 +00004146 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCallf2370c92010-01-06 05:24:50 +00004147
John McCall2de56d12010-08-25 11:45:40 +00004148 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00004149
John McCallf2370c92010-01-06 05:24:50 +00004150 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00004151 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00004152 return OutputTypeRange;
4153
4154 IntRange SubRange
4155 = GetExprRange(C, CE->getSubExpr(),
4156 std::min(MaxWidth, OutputTypeRange.Width));
4157
4158 // Bail out if the subexpr's range is as wide as the cast type.
4159 if (SubRange.Width >= OutputTypeRange.Width)
4160 return OutputTypeRange;
4161
4162 // Otherwise, we take the smaller width, and we're non-negative if
4163 // either the output type or the subexpr is.
4164 return IntRange(SubRange.Width,
4165 SubRange.NonNegative || OutputTypeRange.NonNegative);
4166 }
4167
4168 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4169 // If we can fold the condition, just take that operand.
4170 bool CondResult;
4171 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
4172 return GetExprRange(C, CondResult ? CO->getTrueExpr()
4173 : CO->getFalseExpr(),
4174 MaxWidth);
4175
4176 // Otherwise, conservatively merge.
4177 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
4178 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
4179 return IntRange::join(L, R);
4180 }
4181
4182 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4183 switch (BO->getOpcode()) {
4184
4185 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00004186 case BO_LAnd:
4187 case BO_LOr:
4188 case BO_LT:
4189 case BO_GT:
4190 case BO_LE:
4191 case BO_GE:
4192 case BO_EQ:
4193 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00004194 return IntRange::forBoolType();
4195
John McCall862ff872011-07-13 06:35:24 +00004196 // The type of the assignments is the type of the LHS, so the RHS
4197 // is not necessarily the same type.
John McCall2de56d12010-08-25 11:45:40 +00004198 case BO_MulAssign:
4199 case BO_DivAssign:
4200 case BO_RemAssign:
4201 case BO_AddAssign:
4202 case BO_SubAssign:
John McCall862ff872011-07-13 06:35:24 +00004203 case BO_XorAssign:
4204 case BO_OrAssign:
4205 // TODO: bitfields?
John McCall1844a6e2010-11-10 23:38:19 +00004206 return IntRange::forValueOfType(C, E->getType());
John McCallc0cd21d2010-02-23 19:22:29 +00004207
John McCall862ff872011-07-13 06:35:24 +00004208 // Simple assignments just pass through the RHS, which will have
4209 // been coerced to the LHS type.
4210 case BO_Assign:
4211 // TODO: bitfields?
4212 return GetExprRange(C, BO->getRHS(), MaxWidth);
4213
John McCallf2370c92010-01-06 05:24:50 +00004214 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00004215 case BO_PtrMemD:
4216 case BO_PtrMemI:
John McCall1844a6e2010-11-10 23:38:19 +00004217 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00004218
John McCall60fad452010-01-06 22:07:33 +00004219 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00004220 case BO_And:
4221 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00004222 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
4223 GetExprRange(C, BO->getRHS(), MaxWidth));
4224
John McCallf2370c92010-01-06 05:24:50 +00004225 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00004226 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00004227 // ...except that we want to treat '1 << (blah)' as logically
4228 // positive. It's an important idiom.
4229 if (IntegerLiteral *I
4230 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
4231 if (I->getValue() == 1) {
John McCall1844a6e2010-11-10 23:38:19 +00004232 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall3aae6092010-04-07 01:14:35 +00004233 return IntRange(R.Width, /*NonNegative*/ true);
4234 }
4235 }
4236 // fallthrough
4237
John McCall2de56d12010-08-25 11:45:40 +00004238 case BO_ShlAssign:
John McCall1844a6e2010-11-10 23:38:19 +00004239 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00004240
John McCall60fad452010-01-06 22:07:33 +00004241 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00004242 case BO_Shr:
4243 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00004244 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4245
4246 // If the shift amount is a positive constant, drop the width by
4247 // that much.
4248 llvm::APSInt shift;
4249 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
4250 shift.isNonNegative()) {
4251 unsigned zext = shift.getZExtValue();
4252 if (zext >= L.Width)
4253 L.Width = (L.NonNegative ? 0 : 1);
4254 else
4255 L.Width -= zext;
4256 }
4257
4258 return L;
4259 }
4260
4261 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00004262 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00004263 return GetExprRange(C, BO->getRHS(), MaxWidth);
4264
John McCall60fad452010-01-06 22:07:33 +00004265 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00004266 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00004267 if (BO->getLHS()->getType()->isPointerType())
John McCall1844a6e2010-11-10 23:38:19 +00004268 return IntRange::forValueOfType(C, E->getType());
John McCall00fe7612011-07-14 22:39:48 +00004269 break;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00004270
John McCall00fe7612011-07-14 22:39:48 +00004271 // The width of a division result is mostly determined by the size
4272 // of the LHS.
4273 case BO_Div: {
4274 // Don't 'pre-truncate' the operands.
4275 unsigned opWidth = C.getIntWidth(E->getType());
4276 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4277
4278 // If the divisor is constant, use that.
4279 llvm::APSInt divisor;
4280 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
4281 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
4282 if (log2 >= L.Width)
4283 L.Width = (L.NonNegative ? 0 : 1);
4284 else
4285 L.Width = std::min(L.Width - log2, MaxWidth);
4286 return L;
4287 }
4288
4289 // Otherwise, just use the LHS's width.
4290 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4291 return IntRange(L.Width, L.NonNegative && R.NonNegative);
4292 }
4293
4294 // The result of a remainder can't be larger than the result of
4295 // either side.
4296 case BO_Rem: {
4297 // Don't 'pre-truncate' the operands.
4298 unsigned opWidth = C.getIntWidth(E->getType());
4299 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4300 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4301
4302 IntRange meet = IntRange::meet(L, R);
4303 meet.Width = std::min(meet.Width, MaxWidth);
4304 return meet;
4305 }
4306
4307 // The default behavior is okay for these.
4308 case BO_Mul:
4309 case BO_Add:
4310 case BO_Xor:
4311 case BO_Or:
John McCallf2370c92010-01-06 05:24:50 +00004312 break;
4313 }
4314
John McCall00fe7612011-07-14 22:39:48 +00004315 // The default case is to treat the operation as if it were closed
4316 // on the narrowest type that encompasses both operands.
John McCallf2370c92010-01-06 05:24:50 +00004317 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4318 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
4319 return IntRange::join(L, R);
4320 }
4321
4322 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
4323 switch (UO->getOpcode()) {
4324 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00004325 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00004326 return IntRange::forBoolType();
4327
4328 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00004329 case UO_Deref:
4330 case UO_AddrOf: // should be impossible
John McCall1844a6e2010-11-10 23:38:19 +00004331 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00004332
4333 default:
4334 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
4335 }
4336 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004337
4338 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall1844a6e2010-11-10 23:38:19 +00004339 IntRange::forValueOfType(C, E->getType());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004340 }
John McCallf2370c92010-01-06 05:24:50 +00004341
John McCall993f43f2013-05-06 21:39:12 +00004342 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004343 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00004344 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00004345
John McCall1844a6e2010-11-10 23:38:19 +00004346 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00004347}
John McCall51313c32010-01-04 23:31:57 +00004348
Ted Kremenek0692a192012-01-31 05:37:37 +00004349static IntRange GetExprRange(ASTContext &C, Expr *E) {
John McCall323ed742010-05-06 08:58:33 +00004350 return GetExprRange(C, E, C.getIntWidth(E->getType()));
4351}
4352
John McCall51313c32010-01-04 23:31:57 +00004353/// Checks whether the given value, which currently has the given
4354/// source semantics, has the same value when coerced through the
4355/// target semantics.
Ted Kremenek0692a192012-01-31 05:37:37 +00004356static bool IsSameFloatAfterCast(const llvm::APFloat &value,
4357 const llvm::fltSemantics &Src,
4358 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00004359 llvm::APFloat truncated = value;
4360
4361 bool ignored;
4362 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
4363 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
4364
4365 return truncated.bitwiseIsEqual(value);
4366}
4367
4368/// Checks whether the given value, which currently has the given
4369/// source semantics, has the same value when coerced through the
4370/// target semantics.
4371///
4372/// The value might be a vector of floats (or a complex number).
Ted Kremenek0692a192012-01-31 05:37:37 +00004373static bool IsSameFloatAfterCast(const APValue &value,
4374 const llvm::fltSemantics &Src,
4375 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00004376 if (value.isFloat())
4377 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
4378
4379 if (value.isVector()) {
4380 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
4381 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
4382 return false;
4383 return true;
4384 }
4385
4386 assert(value.isComplexFloat());
4387 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
4388 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
4389}
4390
Ted Kremenek0692a192012-01-31 05:37:37 +00004391static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00004392
Ted Kremeneke3b159c2010-09-23 21:43:44 +00004393static bool IsZero(Sema &S, Expr *E) {
4394 // Suppress cases where we are comparing against an enum constant.
4395 if (const DeclRefExpr *DR =
4396 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
4397 if (isa<EnumConstantDecl>(DR->getDecl()))
4398 return false;
4399
4400 // Suppress cases where the '0' value is expanded from a macro.
4401 if (E->getLocStart().isMacroID())
4402 return false;
4403
John McCall323ed742010-05-06 08:58:33 +00004404 llvm::APSInt Value;
4405 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
4406}
4407
John McCall372e1032010-10-06 00:25:24 +00004408static bool HasEnumType(Expr *E) {
4409 // Strip off implicit integral promotions.
4410 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00004411 if (ICE->getCastKind() != CK_IntegralCast &&
4412 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00004413 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00004414 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00004415 }
4416
4417 return E->getType()->isEnumeralType();
4418}
4419
Ted Kremenek0692a192012-01-31 05:37:37 +00004420static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00004421 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00004422 if (E->isValueDependent())
4423 return;
4424
John McCall2de56d12010-08-25 11:45:40 +00004425 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00004426 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004427 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00004428 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004429 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00004430 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004431 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00004432 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004433 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00004434 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004435 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00004436 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004437 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00004438 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004439 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00004440 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4441 }
4442}
4443
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004444static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004445 Expr *Constant, Expr *Other,
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004446 llvm::APSInt Value,
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004447 bool RhsConstant) {
Richard Trieu526e6272012-11-14 22:50:24 +00004448 // 0 values are handled later by CheckTrivialUnsignedComparison().
4449 if (Value == 0)
4450 return;
4451
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004452 BinaryOperatorKind op = E->getOpcode();
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004453 QualType OtherT = Other->getType();
4454 QualType ConstantT = Constant->getType();
Richard Trieu526e6272012-11-14 22:50:24 +00004455 QualType CommonT = E->getLHS()->getType();
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004456 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004457 return;
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004458 assert((OtherT->isIntegerType() && ConstantT->isIntegerType())
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004459 && "comparison with non-integer type");
Richard Trieu526e6272012-11-14 22:50:24 +00004460
4461 bool ConstantSigned = ConstantT->isSignedIntegerType();
Richard Trieu526e6272012-11-14 22:50:24 +00004462 bool CommonSigned = CommonT->isSignedIntegerType();
4463
4464 bool EqualityOnly = false;
4465
4466 // TODO: Investigate using GetExprRange() to get tighter bounds on
4467 // on the bit ranges.
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004468 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
Richard Trieu526e6272012-11-14 22:50:24 +00004469 unsigned OtherWidth = OtherRange.Width;
4470
4471 if (CommonSigned) {
4472 // The common type is signed, therefore no signed to unsigned conversion.
Eli Friedmand87de7b2012-11-30 23:09:29 +00004473 if (!OtherRange.NonNegative) {
Richard Trieu526e6272012-11-14 22:50:24 +00004474 // Check that the constant is representable in type OtherT.
4475 if (ConstantSigned) {
4476 if (OtherWidth >= Value.getMinSignedBits())
4477 return;
4478 } else { // !ConstantSigned
4479 if (OtherWidth >= Value.getActiveBits() + 1)
4480 return;
4481 }
4482 } else { // !OtherSigned
4483 // Check that the constant is representable in type OtherT.
4484 // Negative values are out of range.
4485 if (ConstantSigned) {
4486 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
4487 return;
4488 } else { // !ConstantSigned
4489 if (OtherWidth >= Value.getActiveBits())
4490 return;
4491 }
4492 }
4493 } else { // !CommonSigned
Eli Friedmand87de7b2012-11-30 23:09:29 +00004494 if (OtherRange.NonNegative) {
Richard Trieu526e6272012-11-14 22:50:24 +00004495 if (OtherWidth >= Value.getActiveBits())
4496 return;
Eli Friedmand87de7b2012-11-30 23:09:29 +00004497 } else if (!OtherRange.NonNegative && !ConstantSigned) {
Richard Trieu526e6272012-11-14 22:50:24 +00004498 // Check to see if the constant is representable in OtherT.
4499 if (OtherWidth > Value.getActiveBits())
4500 return;
4501 // Check to see if the constant is equivalent to a negative value
4502 // cast to CommonT.
4503 if (S.Context.getIntWidth(ConstantT) == S.Context.getIntWidth(CommonT) &&
Richard Trieu5d1cf4f2012-11-15 03:43:50 +00004504 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
Richard Trieu526e6272012-11-14 22:50:24 +00004505 return;
4506 // The constant value rests between values that OtherT can represent after
4507 // conversion. Relational comparison still works, but equality
4508 // comparisons will be tautological.
4509 EqualityOnly = true;
4510 } else { // OtherSigned && ConstantSigned
4511 assert(0 && "Two signed types converted to unsigned types.");
4512 }
4513 }
4514
4515 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
4516
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004517 bool IsTrue = true;
Richard Trieu526e6272012-11-14 22:50:24 +00004518 if (op == BO_EQ || op == BO_NE) {
4519 IsTrue = op == BO_NE;
4520 } else if (EqualityOnly) {
4521 return;
4522 } else if (RhsConstant) {
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004523 if (op == BO_GT || op == BO_GE)
Richard Trieu526e6272012-11-14 22:50:24 +00004524 IsTrue = !PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004525 else // op == BO_LT || op == BO_LE
Richard Trieu526e6272012-11-14 22:50:24 +00004526 IsTrue = PositiveConstant;
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004527 } else {
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004528 if (op == BO_LT || op == BO_LE)
Richard Trieu526e6272012-11-14 22:50:24 +00004529 IsTrue = !PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004530 else // op == BO_GT || op == BO_GE
Richard Trieu526e6272012-11-14 22:50:24 +00004531 IsTrue = PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004532 }
Ted Kremenek7adf3a92013-03-15 21:50:10 +00004533
4534 // If this is a comparison to an enum constant, include that
4535 // constant in the diagnostic.
4536 const EnumConstantDecl *ED = 0;
4537 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
4538 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
4539
4540 SmallString<64> PrettySourceValue;
4541 llvm::raw_svector_ostream OS(PrettySourceValue);
4542 if (ED)
Ted Kremenek9de50942013-03-15 22:02:46 +00004543 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenek7adf3a92013-03-15 21:50:10 +00004544 else
4545 OS << Value;
4546
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004547 S.Diag(E->getOperatorLoc(), diag::warn_out_of_range_compare)
Ted Kremenek7adf3a92013-03-15 21:50:10 +00004548 << OS.str() << OtherT << IsTrue
Richard Trieu526e6272012-11-14 22:50:24 +00004549 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004550}
4551
John McCall323ed742010-05-06 08:58:33 +00004552/// Analyze the operands of the given comparison. Implements the
4553/// fallback case from AnalyzeComparison.
Ted Kremenek0692a192012-01-31 05:37:37 +00004554static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00004555 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4556 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00004557}
John McCall51313c32010-01-04 23:31:57 +00004558
John McCallba26e582010-01-04 23:21:16 +00004559/// \brief Implements -Wsign-compare.
4560///
Richard Trieudd225092011-09-15 21:56:47 +00004561/// \param E the binary operator to check for warnings
Ted Kremenek0692a192012-01-31 05:37:37 +00004562static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCall323ed742010-05-06 08:58:33 +00004563 // The type the comparison is being performed in.
4564 QualType T = E->getLHS()->getType();
4565 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
4566 && "comparison with mismatched types");
Fariborz Jahanianab4702f2012-09-18 17:46:26 +00004567 if (E->isValueDependent())
4568 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004569
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004570 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
4571 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004572
4573 bool IsComparisonConstant = false;
4574
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004575 // Check whether an integer constant comparison results in a value
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004576 // of 'true' or 'false'.
4577 if (T->isIntegralType(S.Context)) {
4578 llvm::APSInt RHSValue;
4579 bool IsRHSIntegralLiteral =
4580 RHS->isIntegerConstantExpr(RHSValue, S.Context);
4581 llvm::APSInt LHSValue;
4582 bool IsLHSIntegralLiteral =
4583 LHS->isIntegerConstantExpr(LHSValue, S.Context);
4584 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
4585 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
4586 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
4587 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
4588 else
4589 IsComparisonConstant =
4590 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004591 } else if (!T->hasUnsignedIntegerRepresentation())
4592 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004593
John McCall323ed742010-05-06 08:58:33 +00004594 // We don't do anything special if this isn't an unsigned integral
4595 // comparison: we're only interested in integral comparisons, and
4596 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00004597 //
4598 // We also don't care about value-dependent expressions or expressions
4599 // whose result is a constant.
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004600 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCall323ed742010-05-06 08:58:33 +00004601 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004602
John McCall323ed742010-05-06 08:58:33 +00004603 // Check to see if one of the (unmodified) operands is of different
4604 // signedness.
4605 Expr *signedOperand, *unsignedOperand;
Richard Trieudd225092011-09-15 21:56:47 +00004606 if (LHS->getType()->hasSignedIntegerRepresentation()) {
4607 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00004608 "unsigned comparison between two signed integer expressions?");
Richard Trieudd225092011-09-15 21:56:47 +00004609 signedOperand = LHS;
4610 unsignedOperand = RHS;
4611 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
4612 signedOperand = RHS;
4613 unsignedOperand = LHS;
John McCallba26e582010-01-04 23:21:16 +00004614 } else {
John McCall323ed742010-05-06 08:58:33 +00004615 CheckTrivialUnsignedComparison(S, E);
4616 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004617 }
4618
John McCall323ed742010-05-06 08:58:33 +00004619 // Otherwise, calculate the effective range of the signed operand.
4620 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00004621
John McCall323ed742010-05-06 08:58:33 +00004622 // Go ahead and analyze implicit conversions in the operands. Note
4623 // that we skip the implicit conversions on both sides.
Richard Trieudd225092011-09-15 21:56:47 +00004624 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
4625 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00004626
John McCall323ed742010-05-06 08:58:33 +00004627 // If the signed range is non-negative, -Wsign-compare won't fire,
4628 // but we should still check for comparisons which are always true
4629 // or false.
4630 if (signedRange.NonNegative)
4631 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004632
4633 // For (in)equality comparisons, if the unsigned operand is a
4634 // constant which cannot collide with a overflowed signed operand,
4635 // then reinterpreting the signed operand as unsigned will not
4636 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00004637 if (E->isEqualityOp()) {
4638 unsigned comparisonWidth = S.Context.getIntWidth(T);
4639 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00004640
John McCall323ed742010-05-06 08:58:33 +00004641 // We should never be unable to prove that the unsigned operand is
4642 // non-negative.
4643 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
4644
4645 if (unsignedRange.Width < comparisonWidth)
4646 return;
4647 }
4648
Douglas Gregor6d3b93d2012-05-01 01:53:49 +00004649 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
4650 S.PDiag(diag::warn_mixed_sign_comparison)
4651 << LHS->getType() << RHS->getType()
4652 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallba26e582010-01-04 23:21:16 +00004653}
4654
John McCall15d7d122010-11-11 03:21:53 +00004655/// Analyzes an attempt to assign the given value to a bitfield.
4656///
4657/// Returns true if there was something fishy about the attempt.
Ted Kremenek0692a192012-01-31 05:37:37 +00004658static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
4659 SourceLocation InitLoc) {
John McCall15d7d122010-11-11 03:21:53 +00004660 assert(Bitfield->isBitField());
4661 if (Bitfield->isInvalidDecl())
4662 return false;
4663
John McCall91b60142010-11-11 05:33:51 +00004664 // White-list bool bitfields.
4665 if (Bitfield->getType()->isBooleanType())
4666 return false;
4667
Douglas Gregor46ff3032011-02-04 13:09:01 +00004668 // Ignore value- or type-dependent expressions.
4669 if (Bitfield->getBitWidth()->isValueDependent() ||
4670 Bitfield->getBitWidth()->isTypeDependent() ||
4671 Init->isValueDependent() ||
4672 Init->isTypeDependent())
4673 return false;
4674
John McCall15d7d122010-11-11 03:21:53 +00004675 Expr *OriginalInit = Init->IgnoreParenImpCasts();
4676
Richard Smith80d4b552011-12-28 19:48:30 +00004677 llvm::APSInt Value;
4678 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall15d7d122010-11-11 03:21:53 +00004679 return false;
4680
John McCall15d7d122010-11-11 03:21:53 +00004681 unsigned OriginalWidth = Value.getBitWidth();
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004682 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall15d7d122010-11-11 03:21:53 +00004683
4684 if (OriginalWidth <= FieldWidth)
4685 return false;
4686
Eli Friedman3a643af2012-01-26 23:11:39 +00004687 // Compute the value which the bitfield will contain.
Jay Foad9f71a8f2010-12-07 08:25:34 +00004688 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedman3a643af2012-01-26 23:11:39 +00004689 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall15d7d122010-11-11 03:21:53 +00004690
Eli Friedman3a643af2012-01-26 23:11:39 +00004691 // Check whether the stored value is equal to the original value.
4692 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieue1ecdc12012-07-23 20:21:35 +00004693 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall15d7d122010-11-11 03:21:53 +00004694 return false;
4695
Eli Friedman3a643af2012-01-26 23:11:39 +00004696 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedman34ff0622012-02-02 00:40:20 +00004697 // therefore don't strictly fit into a signed bitfield of width 1.
4698 if (FieldWidth == 1 && Value == 1)
Eli Friedman3a643af2012-01-26 23:11:39 +00004699 return false;
4700
John McCall15d7d122010-11-11 03:21:53 +00004701 std::string PrettyValue = Value.toString(10);
4702 std::string PrettyTrunc = TruncatedValue.toString(10);
4703
4704 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
4705 << PrettyValue << PrettyTrunc << OriginalInit->getType()
4706 << Init->getSourceRange();
4707
4708 return true;
4709}
4710
John McCallbeb22aa2010-11-09 23:24:47 +00004711/// Analyze the given simple or compound assignment for warning-worthy
4712/// operations.
Ted Kremenek0692a192012-01-31 05:37:37 +00004713static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCallbeb22aa2010-11-09 23:24:47 +00004714 // Just recurse on the LHS.
4715 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4716
4717 // We want to recurse on the RHS as normal unless we're assigning to
4718 // a bitfield.
John McCall993f43f2013-05-06 21:39:12 +00004719 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00004720 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall15d7d122010-11-11 03:21:53 +00004721 E->getOperatorLoc())) {
4722 // Recurse, ignoring any implicit conversions on the RHS.
4723 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
4724 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00004725 }
4726 }
4727
4728 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
4729}
4730
John McCall51313c32010-01-04 23:31:57 +00004731/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00004732static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00004733 SourceLocation CContext, unsigned diag,
4734 bool pruneControlFlow = false) {
4735 if (pruneControlFlow) {
4736 S.DiagRuntimeBehavior(E->getExprLoc(), E,
4737 S.PDiag(diag)
4738 << SourceType << T << E->getSourceRange()
4739 << SourceRange(CContext));
4740 return;
4741 }
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004742 S.Diag(E->getExprLoc(), diag)
4743 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
4744}
4745
Chandler Carruthe1b02e02011-04-05 06:47:57 +00004746/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00004747static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00004748 SourceLocation CContext, unsigned diag,
4749 bool pruneControlFlow = false) {
4750 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruthe1b02e02011-04-05 06:47:57 +00004751}
4752
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004753/// Diagnose an implicit cast from a literal expression. Does not warn when the
4754/// cast wouldn't lose information.
Chandler Carruthf65076e2011-04-10 08:36:24 +00004755void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
4756 SourceLocation CContext) {
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004757 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruthf65076e2011-04-10 08:36:24 +00004758 bool isExact = false;
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004759 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00004760 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
4761 T->hasUnsignedIntegerRepresentation());
4762 if (Value.convertToInteger(IntegerValue,
Chandler Carruthf65076e2011-04-10 08:36:24 +00004763 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004764 == llvm::APFloat::opOK && isExact)
Chandler Carruthf65076e2011-04-10 08:36:24 +00004765 return;
4766
David Blaikiebe0ee872012-05-15 16:56:36 +00004767 SmallString<16> PrettySourceValue;
4768 Value.toString(PrettySourceValue);
David Blaikiede7e7b82012-05-15 17:18:27 +00004769 SmallString<16> PrettyTargetValue;
David Blaikiebe0ee872012-05-15 16:56:36 +00004770 if (T->isSpecificBuiltinType(BuiltinType::Bool))
4771 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
4772 else
David Blaikiede7e7b82012-05-15 17:18:27 +00004773 IntegerValue.toString(PrettyTargetValue);
David Blaikiebe0ee872012-05-15 16:56:36 +00004774
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004775 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikiebe0ee872012-05-15 16:56:36 +00004776 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
4777 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruthf65076e2011-04-10 08:36:24 +00004778}
4779
John McCall091f23f2010-11-09 22:22:12 +00004780std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
4781 if (!Range.Width) return "0";
4782
4783 llvm::APSInt ValueInRange = Value;
4784 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00004785 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00004786 return ValueInRange.toString(10);
4787}
4788
Hans Wennborg88617a22012-08-28 15:44:30 +00004789static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
4790 if (!isa<ImplicitCastExpr>(Ex))
4791 return false;
4792
4793 Expr *InnerE = Ex->IgnoreParenImpCasts();
4794 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
4795 const Type *Source =
4796 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
4797 if (Target->isDependentType())
4798 return false;
4799
4800 const BuiltinType *FloatCandidateBT =
4801 dyn_cast<BuiltinType>(ToBool ? Source : Target);
4802 const Type *BoolCandidateType = ToBool ? Target : Source;
4803
4804 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
4805 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
4806}
4807
4808void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
4809 SourceLocation CC) {
4810 unsigned NumArgs = TheCall->getNumArgs();
4811 for (unsigned i = 0; i < NumArgs; ++i) {
4812 Expr *CurrA = TheCall->getArg(i);
4813 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
4814 continue;
4815
4816 bool IsSwapped = ((i > 0) &&
4817 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
4818 IsSwapped |= ((i < (NumArgs - 1)) &&
4819 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
4820 if (IsSwapped) {
4821 // Warn on this floating-point to bool conversion.
4822 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
4823 CurrA->getType(), CC,
4824 diag::warn_impcast_floating_point_to_bool);
4825 }
4826 }
4827}
4828
John McCall323ed742010-05-06 08:58:33 +00004829void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00004830 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00004831 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00004832
John McCall323ed742010-05-06 08:58:33 +00004833 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
4834 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
4835 if (Source == Target) return;
4836 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00004837
Chandler Carruth108f7562011-07-26 05:40:03 +00004838 // If the conversion context location is invalid don't complain. We also
4839 // don't want to emit a warning if the issue occurs from the expansion of
4840 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
4841 // delay this check as long as possible. Once we detect we are in that
4842 // scenario, we just return.
Ted Kremenekef9ff882011-03-10 20:03:42 +00004843 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00004844 return;
4845
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004846 // Diagnose implicit casts to bool.
4847 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
4848 if (isa<StringLiteral>(E))
4849 // Warn on string literal to bool. Checks for string literals in logical
4850 // expressions, for instances, assert(0 && "error here"), is prevented
4851 // by a check in AnalyzeImplicitConversions().
4852 return DiagnoseImpCast(S, E, T, CC,
4853 diag::warn_impcast_string_literal_to_bool);
Lang Hamese14ca9f2011-12-05 20:49:50 +00004854 if (Source->isFunctionType()) {
4855 // Warn on function to bool. Checks free functions and static member
4856 // functions. Weakly imported functions are excluded from the check,
4857 // since it's common to test their value to check whether the linker
4858 // found a definition for them.
4859 ValueDecl *D = 0;
4860 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
4861 D = R->getDecl();
4862 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
4863 D = M->getMemberDecl();
4864 }
4865
4866 if (D && !D->isWeak()) {
Richard Trieu26b45d82011-12-06 04:48:01 +00004867 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
4868 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
4869 << F << E->getSourceRange() << SourceRange(CC);
David Blaikie2def7732011-12-09 21:42:37 +00004870 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
4871 << FixItHint::CreateInsertion(E->getExprLoc(), "&");
4872 QualType ReturnType;
4873 UnresolvedSet<4> NonTemplateOverloads;
4874 S.isExprCallable(*E, ReturnType, NonTemplateOverloads);
4875 if (!ReturnType.isNull()
4876 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
4877 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
4878 << FixItHint::CreateInsertion(
4879 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu26b45d82011-12-06 04:48:01 +00004880 return;
4881 }
Lang Hamese14ca9f2011-12-05 20:49:50 +00004882 }
4883 }
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004884 }
John McCall51313c32010-01-04 23:31:57 +00004885
4886 // Strip vector types.
4887 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004888 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004889 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004890 return;
John McCallb4eb64d2010-10-08 02:01:28 +00004891 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004892 }
Chris Lattnerb792b302011-06-14 04:51:15 +00004893
4894 // If the vector cast is cast between two vectors of the same size, it is
4895 // a bitcast, not a conversion.
4896 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
4897 return;
John McCall51313c32010-01-04 23:31:57 +00004898
4899 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
4900 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
4901 }
4902
4903 // Strip complex types.
4904 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004905 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004906 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004907 return;
4908
John McCallb4eb64d2010-10-08 02:01:28 +00004909 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004910 }
John McCall51313c32010-01-04 23:31:57 +00004911
4912 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
4913 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
4914 }
4915
4916 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
4917 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
4918
4919 // If the source is floating point...
4920 if (SourceBT && SourceBT->isFloatingPoint()) {
4921 // ...and the target is floating point...
4922 if (TargetBT && TargetBT->isFloatingPoint()) {
4923 // ...then warn if we're dropping FP rank.
4924
4925 // Builtin FP kinds are ordered by increasing FP rank.
4926 if (SourceBT->getKind() > TargetBT->getKind()) {
4927 // Don't warn about float constants that are precisely
4928 // representable in the target type.
4929 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00004930 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00004931 // Value might be a float, a float vector, or a float complex.
4932 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00004933 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
4934 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00004935 return;
4936 }
4937
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004938 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004939 return;
4940
John McCallb4eb64d2010-10-08 02:01:28 +00004941 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00004942 }
4943 return;
4944 }
4945
Ted Kremenekef9ff882011-03-10 20:03:42 +00004946 // If the target is integral, always warn.
David Blaikiebe0ee872012-05-15 16:56:36 +00004947 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004948 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004949 return;
4950
Chandler Carrutha5b93322011-02-17 11:05:49 +00004951 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay634c8af2011-09-08 22:30:47 +00004952 // We also want to warn on, e.g., "int i = -1.234"
4953 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
4954 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
4955 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
4956
Chandler Carruthf65076e2011-04-10 08:36:24 +00004957 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
4958 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00004959 } else {
4960 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
4961 }
4962 }
John McCall51313c32010-01-04 23:31:57 +00004963
Hans Wennborg88617a22012-08-28 15:44:30 +00004964 // If the target is bool, warn if expr is a function or method call.
4965 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
4966 isa<CallExpr>(E)) {
4967 // Check last argument of function call to see if it is an
4968 // implicit cast from a type matching the type the result
4969 // is being cast to.
4970 CallExpr *CEx = cast<CallExpr>(E);
4971 unsigned NumArgs = CEx->getNumArgs();
4972 if (NumArgs > 0) {
4973 Expr *LastA = CEx->getArg(NumArgs - 1);
4974 Expr *InnerE = LastA->IgnoreParenImpCasts();
4975 const Type *InnerType =
4976 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
4977 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
4978 // Warn on this floating-point to bool conversion
4979 DiagnoseImpCast(S, E, T, CC,
4980 diag::warn_impcast_floating_point_to_bool);
4981 }
4982 }
4983 }
John McCall51313c32010-01-04 23:31:57 +00004984 return;
4985 }
4986
Richard Trieu1838ca52011-05-29 19:59:02 +00004987 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
David Blaikieb26331b2012-06-19 21:19:06 +00004988 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
David Blaikiee81b43b2012-11-08 00:41:20 +00004989 && !Target->isBlockPointerType() && !Target->isMemberPointerType()
David Blaikie896c7dd2013-02-16 00:56:22 +00004990 && Target->isScalarType() && !Target->isNullPtrType()) {
David Blaikieb1360492012-03-16 20:30:12 +00004991 SourceLocation Loc = E->getSourceRange().getBegin();
4992 if (Loc.isMacroID())
4993 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
David Blaikie9fb1ac52012-05-15 21:57:38 +00004994 if (!Loc.isMacroID() || CC.isMacroID())
4995 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
4996 << T << clang::SourceRange(CC)
4997 << FixItHint::CreateReplacement(Loc, S.getFixItZeroLiteralForType(T));
Richard Trieu1838ca52011-05-29 19:59:02 +00004998 }
4999
David Blaikieb26331b2012-06-19 21:19:06 +00005000 if (!Source->isIntegerType() || !Target->isIntegerType())
5001 return;
5002
David Blaikiebe0ee872012-05-15 16:56:36 +00005003 // TODO: remove this early return once the false positives for constant->bool
5004 // in templates, macros, etc, are reduced or removed.
5005 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
5006 return;
5007
John McCall323ed742010-05-06 08:58:33 +00005008 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00005009 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00005010
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005011 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer25ffbef2013-03-28 19:07:11 +00005012 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005013 // TODO: this should happen for bitfield stores, too.
5014 llvm::APSInt Value(32);
5015 if (E->isIntegerConstantExpr(Value, S.Context)) {
5016 if (S.SourceMgr.isInSystemMacro(CC))
5017 return;
5018
John McCall091f23f2010-11-09 22:22:12 +00005019 std::string PrettySourceValue = Value.toString(10);
5020 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005021
Ted Kremenek5e745da2011-10-22 02:37:33 +00005022 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5023 S.PDiag(diag::warn_impcast_integer_precision_constant)
5024 << PrettySourceValue << PrettyTargetValue
5025 << E->getType() << T << E->getSourceRange()
5026 << clang::SourceRange(CC));
John McCall091f23f2010-11-09 22:22:12 +00005027 return;
5028 }
5029
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005030 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
5031 if (S.SourceMgr.isInSystemMacro(CC))
5032 return;
5033
David Blaikie37050842012-04-12 22:40:54 +00005034 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaksc36bedc2012-02-01 19:08:57 +00005035 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
5036 /* pruneControlFlow */ true);
John McCallb4eb64d2010-10-08 02:01:28 +00005037 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00005038 }
5039
5040 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
5041 (!TargetRange.NonNegative && SourceRange.NonNegative &&
5042 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00005043
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005044 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005045 return;
5046
John McCall323ed742010-05-06 08:58:33 +00005047 unsigned DiagID = diag::warn_impcast_integer_sign;
5048
5049 // Traditionally, gcc has warned about this under -Wsign-compare.
5050 // We also want to warn about it in -Wconversion.
5051 // So if -Wconversion is off, use a completely identical diagnostic
5052 // in the sign-compare group.
5053 // The conditional-checking code will
5054 if (ICContext) {
5055 DiagID = diag::warn_impcast_integer_sign_conditional;
5056 *ICContext = true;
5057 }
5058
John McCallb4eb64d2010-10-08 02:01:28 +00005059 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00005060 }
5061
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005062 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005063 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
5064 // type, to give us better diagnostics.
5065 QualType SourceType = E->getType();
David Blaikie4e4d0842012-03-11 07:00:24 +00005066 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005067 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5068 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
5069 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
5070 SourceType = S.Context.getTypeDeclType(Enum);
5071 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
5072 }
5073 }
5074
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005075 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
5076 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall83972f12013-03-09 00:54:27 +00005077 if (SourceEnum->getDecl()->hasNameForLinkage() &&
5078 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00005079 SourceEnum != TargetEnum) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005080 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005081 return;
5082
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005083 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005084 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00005085 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005086
John McCall51313c32010-01-04 23:31:57 +00005087 return;
5088}
5089
David Blaikie9fb1ac52012-05-15 21:57:38 +00005090void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5091 SourceLocation CC, QualType T);
John McCall323ed742010-05-06 08:58:33 +00005092
5093void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00005094 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00005095 E = E->IgnoreParenImpCasts();
5096
5097 if (isa<ConditionalOperator>(E))
David Blaikie9fb1ac52012-05-15 21:57:38 +00005098 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCall323ed742010-05-06 08:58:33 +00005099
John McCallb4eb64d2010-10-08 02:01:28 +00005100 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005101 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00005102 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00005103 return;
5104}
5105
David Blaikie9fb1ac52012-05-15 21:57:38 +00005106void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5107 SourceLocation CC, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00005108 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00005109
5110 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00005111 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
5112 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00005113
5114 // If -Wconversion would have warned about either of the candidates
5115 // for a signedness conversion to the context type...
5116 if (!Suspicious) return;
5117
5118 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00005119 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
5120 CC))
John McCall323ed742010-05-06 08:58:33 +00005121 return;
5122
John McCall323ed742010-05-06 08:58:33 +00005123 // ...then check whether it would have warned about either of the
5124 // candidates for a signedness conversion to the condition type.
Richard Trieu52541612011-07-21 02:46:28 +00005125 if (E->getType() == T) return;
5126
5127 Suspicious = false;
5128 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
5129 E->getType(), CC, &Suspicious);
5130 if (!Suspicious)
5131 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00005132 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00005133}
5134
5135/// AnalyzeImplicitConversions - Find and report any interesting
5136/// implicit conversions in the given expression. There are a couple
5137/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00005138void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00005139 QualType T = OrigE->getType();
5140 Expr *E = OrigE->IgnoreParenImpCasts();
5141
Douglas Gregorf8b6e152011-10-10 17:38:18 +00005142 if (E->isTypeDependent() || E->isValueDependent())
5143 return;
5144
John McCall323ed742010-05-06 08:58:33 +00005145 // For conditional operators, we analyze the arguments as if they
5146 // were being fed directly into the output.
5147 if (isa<ConditionalOperator>(E)) {
5148 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie9fb1ac52012-05-15 21:57:38 +00005149 CheckConditionalOperator(S, CO, CC, T);
John McCall323ed742010-05-06 08:58:33 +00005150 return;
5151 }
5152
Hans Wennborg88617a22012-08-28 15:44:30 +00005153 // Check implicit argument conversions for function calls.
5154 if (CallExpr *Call = dyn_cast<CallExpr>(E))
5155 CheckImplicitArgumentConversions(S, Call, CC);
5156
John McCall323ed742010-05-06 08:58:33 +00005157 // Go ahead and check any implicit conversions we might have skipped.
5158 // The non-canonical typecheck is just an optimization;
5159 // CheckImplicitConversion will filter out dead implicit conversions.
5160 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00005161 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00005162
5163 // Now continue drilling into this expression.
Fariborz Jahanian6f2a9fa2013-05-15 19:03:04 +00005164
5165 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahaniana1bfe1c2013-05-15 22:25:03 +00005166 if (POE->getResultExpr())
5167 E = POE->getResultExpr();
Fariborz Jahanian6f2a9fa2013-05-15 19:03:04 +00005168 }
5169
Fariborz Jahaniana1bfe1c2013-05-15 22:25:03 +00005170 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5171 return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
5172
John McCall323ed742010-05-06 08:58:33 +00005173 // Skip past explicit casts.
5174 if (isa<ExplicitCastExpr>(E)) {
5175 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00005176 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005177 }
5178
John McCallbeb22aa2010-11-09 23:24:47 +00005179 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5180 // Do a somewhat different check with comparison operators.
5181 if (BO->isComparisonOp())
5182 return AnalyzeComparison(S, BO);
5183
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005184 // And with simple assignments.
5185 if (BO->getOpcode() == BO_Assign)
John McCallbeb22aa2010-11-09 23:24:47 +00005186 return AnalyzeAssignment(S, BO);
5187 }
John McCall323ed742010-05-06 08:58:33 +00005188
5189 // These break the otherwise-useful invariant below. Fortunately,
5190 // we don't really need to recurse into them, because any internal
5191 // expressions should have been analyzed already when they were
5192 // built into statements.
5193 if (isa<StmtExpr>(E)) return;
5194
5195 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005196 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00005197
5198 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00005199 CC = E->getExprLoc();
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005200 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
5201 bool IsLogicalOperator = BO && BO->isLogicalOp();
5202 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor54042f12012-02-09 10:18:50 +00005203 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor503384f2012-02-09 00:47:04 +00005204 if (!ChildExpr)
5205 continue;
5206
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005207 if (IsLogicalOperator &&
5208 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
5209 // Ignore checking string literals that are in logical operators.
5210 continue;
5211 AnalyzeImplicitConversions(S, ChildExpr, CC);
5212 }
John McCall323ed742010-05-06 08:58:33 +00005213}
5214
5215} // end anonymous namespace
5216
5217/// Diagnoses "dangerous" implicit conversions within the given
5218/// expression (which is a full expression). Implements -Wconversion
5219/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00005220///
5221/// \param CC the "context" location of the implicit conversion, i.e.
5222/// the most location of the syntactic entity requiring the implicit
5223/// conversion
5224void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00005225 // Don't diagnose in unevaluated contexts.
David Blaikie71f55f72012-08-06 22:47:24 +00005226 if (isUnevaluatedContext())
John McCall323ed742010-05-06 08:58:33 +00005227 return;
5228
5229 // Don't diagnose for value- or type-dependent expressions.
5230 if (E->isTypeDependent() || E->isValueDependent())
5231 return;
5232
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005233 // Check for array bounds violations in cases where the check isn't triggered
5234 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
5235 // ArraySubscriptExpr is on the RHS of a variable initialization.
5236 CheckArrayAccess(E);
5237
John McCallb4eb64d2010-10-08 02:01:28 +00005238 // This is not the right CC for (e.g.) a variable initialization.
5239 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005240}
5241
Fariborz Jahanianad48a502013-01-24 22:11:45 +00005242/// Diagnose when expression is an integer constant expression and its evaluation
5243/// results in integer overflow
5244void Sema::CheckForIntOverflow (Expr *E) {
Fariborz Jahanian1fd8d462013-03-15 20:47:07 +00005245 if (isa<BinaryOperator>(E->IgnoreParens())) {
Fariborz Jahanianad48a502013-01-24 22:11:45 +00005246 llvm::SmallVector<PartialDiagnosticAt, 4> Diags;
5247 E->EvaluateForOverflow(Context, &Diags);
5248 }
5249}
5250
Richard Smith6c3af3d2013-01-17 01:17:56 +00005251namespace {
5252/// \brief Visitor for expressions which looks for unsequenced operations on the
5253/// same object.
5254class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
5255 /// \brief A tree of sequenced regions within an expression. Two regions are
5256 /// unsequenced if one is an ancestor or a descendent of the other. When we
5257 /// finish processing an expression with sequencing, such as a comma
5258 /// expression, we fold its tree nodes into its parent, since they are
5259 /// unsequenced with respect to nodes we will visit later.
5260 class SequenceTree {
5261 struct Value {
5262 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
5263 unsigned Parent : 31;
5264 bool Merged : 1;
5265 };
5266 llvm::SmallVector<Value, 8> Values;
5267
5268 public:
5269 /// \brief A region within an expression which may be sequenced with respect
5270 /// to some other region.
5271 class Seq {
5272 explicit Seq(unsigned N) : Index(N) {}
5273 unsigned Index;
5274 friend class SequenceTree;
5275 public:
5276 Seq() : Index(0) {}
5277 };
5278
5279 SequenceTree() { Values.push_back(Value(0)); }
5280 Seq root() const { return Seq(0); }
5281
5282 /// \brief Create a new sequence of operations, which is an unsequenced
5283 /// subset of \p Parent. This sequence of operations is sequenced with
5284 /// respect to other children of \p Parent.
5285 Seq allocate(Seq Parent) {
5286 Values.push_back(Value(Parent.Index));
5287 return Seq(Values.size() - 1);
5288 }
5289
5290 /// \brief Merge a sequence of operations into its parent.
5291 void merge(Seq S) {
5292 Values[S.Index].Merged = true;
5293 }
5294
5295 /// \brief Determine whether two operations are unsequenced. This operation
5296 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
5297 /// should have been merged into its parent as appropriate.
5298 bool isUnsequenced(Seq Cur, Seq Old) {
5299 unsigned C = representative(Cur.Index);
5300 unsigned Target = representative(Old.Index);
5301 while (C >= Target) {
5302 if (C == Target)
5303 return true;
5304 C = Values[C].Parent;
5305 }
5306 return false;
5307 }
5308
5309 private:
5310 /// \brief Pick a representative for a sequence.
5311 unsigned representative(unsigned K) {
5312 if (Values[K].Merged)
5313 // Perform path compression as we go.
5314 return Values[K].Parent = representative(Values[K].Parent);
5315 return K;
5316 }
5317 };
5318
5319 /// An object for which we can track unsequenced uses.
5320 typedef NamedDecl *Object;
5321
5322 /// Different flavors of object usage which we track. We only track the
5323 /// least-sequenced usage of each kind.
5324 enum UsageKind {
5325 /// A read of an object. Multiple unsequenced reads are OK.
5326 UK_Use,
5327 /// A modification of an object which is sequenced before the value
5328 /// computation of the expression, such as ++n.
5329 UK_ModAsValue,
5330 /// A modification of an object which is not sequenced before the value
5331 /// computation of the expression, such as n++.
5332 UK_ModAsSideEffect,
5333
5334 UK_Count = UK_ModAsSideEffect + 1
5335 };
5336
5337 struct Usage {
5338 Usage() : Use(0), Seq() {}
5339 Expr *Use;
5340 SequenceTree::Seq Seq;
5341 };
5342
5343 struct UsageInfo {
5344 UsageInfo() : Diagnosed(false) {}
5345 Usage Uses[UK_Count];
5346 /// Have we issued a diagnostic for this variable already?
5347 bool Diagnosed;
5348 };
5349 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
5350
5351 Sema &SemaRef;
5352 /// Sequenced regions within the expression.
5353 SequenceTree Tree;
5354 /// Declaration modifications and references which we have seen.
5355 UsageInfoMap UsageMap;
5356 /// The region we are currently within.
5357 SequenceTree::Seq Region;
5358 /// Filled in with declarations which were modified as a side-effect
5359 /// (that is, post-increment operations).
5360 llvm::SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smith1a2dcd52013-01-17 23:18:09 +00005361 /// Expressions to check later. We defer checking these to reduce
5362 /// stack usage.
5363 llvm::SmallVectorImpl<Expr*> &WorkList;
Richard Smith6c3af3d2013-01-17 01:17:56 +00005364
5365 /// RAII object wrapping the visitation of a sequenced subexpression of an
5366 /// expression. At the end of this process, the side-effects of the evaluation
5367 /// become sequenced with respect to the value computation of the result, so
5368 /// we downgrade any UK_ModAsSideEffect within the evaluation to
5369 /// UK_ModAsValue.
5370 struct SequencedSubexpression {
5371 SequencedSubexpression(SequenceChecker &Self)
5372 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
5373 Self.ModAsSideEffect = &ModAsSideEffect;
5374 }
5375 ~SequencedSubexpression() {
5376 for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) {
5377 UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first];
5378 U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second;
5379 Self.addUsage(U, ModAsSideEffect[I].first,
5380 ModAsSideEffect[I].second.Use, UK_ModAsValue);
5381 }
5382 Self.ModAsSideEffect = OldModAsSideEffect;
5383 }
5384
5385 SequenceChecker &Self;
5386 llvm::SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
5387 llvm::SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
5388 };
5389
5390 /// \brief Find the object which is produced by the specified expression,
5391 /// if any.
5392 Object getObject(Expr *E, bool Mod) const {
5393 E = E->IgnoreParenCasts();
5394 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5395 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
5396 return getObject(UO->getSubExpr(), Mod);
5397 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5398 if (BO->getOpcode() == BO_Comma)
5399 return getObject(BO->getRHS(), Mod);
5400 if (Mod && BO->isAssignmentOp())
5401 return getObject(BO->getLHS(), Mod);
5402 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
5403 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
5404 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
5405 return ME->getMemberDecl();
5406 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5407 // FIXME: If this is a reference, map through to its value.
5408 return DRE->getDecl();
5409 return 0;
5410 }
5411
5412 /// \brief Note that an object was modified or used by an expression.
5413 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
5414 Usage &U = UI.Uses[UK];
5415 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
5416 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
5417 ModAsSideEffect->push_back(std::make_pair(O, U));
5418 U.Use = Ref;
5419 U.Seq = Region;
5420 }
5421 }
5422 /// \brief Check whether a modification or use conflicts with a prior usage.
5423 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
5424 bool IsModMod) {
5425 if (UI.Diagnosed)
5426 return;
5427
5428 const Usage &U = UI.Uses[OtherKind];
5429 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
5430 return;
5431
5432 Expr *Mod = U.Use;
5433 Expr *ModOrUse = Ref;
5434 if (OtherKind == UK_Use)
5435 std::swap(Mod, ModOrUse);
5436
5437 SemaRef.Diag(Mod->getExprLoc(),
5438 IsModMod ? diag::warn_unsequenced_mod_mod
5439 : diag::warn_unsequenced_mod_use)
5440 << O << SourceRange(ModOrUse->getExprLoc());
5441 UI.Diagnosed = true;
5442 }
5443
5444 void notePreUse(Object O, Expr *Use) {
5445 UsageInfo &U = UsageMap[O];
5446 // Uses conflict with other modifications.
5447 checkUsage(O, U, Use, UK_ModAsValue, false);
5448 }
5449 void notePostUse(Object O, Expr *Use) {
5450 UsageInfo &U = UsageMap[O];
5451 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
5452 addUsage(U, O, Use, UK_Use);
5453 }
5454
5455 void notePreMod(Object O, Expr *Mod) {
5456 UsageInfo &U = UsageMap[O];
5457 // Modifications conflict with other modifications and with uses.
5458 checkUsage(O, U, Mod, UK_ModAsValue, true);
5459 checkUsage(O, U, Mod, UK_Use, false);
5460 }
5461 void notePostMod(Object O, Expr *Use, UsageKind UK) {
5462 UsageInfo &U = UsageMap[O];
5463 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
5464 addUsage(U, O, Use, UK);
5465 }
5466
5467public:
Richard Smith1a2dcd52013-01-17 23:18:09 +00005468 SequenceChecker(Sema &S, Expr *E,
5469 llvm::SmallVectorImpl<Expr*> &WorkList)
Richard Smithe5096c82013-01-17 01:40:50 +00005470 : EvaluatedExprVisitor<SequenceChecker>(S.Context), SemaRef(S),
Richard Smith1a2dcd52013-01-17 23:18:09 +00005471 Region(Tree.root()), ModAsSideEffect(0), WorkList(WorkList) {
Richard Smith6c3af3d2013-01-17 01:17:56 +00005472 Visit(E);
5473 }
5474
5475 void VisitStmt(Stmt *S) {
5476 // Skip all statements which aren't expressions for now.
5477 }
5478
5479 void VisitExpr(Expr *E) {
5480 // By default, just recurse to evaluated subexpressions.
Richard Smithe5096c82013-01-17 01:40:50 +00005481 EvaluatedExprVisitor<SequenceChecker>::VisitStmt(E);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005482 }
5483
5484 void VisitCastExpr(CastExpr *E) {
5485 Object O = Object();
5486 if (E->getCastKind() == CK_LValueToRValue)
5487 O = getObject(E->getSubExpr(), false);
5488
5489 if (O)
5490 notePreUse(O, E);
5491 VisitExpr(E);
5492 if (O)
5493 notePostUse(O, E);
5494 }
5495
5496 void VisitBinComma(BinaryOperator *BO) {
5497 // C++11 [expr.comma]p1:
5498 // Every value computation and side effect associated with the left
5499 // expression is sequenced before every value computation and side
5500 // effect associated with the right expression.
5501 SequenceTree::Seq LHS = Tree.allocate(Region);
5502 SequenceTree::Seq RHS = Tree.allocate(Region);
5503 SequenceTree::Seq OldRegion = Region;
5504
5505 {
5506 SequencedSubexpression SeqLHS(*this);
5507 Region = LHS;
5508 Visit(BO->getLHS());
5509 }
5510
5511 Region = RHS;
5512 Visit(BO->getRHS());
5513
5514 Region = OldRegion;
5515
5516 // Forget that LHS and RHS are sequenced. They are both unsequenced
5517 // with respect to other stuff.
5518 Tree.merge(LHS);
5519 Tree.merge(RHS);
5520 }
5521
5522 void VisitBinAssign(BinaryOperator *BO) {
5523 // The modification is sequenced after the value computation of the LHS
5524 // and RHS, so check it before inspecting the operands and update the
5525 // map afterwards.
5526 Object O = getObject(BO->getLHS(), true);
5527 if (!O)
5528 return VisitExpr(BO);
5529
5530 notePreMod(O, BO);
5531
5532 // C++11 [expr.ass]p7:
5533 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
5534 // only once.
5535 //
5536 // Therefore, for a compound assignment operator, O is considered used
5537 // everywhere except within the evaluation of E1 itself.
5538 if (isa<CompoundAssignOperator>(BO))
5539 notePreUse(O, BO);
5540
5541 Visit(BO->getLHS());
5542
5543 if (isa<CompoundAssignOperator>(BO))
5544 notePostUse(O, BO);
5545
5546 Visit(BO->getRHS());
5547
5548 notePostMod(O, BO, UK_ModAsValue);
5549 }
5550 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
5551 VisitBinAssign(CAO);
5552 }
5553
5554 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
5555 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
5556 void VisitUnaryPreIncDec(UnaryOperator *UO) {
5557 Object O = getObject(UO->getSubExpr(), true);
5558 if (!O)
5559 return VisitExpr(UO);
5560
5561 notePreMod(O, UO);
5562 Visit(UO->getSubExpr());
5563 notePostMod(O, UO, UK_ModAsValue);
5564 }
5565
5566 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
5567 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
5568 void VisitUnaryPostIncDec(UnaryOperator *UO) {
5569 Object O = getObject(UO->getSubExpr(), true);
5570 if (!O)
5571 return VisitExpr(UO);
5572
5573 notePreMod(O, UO);
5574 Visit(UO->getSubExpr());
5575 notePostMod(O, UO, UK_ModAsSideEffect);
5576 }
5577
5578 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
5579 void VisitBinLOr(BinaryOperator *BO) {
5580 // The side-effects of the LHS of an '&&' are sequenced before the
5581 // value computation of the RHS, and hence before the value computation
5582 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
5583 // as if they were unconditionally sequenced.
5584 {
5585 SequencedSubexpression Sequenced(*this);
5586 Visit(BO->getLHS());
5587 }
5588
5589 bool Result;
5590 if (!BO->getLHS()->isValueDependent() &&
Richard Smith995e4a72013-01-17 22:06:26 +00005591 BO->getLHS()->EvaluateAsBooleanCondition(Result, SemaRef.Context)) {
5592 if (!Result)
5593 Visit(BO->getRHS());
5594 } else {
5595 // Check for unsequenced operations in the RHS, treating it as an
5596 // entirely separate evaluation.
5597 //
5598 // FIXME: If there are operations in the RHS which are unsequenced
5599 // with respect to operations outside the RHS, and those operations
5600 // are unconditionally evaluated, diagnose them.
Richard Smith1a2dcd52013-01-17 23:18:09 +00005601 WorkList.push_back(BO->getRHS());
Richard Smith995e4a72013-01-17 22:06:26 +00005602 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00005603 }
5604 void VisitBinLAnd(BinaryOperator *BO) {
5605 {
5606 SequencedSubexpression Sequenced(*this);
5607 Visit(BO->getLHS());
5608 }
5609
5610 bool Result;
5611 if (!BO->getLHS()->isValueDependent() &&
Richard Smith995e4a72013-01-17 22:06:26 +00005612 BO->getLHS()->EvaluateAsBooleanCondition(Result, SemaRef.Context)) {
5613 if (Result)
5614 Visit(BO->getRHS());
5615 } else {
Richard Smith1a2dcd52013-01-17 23:18:09 +00005616 WorkList.push_back(BO->getRHS());
Richard Smith995e4a72013-01-17 22:06:26 +00005617 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00005618 }
5619
5620 // Only visit the condition, unless we can be sure which subexpression will
5621 // be chosen.
5622 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
5623 SequencedSubexpression Sequenced(*this);
5624 Visit(CO->getCond());
5625
5626 bool Result;
5627 if (!CO->getCond()->isValueDependent() &&
5628 CO->getCond()->EvaluateAsBooleanCondition(Result, SemaRef.Context))
5629 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith995e4a72013-01-17 22:06:26 +00005630 else {
Richard Smith1a2dcd52013-01-17 23:18:09 +00005631 WorkList.push_back(CO->getTrueExpr());
5632 WorkList.push_back(CO->getFalseExpr());
Richard Smith995e4a72013-01-17 22:06:26 +00005633 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00005634 }
5635
5636 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
5637 if (!CCE->isListInitialization())
5638 return VisitExpr(CCE);
5639
5640 // In C++11, list initializations are sequenced.
5641 llvm::SmallVector<SequenceTree::Seq, 32> Elts;
5642 SequenceTree::Seq Parent = Region;
5643 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
5644 E = CCE->arg_end();
5645 I != E; ++I) {
5646 Region = Tree.allocate(Parent);
5647 Elts.push_back(Region);
5648 Visit(*I);
5649 }
5650
5651 // Forget that the initializers are sequenced.
5652 Region = Parent;
5653 for (unsigned I = 0; I < Elts.size(); ++I)
5654 Tree.merge(Elts[I]);
5655 }
5656
5657 void VisitInitListExpr(InitListExpr *ILE) {
5658 if (!SemaRef.getLangOpts().CPlusPlus11)
5659 return VisitExpr(ILE);
5660
5661 // In C++11, list initializations are sequenced.
5662 llvm::SmallVector<SequenceTree::Seq, 32> Elts;
5663 SequenceTree::Seq Parent = Region;
5664 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
5665 Expr *E = ILE->getInit(I);
5666 if (!E) continue;
5667 Region = Tree.allocate(Parent);
5668 Elts.push_back(Region);
5669 Visit(E);
5670 }
5671
5672 // Forget that the initializers are sequenced.
5673 Region = Parent;
5674 for (unsigned I = 0; I < Elts.size(); ++I)
5675 Tree.merge(Elts[I]);
5676 }
5677};
5678}
5679
5680void Sema::CheckUnsequencedOperations(Expr *E) {
Richard Smith1a2dcd52013-01-17 23:18:09 +00005681 llvm::SmallVector<Expr*, 8> WorkList;
5682 WorkList.push_back(E);
5683 while (!WorkList.empty()) {
5684 Expr *Item = WorkList.back();
5685 WorkList.pop_back();
5686 SequenceChecker(*this, Item, WorkList);
5687 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00005688}
5689
Fariborz Jahanianad48a502013-01-24 22:11:45 +00005690void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
5691 bool IsConstexpr) {
Richard Smith6c3af3d2013-01-17 01:17:56 +00005692 CheckImplicitConversions(E, CheckLoc);
5693 CheckUnsequencedOperations(E);
Fariborz Jahanianad48a502013-01-24 22:11:45 +00005694 if (!IsConstexpr && !E->isValueDependent())
5695 CheckForIntOverflow(E);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005696}
5697
John McCall15d7d122010-11-11 03:21:53 +00005698void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
5699 FieldDecl *BitField,
5700 Expr *Init) {
5701 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
5702}
5703
Mike Stumpf8c49212010-01-21 03:59:47 +00005704/// CheckParmsForFunctionDef - Check that the parameters of the given
5705/// function are appropriate for the definition of a function. This
5706/// takes care of any checks that cannot be performed on the
5707/// declaration itself, e.g., that the types of each of the function
5708/// parameters are complete.
Douglas Gregor82aa7132010-11-01 18:37:59 +00005709bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
5710 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00005711 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00005712 for (; P != PEnd; ++P) {
5713 ParmVarDecl *Param = *P;
5714
Mike Stumpf8c49212010-01-21 03:59:47 +00005715 // C99 6.7.5.3p4: the parameters in a parameter type list in a
5716 // function declarator that is part of a function definition of
5717 // that function shall not have incomplete type.
5718 //
5719 // This is also C++ [dcl.fct]p6.
5720 if (!Param->isInvalidDecl() &&
5721 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00005722 diag::err_typecheck_decl_incomplete_type)) {
Mike Stumpf8c49212010-01-21 03:59:47 +00005723 Param->setInvalidDecl();
5724 HasInvalidParm = true;
5725 }
5726
5727 // C99 6.9.1p5: If the declarator includes a parameter type list, the
5728 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00005729 if (CheckParameterNames &&
5730 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00005731 !Param->isImplicit() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00005732 !getLangOpts().CPlusPlus)
Mike Stumpf8c49212010-01-21 03:59:47 +00005733 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00005734
5735 // C99 6.7.5.3p12:
5736 // If the function declarator is not part of a definition of that
5737 // function, parameters may have incomplete type and may use the [*]
5738 // notation in their sequences of declarator specifiers to specify
5739 // variable length array types.
5740 QualType PType = Param->getOriginalType();
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00005741 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigd17e3402010-02-01 05:02:49 +00005742 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitfc093362013-03-01 21:41:22 +00005743 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigd17e3402010-02-01 05:02:49 +00005744 // information is added for it.
5745 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00005746 break;
Sam Weinigd17e3402010-02-01 05:02:49 +00005747 }
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00005748 PType= AT->getElementType();
Sam Weinigd17e3402010-02-01 05:02:49 +00005749 }
Mike Stumpf8c49212010-01-21 03:59:47 +00005750 }
5751
5752 return HasInvalidParm;
5753}
John McCallb7f4ffe2010-08-12 21:44:57 +00005754
5755/// CheckCastAlign - Implements -Wcast-align, which warns when a
5756/// pointer cast increases the alignment requirements.
5757void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
5758 // This is actually a lot of work to potentially be doing on every
5759 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00005760 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
5761 TRange.getBegin())
David Blaikied6471f72011-09-25 23:23:43 +00005762 == DiagnosticsEngine::Ignored)
John McCallb7f4ffe2010-08-12 21:44:57 +00005763 return;
5764
5765 // Ignore dependent types.
5766 if (T->isDependentType() || Op->getType()->isDependentType())
5767 return;
5768
5769 // Require that the destination be a pointer type.
5770 const PointerType *DestPtr = T->getAs<PointerType>();
5771 if (!DestPtr) return;
5772
5773 // If the destination has alignment 1, we're done.
5774 QualType DestPointee = DestPtr->getPointeeType();
5775 if (DestPointee->isIncompleteType()) return;
5776 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
5777 if (DestAlign.isOne()) return;
5778
5779 // Require that the source be a pointer type.
5780 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
5781 if (!SrcPtr) return;
5782 QualType SrcPointee = SrcPtr->getPointeeType();
5783
5784 // Whitelist casts from cv void*. We already implicitly
5785 // whitelisted casts to cv void*, since they have alignment 1.
5786 // Also whitelist casts involving incomplete types, which implicitly
5787 // includes 'void'.
5788 if (SrcPointee->isIncompleteType()) return;
5789
5790 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
5791 if (SrcAlign >= DestAlign) return;
5792
5793 Diag(TRange.getBegin(), diag::warn_cast_align)
5794 << Op->getType() << T
5795 << static_cast<unsigned>(SrcAlign.getQuantity())
5796 << static_cast<unsigned>(DestAlign.getQuantity())
5797 << TRange << Op->getSourceRange();
5798}
5799
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005800static const Type* getElementType(const Expr *BaseExpr) {
5801 const Type* EltType = BaseExpr->getType().getTypePtr();
5802 if (EltType->isAnyPointerType())
5803 return EltType->getPointeeType().getTypePtr();
5804 else if (EltType->isArrayType())
5805 return EltType->getBaseElementTypeUnsafe();
5806 return EltType;
5807}
5808
Chandler Carruthc2684342011-08-05 09:10:50 +00005809/// \brief Check whether this array fits the idiom of a size-one tail padded
5810/// array member of a struct.
5811///
5812/// We avoid emitting out-of-bounds access warnings for such arrays as they are
5813/// commonly used to emulate flexible arrays in C89 code.
5814static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
5815 const NamedDecl *ND) {
5816 if (Size != 1 || !ND) return false;
5817
5818 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
5819 if (!FD) return false;
5820
5821 // Don't consider sizes resulting from macro expansions or template argument
5822 // substitution to form C89 tail-padded arrays.
Sean Callanand2cf3482012-05-04 18:22:53 +00005823
5824 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00005825 while (TInfo) {
5826 TypeLoc TL = TInfo->getTypeLoc();
5827 // Look through typedefs.
David Blaikie39e6ab42013-02-18 22:06:02 +00005828 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
5829 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00005830 TInfo = TDL->getTypeSourceInfo();
5831 continue;
5832 }
David Blaikie39e6ab42013-02-18 22:06:02 +00005833 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
5834 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier5e253012013-02-06 00:58:34 +00005835 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
5836 return false;
5837 }
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00005838 break;
Sean Callanand2cf3482012-05-04 18:22:53 +00005839 }
Chandler Carruthc2684342011-08-05 09:10:50 +00005840
5841 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gay381711c2011-11-29 22:43:53 +00005842 if (!RD) return false;
5843 if (RD->isUnion()) return false;
5844 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
5845 if (!CRD->isStandardLayout()) return false;
5846 }
Chandler Carruthc2684342011-08-05 09:10:50 +00005847
Benjamin Kramer22d4fed2011-08-06 03:04:42 +00005848 // See if this is the last field decl in the record.
5849 const Decl *D = FD;
5850 while ((D = D->getNextDeclInContext()))
5851 if (isa<FieldDecl>(D))
5852 return false;
5853 return true;
Chandler Carruthc2684342011-08-05 09:10:50 +00005854}
5855
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005856void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005857 const ArraySubscriptExpr *ASE,
Richard Smith25b009a2011-12-16 19:31:14 +00005858 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman92b670e2012-02-27 21:21:40 +00005859 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005860 if (IndexExpr->isValueDependent())
5861 return;
5862
Matt Beaumont-Gay8ef8f432011-12-12 22:35:02 +00005863 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005864 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00005865 const ConstantArrayType *ArrayTy =
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005866 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00005867 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00005868 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00005869
Chandler Carruth34064582011-02-17 20:55:08 +00005870 llvm::APSInt index;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005871 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00005872 return;
Richard Smith25b009a2011-12-16 19:31:14 +00005873 if (IndexNegated)
5874 index = -index;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00005875
Chandler Carruthba447122011-08-05 08:07:29 +00005876 const NamedDecl *ND = NULL;
Chandler Carruthba447122011-08-05 08:07:29 +00005877 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
5878 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruthc2684342011-08-05 09:10:50 +00005879 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruthba447122011-08-05 08:07:29 +00005880 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruthba447122011-08-05 08:07:29 +00005881
Ted Kremenek9e060ca2011-02-23 23:06:04 +00005882 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00005883 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00005884 if (!size.isStrictlyPositive())
5885 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005886
5887 const Type* BaseType = getElementType(BaseExpr);
Nico Weberde5998f2011-09-17 22:59:41 +00005888 if (BaseType != EffectiveType) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005889 // Make sure we're comparing apples to apples when comparing index to size
5890 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
5891 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhraind10f4bc2011-08-10 19:47:25 +00005892 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhrain18f16972011-08-10 18:49:28 +00005893 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005894 if (ptrarith_typesize != array_typesize) {
5895 // There's a cast to a different size type involved
5896 uint64_t ratio = array_typesize / ptrarith_typesize;
5897 // TODO: Be smarter about handling cases where array_typesize is not a
5898 // multiple of ptrarith_typesize
5899 if (ptrarith_typesize * ratio == array_typesize)
5900 size *= llvm::APInt(size.getBitWidth(), ratio);
5901 }
5902 }
5903
Chandler Carruth34064582011-02-17 20:55:08 +00005904 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00005905 index = index.zext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00005906 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00005907 size = size.zext(index.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00005908
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005909 // For array subscripting the index must be less than size, but for pointer
5910 // arithmetic also allow the index (offset) to be equal to size since
5911 // computing the next address after the end of the array is legal and
5912 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman92b670e2012-02-27 21:21:40 +00005913 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruthba447122011-08-05 08:07:29 +00005914 return;
5915
5916 // Also don't warn for arrays of size 1 which are members of some
5917 // structure. These are often used to approximate flexible arrays in C89
5918 // code.
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005919 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00005920 return;
Chandler Carruth34064582011-02-17 20:55:08 +00005921
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005922 // Suppress the warning if the subscript expression (as identified by the
5923 // ']' location) and the index expression are both from macro expansions
5924 // within a system header.
5925 if (ASE) {
5926 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
5927 ASE->getRBracketLoc());
5928 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
5929 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
5930 IndexExpr->getLocStart());
5931 if (SourceMgr.isFromSameFile(RBracketLoc, IndexLoc))
5932 return;
5933 }
5934 }
5935
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005936 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005937 if (ASE)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005938 DiagID = diag::warn_array_index_exceeds_bounds;
5939
5940 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
5941 PDiag(DiagID) << index.toString(10, true)
5942 << size.toString(10, true)
5943 << (unsigned)size.getLimitedValue(~0U)
5944 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00005945 } else {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005946 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005947 if (!ASE) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005948 DiagID = diag::warn_ptr_arith_precedes_bounds;
5949 if (index.isNegative()) index = -index;
5950 }
5951
5952 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
5953 PDiag(DiagID) << index.toString(10, true)
5954 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00005955 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00005956
Matt Beaumont-Gaycfbc5b52011-11-29 19:27:11 +00005957 if (!ND) {
5958 // Try harder to find a NamedDecl to point at in the note.
5959 while (const ArraySubscriptExpr *ASE =
5960 dyn_cast<ArraySubscriptExpr>(BaseExpr))
5961 BaseExpr = ASE->getBase()->IgnoreParenCasts();
5962 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
5963 ND = dyn_cast<NamedDecl>(DRE->getDecl());
5964 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
5965 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
5966 }
5967
Chandler Carruth35001ca2011-02-17 21:10:52 +00005968 if (ND)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005969 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
5970 PDiag(diag::note_array_index_out_of_bounds)
5971 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00005972}
5973
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005974void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005975 int AllowOnePastEnd = 0;
5976 while (expr) {
5977 expr = expr->IgnoreParenImpCasts();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005978 switch (expr->getStmtClass()) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005979 case Stmt::ArraySubscriptExprClass: {
5980 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005981 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005982 AllowOnePastEnd > 0);
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005983 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005984 }
5985 case Stmt::UnaryOperatorClass: {
5986 // Only unwrap the * and & unary operators
5987 const UnaryOperator *UO = cast<UnaryOperator>(expr);
5988 expr = UO->getSubExpr();
5989 switch (UO->getOpcode()) {
5990 case UO_AddrOf:
5991 AllowOnePastEnd++;
5992 break;
5993 case UO_Deref:
5994 AllowOnePastEnd--;
5995 break;
5996 default:
5997 return;
5998 }
5999 break;
6000 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006001 case Stmt::ConditionalOperatorClass: {
6002 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
6003 if (const Expr *lhs = cond->getLHS())
6004 CheckArrayAccess(lhs);
6005 if (const Expr *rhs = cond->getRHS())
6006 CheckArrayAccess(rhs);
6007 return;
6008 }
6009 default:
6010 return;
6011 }
Peter Collingbournef111d932011-04-15 00:35:48 +00006012 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006013}
John McCallf85e1932011-06-15 23:02:42 +00006014
6015//===--- CHECK: Objective-C retain cycles ----------------------------------//
6016
6017namespace {
6018 struct RetainCycleOwner {
6019 RetainCycleOwner() : Variable(0), Indirect(false) {}
6020 VarDecl *Variable;
6021 SourceRange Range;
6022 SourceLocation Loc;
6023 bool Indirect;
6024
6025 void setLocsFrom(Expr *e) {
6026 Loc = e->getExprLoc();
6027 Range = e->getSourceRange();
6028 }
6029 };
6030}
6031
6032/// Consider whether capturing the given variable can possibly lead to
6033/// a retain cycle.
6034static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledruf3477c12012-09-27 10:16:10 +00006035 // In ARC, it's captured strongly iff the variable has __strong
John McCallf85e1932011-06-15 23:02:42 +00006036 // lifetime. In MRR, it's captured strongly if the variable is
6037 // __block and has an appropriate type.
6038 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
6039 return false;
6040
6041 owner.Variable = var;
Jordan Rosee10f4d32012-09-15 02:48:31 +00006042 if (ref)
6043 owner.setLocsFrom(ref);
John McCallf85e1932011-06-15 23:02:42 +00006044 return true;
6045}
6046
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006047static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCallf85e1932011-06-15 23:02:42 +00006048 while (true) {
6049 e = e->IgnoreParens();
6050 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
6051 switch (cast->getCastKind()) {
6052 case CK_BitCast:
6053 case CK_LValueBitCast:
6054 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00006055 case CK_ARCReclaimReturnedObject:
John McCallf85e1932011-06-15 23:02:42 +00006056 e = cast->getSubExpr();
6057 continue;
6058
John McCallf85e1932011-06-15 23:02:42 +00006059 default:
6060 return false;
6061 }
6062 }
6063
6064 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
6065 ObjCIvarDecl *ivar = ref->getDecl();
6066 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
6067 return false;
6068
6069 // Try to find a retain cycle in the base.
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006070 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCallf85e1932011-06-15 23:02:42 +00006071 return false;
6072
6073 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
6074 owner.Indirect = true;
6075 return true;
6076 }
6077
6078 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
6079 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
6080 if (!var) return false;
6081 return considerVariable(var, ref, owner);
6082 }
6083
John McCallf85e1932011-06-15 23:02:42 +00006084 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
6085 if (member->isArrow()) return false;
6086
6087 // Don't count this as an indirect ownership.
6088 e = member->getBase();
6089 continue;
6090 }
6091
John McCall4b9c2d22011-11-06 09:01:30 +00006092 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
6093 // Only pay attention to pseudo-objects on property references.
6094 ObjCPropertyRefExpr *pre
6095 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
6096 ->IgnoreParens());
6097 if (!pre) return false;
6098 if (pre->isImplicitProperty()) return false;
6099 ObjCPropertyDecl *property = pre->getExplicitProperty();
6100 if (!property->isRetaining() &&
6101 !(property->getPropertyIvarDecl() &&
6102 property->getPropertyIvarDecl()->getType()
6103 .getObjCLifetime() == Qualifiers::OCL_Strong))
6104 return false;
6105
6106 owner.Indirect = true;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006107 if (pre->isSuperReceiver()) {
6108 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
6109 if (!owner.Variable)
6110 return false;
6111 owner.Loc = pre->getLocation();
6112 owner.Range = pre->getSourceRange();
6113 return true;
6114 }
John McCall4b9c2d22011-11-06 09:01:30 +00006115 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
6116 ->getSourceExpr());
6117 continue;
6118 }
6119
John McCallf85e1932011-06-15 23:02:42 +00006120 // Array ivars?
6121
6122 return false;
6123 }
6124}
6125
6126namespace {
6127 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
6128 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
6129 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
6130 Variable(variable), Capturer(0) {}
6131
6132 VarDecl *Variable;
6133 Expr *Capturer;
6134
6135 void VisitDeclRefExpr(DeclRefExpr *ref) {
6136 if (ref->getDecl() == Variable && !Capturer)
6137 Capturer = ref;
6138 }
6139
John McCallf85e1932011-06-15 23:02:42 +00006140 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
6141 if (Capturer) return;
6142 Visit(ref->getBase());
6143 if (Capturer && ref->isFreeIvar())
6144 Capturer = ref;
6145 }
6146
6147 void VisitBlockExpr(BlockExpr *block) {
6148 // Look inside nested blocks
6149 if (block->getBlockDecl()->capturesVariable(Variable))
6150 Visit(block->getBlockDecl()->getBody());
6151 }
Fariborz Jahanian7e2e4c32012-08-31 20:04:47 +00006152
6153 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
6154 if (Capturer) return;
6155 if (OVE->getSourceExpr())
6156 Visit(OVE->getSourceExpr());
6157 }
John McCallf85e1932011-06-15 23:02:42 +00006158 };
6159}
6160
6161/// Check whether the given argument is a block which captures a
6162/// variable.
6163static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
6164 assert(owner.Variable && owner.Loc.isValid());
6165
6166 e = e->IgnoreParenCasts();
Jordan Rose1fac58a2012-09-17 17:54:30 +00006167
6168 // Look through [^{...} copy] and Block_copy(^{...}).
6169 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
6170 Selector Cmd = ME->getSelector();
6171 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
6172 e = ME->getInstanceReceiver();
6173 if (!e)
6174 return 0;
6175 e = e->IgnoreParenCasts();
6176 }
6177 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
6178 if (CE->getNumArgs() == 1) {
6179 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekd13eff62012-10-02 04:36:54 +00006180 if (Fn) {
6181 const IdentifierInfo *FnI = Fn->getIdentifier();
6182 if (FnI && FnI->isStr("_Block_copy")) {
6183 e = CE->getArg(0)->IgnoreParenCasts();
6184 }
6185 }
Jordan Rose1fac58a2012-09-17 17:54:30 +00006186 }
6187 }
6188
John McCallf85e1932011-06-15 23:02:42 +00006189 BlockExpr *block = dyn_cast<BlockExpr>(e);
6190 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
6191 return 0;
6192
6193 FindCaptureVisitor visitor(S.Context, owner.Variable);
6194 visitor.Visit(block->getBlockDecl()->getBody());
6195 return visitor.Capturer;
6196}
6197
6198static void diagnoseRetainCycle(Sema &S, Expr *capturer,
6199 RetainCycleOwner &owner) {
6200 assert(capturer);
6201 assert(owner.Variable && owner.Loc.isValid());
6202
6203 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
6204 << owner.Variable << capturer->getSourceRange();
6205 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
6206 << owner.Indirect << owner.Range;
6207}
6208
6209/// Check for a keyword selector that starts with the word 'add' or
6210/// 'set'.
6211static bool isSetterLikeSelector(Selector sel) {
6212 if (sel.isUnarySelector()) return false;
6213
Chris Lattner5f9e2722011-07-23 10:55:15 +00006214 StringRef str = sel.getNameForSlot(0);
John McCallf85e1932011-06-15 23:02:42 +00006215 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00006216 if (str.startswith("set"))
John McCallf85e1932011-06-15 23:02:42 +00006217 str = str.substr(3);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00006218 else if (str.startswith("add")) {
6219 // Specially whitelist 'addOperationWithBlock:'.
6220 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
6221 return false;
6222 str = str.substr(3);
6223 }
John McCallf85e1932011-06-15 23:02:42 +00006224 else
6225 return false;
6226
6227 if (str.empty()) return true;
Jordan Rose3f6f51e2013-02-08 22:30:41 +00006228 return !isLowercase(str.front());
John McCallf85e1932011-06-15 23:02:42 +00006229}
6230
6231/// Check a message send to see if it's likely to cause a retain cycle.
6232void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
6233 // Only check instance methods whose selector looks like a setter.
6234 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
6235 return;
6236
6237 // Try to find a variable that the receiver is strongly owned by.
6238 RetainCycleOwner owner;
6239 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006240 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCallf85e1932011-06-15 23:02:42 +00006241 return;
6242 } else {
6243 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
6244 owner.Variable = getCurMethodDecl()->getSelfDecl();
6245 owner.Loc = msg->getSuperLoc();
6246 owner.Range = msg->getSuperLoc();
6247 }
6248
6249 // Check whether the receiver is captured by any of the arguments.
6250 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
6251 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
6252 return diagnoseRetainCycle(*this, capturer, owner);
6253}
6254
6255/// Check a property assign to see if it's likely to cause a retain cycle.
6256void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
6257 RetainCycleOwner owner;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006258 if (!findRetainCycleOwner(*this, receiver, owner))
John McCallf85e1932011-06-15 23:02:42 +00006259 return;
6260
6261 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
6262 diagnoseRetainCycle(*this, capturer, owner);
6263}
6264
Jordan Rosee10f4d32012-09-15 02:48:31 +00006265void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
6266 RetainCycleOwner Owner;
6267 if (!considerVariable(Var, /*DeclRefExpr=*/0, Owner))
6268 return;
6269
6270 // Because we don't have an expression for the variable, we have to set the
6271 // location explicitly here.
6272 Owner.Loc = Var->getLocation();
6273 Owner.Range = Var->getSourceRange();
6274
6275 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
6276 diagnoseRetainCycle(*this, Capturer, Owner);
6277}
6278
Ted Kremenek9d084012012-12-21 08:04:28 +00006279static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
6280 Expr *RHS, bool isProperty) {
6281 // Check if RHS is an Objective-C object literal, which also can get
6282 // immediately zapped in a weak reference. Note that we explicitly
6283 // allow ObjCStringLiterals, since those are designed to never really die.
6284 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenekf530ff72012-12-21 21:59:39 +00006285
Ted Kremenekd3292c82012-12-21 22:46:35 +00006286 // This enum needs to match with the 'select' in
6287 // warn_objc_arc_literal_assign (off-by-1).
6288 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
6289 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
6290 return false;
Ted Kremenekf530ff72012-12-21 21:59:39 +00006291
6292 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenekd3292c82012-12-21 22:46:35 +00006293 << (unsigned) Kind
Ted Kremenek9d084012012-12-21 08:04:28 +00006294 << (isProperty ? 0 : 1)
6295 << RHS->getSourceRange();
Ted Kremenekf530ff72012-12-21 21:59:39 +00006296
6297 return true;
Ted Kremenek9d084012012-12-21 08:04:28 +00006298}
6299
Ted Kremenekb29b30f2012-12-21 19:45:30 +00006300static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
6301 Qualifiers::ObjCLifetime LT,
6302 Expr *RHS, bool isProperty) {
6303 // Strip off any implicit cast added to get to the one ARC-specific.
6304 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
6305 if (cast->getCastKind() == CK_ARCConsumeObject) {
6306 S.Diag(Loc, diag::warn_arc_retained_assign)
6307 << (LT == Qualifiers::OCL_ExplicitNone)
6308 << (isProperty ? 0 : 1)
6309 << RHS->getSourceRange();
6310 return true;
6311 }
6312 RHS = cast->getSubExpr();
6313 }
6314
6315 if (LT == Qualifiers::OCL_Weak &&
6316 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
6317 return true;
6318
6319 return false;
6320}
6321
Ted Kremenekb1ea5102012-12-21 08:04:20 +00006322bool Sema::checkUnsafeAssigns(SourceLocation Loc,
6323 QualType LHS, Expr *RHS) {
6324 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
6325
6326 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
6327 return false;
6328
6329 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
6330 return true;
6331
6332 return false;
6333}
6334
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006335void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
6336 Expr *LHS, Expr *RHS) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006337 QualType LHSType;
6338 // PropertyRef on LHS type need be directly obtained from
6339 // its declaration as it has a PsuedoType.
6340 ObjCPropertyRefExpr *PRE
6341 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
6342 if (PRE && !PRE->isImplicitProperty()) {
6343 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
6344 if (PD)
6345 LHSType = PD->getType();
6346 }
6347
6348 if (LHSType.isNull())
6349 LHSType = LHS->getType();
Jordan Rose7a270482012-09-28 22:21:35 +00006350
6351 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
6352
6353 if (LT == Qualifiers::OCL_Weak) {
6354 DiagnosticsEngine::Level Level =
6355 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
6356 if (Level != DiagnosticsEngine::Ignored)
6357 getCurFunction()->markSafeWeakUse(LHS);
6358 }
6359
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006360 if (checkUnsafeAssigns(Loc, LHSType, RHS))
6361 return;
Jordan Rose7a270482012-09-28 22:21:35 +00006362
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006363 // FIXME. Check for other life times.
6364 if (LT != Qualifiers::OCL_None)
6365 return;
6366
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006367 if (PRE) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006368 if (PRE->isImplicitProperty())
6369 return;
6370 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
6371 if (!PD)
6372 return;
6373
Bill Wendlingad017fa2012-12-20 19:22:21 +00006374 unsigned Attributes = PD->getPropertyAttributes();
6375 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006376 // when 'assign' attribute was not explicitly specified
6377 // by user, ignore it and rely on property type itself
6378 // for lifetime info.
6379 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
6380 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
6381 LHSType->isObjCRetainableType())
6382 return;
6383
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006384 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00006385 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006386 Diag(Loc, diag::warn_arc_retained_property_assign)
6387 << RHS->getSourceRange();
6388 return;
6389 }
6390 RHS = cast->getSubExpr();
6391 }
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006392 }
Bill Wendlingad017fa2012-12-20 19:22:21 +00006393 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb1ea5102012-12-21 08:04:20 +00006394 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
6395 return;
Fariborz Jahanianbd2e27e2012-07-06 21:09:27 +00006396 }
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006397 }
6398}
Dmitri Gribenko625bb562012-02-14 22:14:32 +00006399
6400//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
6401
6402namespace {
6403bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
6404 SourceLocation StmtLoc,
6405 const NullStmt *Body) {
6406 // Do not warn if the body is a macro that expands to nothing, e.g:
6407 //
6408 // #define CALL(x)
6409 // if (condition)
6410 // CALL(0);
6411 //
6412 if (Body->hasLeadingEmptyMacro())
6413 return false;
6414
6415 // Get line numbers of statement and body.
6416 bool StmtLineInvalid;
6417 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
6418 &StmtLineInvalid);
6419 if (StmtLineInvalid)
6420 return false;
6421
6422 bool BodyLineInvalid;
6423 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
6424 &BodyLineInvalid);
6425 if (BodyLineInvalid)
6426 return false;
6427
6428 // Warn if null statement and body are on the same line.
6429 if (StmtLine != BodyLine)
6430 return false;
6431
6432 return true;
6433}
6434} // Unnamed namespace
6435
6436void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
6437 const Stmt *Body,
6438 unsigned DiagID) {
6439 // Since this is a syntactic check, don't emit diagnostic for template
6440 // instantiations, this just adds noise.
6441 if (CurrentInstantiationScope)
6442 return;
6443
6444 // The body should be a null statement.
6445 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
6446 if (!NBody)
6447 return;
6448
6449 // Do the usual checks.
6450 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
6451 return;
6452
6453 Diag(NBody->getSemiLoc(), DiagID);
6454 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
6455}
6456
6457void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
6458 const Stmt *PossibleBody) {
6459 assert(!CurrentInstantiationScope); // Ensured by caller
6460
6461 SourceLocation StmtLoc;
6462 const Stmt *Body;
6463 unsigned DiagID;
6464 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
6465 StmtLoc = FS->getRParenLoc();
6466 Body = FS->getBody();
6467 DiagID = diag::warn_empty_for_body;
6468 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
6469 StmtLoc = WS->getCond()->getSourceRange().getEnd();
6470 Body = WS->getBody();
6471 DiagID = diag::warn_empty_while_body;
6472 } else
6473 return; // Neither `for' nor `while'.
6474
6475 // The body should be a null statement.
6476 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
6477 if (!NBody)
6478 return;
6479
6480 // Skip expensive checks if diagnostic is disabled.
6481 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
6482 DiagnosticsEngine::Ignored)
6483 return;
6484
6485 // Do the usual checks.
6486 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
6487 return;
6488
6489 // `for(...);' and `while(...);' are popular idioms, so in order to keep
6490 // noise level low, emit diagnostics only if for/while is followed by a
6491 // CompoundStmt, e.g.:
6492 // for (int i = 0; i < n; i++);
6493 // {
6494 // a(i);
6495 // }
6496 // or if for/while is followed by a statement with more indentation
6497 // than for/while itself:
6498 // for (int i = 0; i < n; i++);
6499 // a(i);
6500 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
6501 if (!ProbableTypo) {
6502 bool BodyColInvalid;
6503 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
6504 PossibleBody->getLocStart(),
6505 &BodyColInvalid);
6506 if (BodyColInvalid)
6507 return;
6508
6509 bool StmtColInvalid;
6510 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
6511 S->getLocStart(),
6512 &StmtColInvalid);
6513 if (StmtColInvalid)
6514 return;
6515
6516 if (BodyCol > StmtCol)
6517 ProbableTypo = true;
6518 }
6519
6520 if (ProbableTypo) {
6521 Diag(NBody->getSemiLoc(), DiagID);
6522 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
6523 }
6524}
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00006525
6526//===--- Layout compatibility ----------------------------------------------//
6527
6528namespace {
6529
6530bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
6531
6532/// \brief Check if two enumeration types are layout-compatible.
6533bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
6534 // C++11 [dcl.enum] p8:
6535 // Two enumeration types are layout-compatible if they have the same
6536 // underlying type.
6537 return ED1->isComplete() && ED2->isComplete() &&
6538 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
6539}
6540
6541/// \brief Check if two fields are layout-compatible.
6542bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
6543 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
6544 return false;
6545
6546 if (Field1->isBitField() != Field2->isBitField())
6547 return false;
6548
6549 if (Field1->isBitField()) {
6550 // Make sure that the bit-fields are the same length.
6551 unsigned Bits1 = Field1->getBitWidthValue(C);
6552 unsigned Bits2 = Field2->getBitWidthValue(C);
6553
6554 if (Bits1 != Bits2)
6555 return false;
6556 }
6557
6558 return true;
6559}
6560
6561/// \brief Check if two standard-layout structs are layout-compatible.
6562/// (C++11 [class.mem] p17)
6563bool isLayoutCompatibleStruct(ASTContext &C,
6564 RecordDecl *RD1,
6565 RecordDecl *RD2) {
6566 // If both records are C++ classes, check that base classes match.
6567 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
6568 // If one of records is a CXXRecordDecl we are in C++ mode,
6569 // thus the other one is a CXXRecordDecl, too.
6570 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
6571 // Check number of base classes.
6572 if (D1CXX->getNumBases() != D2CXX->getNumBases())
6573 return false;
6574
6575 // Check the base classes.
6576 for (CXXRecordDecl::base_class_const_iterator
6577 Base1 = D1CXX->bases_begin(),
6578 BaseEnd1 = D1CXX->bases_end(),
6579 Base2 = D2CXX->bases_begin();
6580 Base1 != BaseEnd1;
6581 ++Base1, ++Base2) {
6582 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
6583 return false;
6584 }
6585 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
6586 // If only RD2 is a C++ class, it should have zero base classes.
6587 if (D2CXX->getNumBases() > 0)
6588 return false;
6589 }
6590
6591 // Check the fields.
6592 RecordDecl::field_iterator Field2 = RD2->field_begin(),
6593 Field2End = RD2->field_end(),
6594 Field1 = RD1->field_begin(),
6595 Field1End = RD1->field_end();
6596 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
6597 if (!isLayoutCompatible(C, *Field1, *Field2))
6598 return false;
6599 }
6600 if (Field1 != Field1End || Field2 != Field2End)
6601 return false;
6602
6603 return true;
6604}
6605
6606/// \brief Check if two standard-layout unions are layout-compatible.
6607/// (C++11 [class.mem] p18)
6608bool isLayoutCompatibleUnion(ASTContext &C,
6609 RecordDecl *RD1,
6610 RecordDecl *RD2) {
6611 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
6612 for (RecordDecl::field_iterator Field2 = RD2->field_begin(),
6613 Field2End = RD2->field_end();
6614 Field2 != Field2End; ++Field2) {
6615 UnmatchedFields.insert(*Field2);
6616 }
6617
6618 for (RecordDecl::field_iterator Field1 = RD1->field_begin(),
6619 Field1End = RD1->field_end();
6620 Field1 != Field1End; ++Field1) {
6621 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
6622 I = UnmatchedFields.begin(),
6623 E = UnmatchedFields.end();
6624
6625 for ( ; I != E; ++I) {
6626 if (isLayoutCompatible(C, *Field1, *I)) {
6627 bool Result = UnmatchedFields.erase(*I);
6628 (void) Result;
6629 assert(Result);
6630 break;
6631 }
6632 }
6633 if (I == E)
6634 return false;
6635 }
6636
6637 return UnmatchedFields.empty();
6638}
6639
6640bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
6641 if (RD1->isUnion() != RD2->isUnion())
6642 return false;
6643
6644 if (RD1->isUnion())
6645 return isLayoutCompatibleUnion(C, RD1, RD2);
6646 else
6647 return isLayoutCompatibleStruct(C, RD1, RD2);
6648}
6649
6650/// \brief Check if two types are layout-compatible in C++11 sense.
6651bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
6652 if (T1.isNull() || T2.isNull())
6653 return false;
6654
6655 // C++11 [basic.types] p11:
6656 // If two types T1 and T2 are the same type, then T1 and T2 are
6657 // layout-compatible types.
6658 if (C.hasSameType(T1, T2))
6659 return true;
6660
6661 T1 = T1.getCanonicalType().getUnqualifiedType();
6662 T2 = T2.getCanonicalType().getUnqualifiedType();
6663
6664 const Type::TypeClass TC1 = T1->getTypeClass();
6665 const Type::TypeClass TC2 = T2->getTypeClass();
6666
6667 if (TC1 != TC2)
6668 return false;
6669
6670 if (TC1 == Type::Enum) {
6671 return isLayoutCompatible(C,
6672 cast<EnumType>(T1)->getDecl(),
6673 cast<EnumType>(T2)->getDecl());
6674 } else if (TC1 == Type::Record) {
6675 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
6676 return false;
6677
6678 return isLayoutCompatible(C,
6679 cast<RecordType>(T1)->getDecl(),
6680 cast<RecordType>(T2)->getDecl());
6681 }
6682
6683 return false;
6684}
6685}
6686
6687//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
6688
6689namespace {
6690/// \brief Given a type tag expression find the type tag itself.
6691///
6692/// \param TypeExpr Type tag expression, as it appears in user's code.
6693///
6694/// \param VD Declaration of an identifier that appears in a type tag.
6695///
6696/// \param MagicValue Type tag magic value.
6697bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
6698 const ValueDecl **VD, uint64_t *MagicValue) {
6699 while(true) {
6700 if (!TypeExpr)
6701 return false;
6702
6703 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
6704
6705 switch (TypeExpr->getStmtClass()) {
6706 case Stmt::UnaryOperatorClass: {
6707 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
6708 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
6709 TypeExpr = UO->getSubExpr();
6710 continue;
6711 }
6712 return false;
6713 }
6714
6715 case Stmt::DeclRefExprClass: {
6716 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
6717 *VD = DRE->getDecl();
6718 return true;
6719 }
6720
6721 case Stmt::IntegerLiteralClass: {
6722 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
6723 llvm::APInt MagicValueAPInt = IL->getValue();
6724 if (MagicValueAPInt.getActiveBits() <= 64) {
6725 *MagicValue = MagicValueAPInt.getZExtValue();
6726 return true;
6727 } else
6728 return false;
6729 }
6730
6731 case Stmt::BinaryConditionalOperatorClass:
6732 case Stmt::ConditionalOperatorClass: {
6733 const AbstractConditionalOperator *ACO =
6734 cast<AbstractConditionalOperator>(TypeExpr);
6735 bool Result;
6736 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
6737 if (Result)
6738 TypeExpr = ACO->getTrueExpr();
6739 else
6740 TypeExpr = ACO->getFalseExpr();
6741 continue;
6742 }
6743 return false;
6744 }
6745
6746 case Stmt::BinaryOperatorClass: {
6747 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
6748 if (BO->getOpcode() == BO_Comma) {
6749 TypeExpr = BO->getRHS();
6750 continue;
6751 }
6752 return false;
6753 }
6754
6755 default:
6756 return false;
6757 }
6758 }
6759}
6760
6761/// \brief Retrieve the C type corresponding to type tag TypeExpr.
6762///
6763/// \param TypeExpr Expression that specifies a type tag.
6764///
6765/// \param MagicValues Registered magic values.
6766///
6767/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
6768/// kind.
6769///
6770/// \param TypeInfo Information about the corresponding C type.
6771///
6772/// \returns true if the corresponding C type was found.
6773bool GetMatchingCType(
6774 const IdentifierInfo *ArgumentKind,
6775 const Expr *TypeExpr, const ASTContext &Ctx,
6776 const llvm::DenseMap<Sema::TypeTagMagicValue,
6777 Sema::TypeTagData> *MagicValues,
6778 bool &FoundWrongKind,
6779 Sema::TypeTagData &TypeInfo) {
6780 FoundWrongKind = false;
6781
6782 // Variable declaration that has type_tag_for_datatype attribute.
6783 const ValueDecl *VD = NULL;
6784
6785 uint64_t MagicValue;
6786
6787 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
6788 return false;
6789
6790 if (VD) {
6791 for (specific_attr_iterator<TypeTagForDatatypeAttr>
6792 I = VD->specific_attr_begin<TypeTagForDatatypeAttr>(),
6793 E = VD->specific_attr_end<TypeTagForDatatypeAttr>();
6794 I != E; ++I) {
6795 if (I->getArgumentKind() != ArgumentKind) {
6796 FoundWrongKind = true;
6797 return false;
6798 }
6799 TypeInfo.Type = I->getMatchingCType();
6800 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
6801 TypeInfo.MustBeNull = I->getMustBeNull();
6802 return true;
6803 }
6804 return false;
6805 }
6806
6807 if (!MagicValues)
6808 return false;
6809
6810 llvm::DenseMap<Sema::TypeTagMagicValue,
6811 Sema::TypeTagData>::const_iterator I =
6812 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
6813 if (I == MagicValues->end())
6814 return false;
6815
6816 TypeInfo = I->second;
6817 return true;
6818}
6819} // unnamed namespace
6820
6821void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
6822 uint64_t MagicValue, QualType Type,
6823 bool LayoutCompatible,
6824 bool MustBeNull) {
6825 if (!TypeTagForDatatypeMagicValues)
6826 TypeTagForDatatypeMagicValues.reset(
6827 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
6828
6829 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
6830 (*TypeTagForDatatypeMagicValues)[Magic] =
6831 TypeTagData(Type, LayoutCompatible, MustBeNull);
6832}
6833
6834namespace {
6835bool IsSameCharType(QualType T1, QualType T2) {
6836 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
6837 if (!BT1)
6838 return false;
6839
6840 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
6841 if (!BT2)
6842 return false;
6843
6844 BuiltinType::Kind T1Kind = BT1->getKind();
6845 BuiltinType::Kind T2Kind = BT2->getKind();
6846
6847 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
6848 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
6849 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
6850 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
6851}
6852} // unnamed namespace
6853
6854void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
6855 const Expr * const *ExprArgs) {
6856 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
6857 bool IsPointerAttr = Attr->getIsPointer();
6858
6859 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
6860 bool FoundWrongKind;
6861 TypeTagData TypeInfo;
6862 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
6863 TypeTagForDatatypeMagicValues.get(),
6864 FoundWrongKind, TypeInfo)) {
6865 if (FoundWrongKind)
6866 Diag(TypeTagExpr->getExprLoc(),
6867 diag::warn_type_tag_for_datatype_wrong_kind)
6868 << TypeTagExpr->getSourceRange();
6869 return;
6870 }
6871
6872 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
6873 if (IsPointerAttr) {
6874 // Skip implicit cast of pointer to `void *' (as a function argument).
6875 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5a249802012-11-03 16:07:49 +00006876 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkob57ce4e2012-11-03 22:10:18 +00006877 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00006878 ArgumentExpr = ICE->getSubExpr();
6879 }
6880 QualType ArgumentType = ArgumentExpr->getType();
6881
6882 // Passing a `void*' pointer shouldn't trigger a warning.
6883 if (IsPointerAttr && ArgumentType->isVoidPointerType())
6884 return;
6885
6886 if (TypeInfo.MustBeNull) {
6887 // Type tag with matching void type requires a null pointer.
6888 if (!ArgumentExpr->isNullPointerConstant(Context,
6889 Expr::NPC_ValueDependentIsNotNull)) {
6890 Diag(ArgumentExpr->getExprLoc(),
6891 diag::warn_type_safety_null_pointer_required)
6892 << ArgumentKind->getName()
6893 << ArgumentExpr->getSourceRange()
6894 << TypeTagExpr->getSourceRange();
6895 }
6896 return;
6897 }
6898
6899 QualType RequiredType = TypeInfo.Type;
6900 if (IsPointerAttr)
6901 RequiredType = Context.getPointerType(RequiredType);
6902
6903 bool mismatch = false;
6904 if (!TypeInfo.LayoutCompatible) {
6905 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
6906
6907 // C++11 [basic.fundamental] p1:
6908 // Plain char, signed char, and unsigned char are three distinct types.
6909 //
6910 // But we treat plain `char' as equivalent to `signed char' or `unsigned
6911 // char' depending on the current char signedness mode.
6912 if (mismatch)
6913 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
6914 RequiredType->getPointeeType())) ||
6915 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
6916 mismatch = false;
6917 } else
6918 if (IsPointerAttr)
6919 mismatch = !isLayoutCompatible(Context,
6920 ArgumentType->getPointeeType(),
6921 RequiredType->getPointeeType());
6922 else
6923 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
6924
6925 if (mismatch)
6926 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
6927 << ArgumentType << ArgumentKind->getName()
6928 << TypeInfo.LayoutCompatible << RequiredType
6929 << ArgumentExpr->getSourceRange()
6930 << TypeTagExpr->getSourceRange();
6931}