blob: da24667804b5d361217b613646b6ef538eca8710 [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 Smith831421f2012-06-25 20:30:08 +0000600bool Sema::CheckBlockCall(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();
607 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000608 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000609
Richard Smith831421f2012-06-25 20:30:08 +0000610 VariadicCallType CallType =
611 Proto && Proto->isVariadic() ? VariadicBlock : VariadicDoesNotApply ;
612 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
Anders Carlssond406bf02009-08-16 01:56:34 +0000613
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000614 checkCall(NDecl,
615 llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
616 TheCall->getNumArgs()),
Richard Smith831421f2012-06-25 20:30:08 +0000617 NumProtoArgs, /*IsMemberFunction=*/false,
618 TheCall->getRParenLoc(),
619 TheCall->getCallee()->getSourceRange(), CallType);
620
Anders Carlssond406bf02009-08-16 01:56:34 +0000621 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000622}
623
Richard Smithff34d402012-04-12 05:08:17 +0000624ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
625 AtomicExpr::AtomicOp Op) {
Eli Friedman276b0612011-10-11 02:20:01 +0000626 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
627 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedman276b0612011-10-11 02:20:01 +0000628
Richard Smithff34d402012-04-12 05:08:17 +0000629 // All these operations take one of the following forms:
630 enum {
631 // C __c11_atomic_init(A *, C)
632 Init,
633 // C __c11_atomic_load(A *, int)
634 Load,
635 // void __atomic_load(A *, CP, int)
636 Copy,
637 // C __c11_atomic_add(A *, M, int)
638 Arithmetic,
639 // C __atomic_exchange_n(A *, CP, int)
640 Xchg,
641 // void __atomic_exchange(A *, C *, CP, int)
642 GNUXchg,
643 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
644 C11CmpXchg,
645 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
646 GNUCmpXchg
647 } Form = Init;
648 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
649 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
650 // where:
651 // C is an appropriate type,
652 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
653 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
654 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
655 // the int parameters are for orderings.
Eli Friedman276b0612011-10-11 02:20:01 +0000656
Richard Smithff34d402012-04-12 05:08:17 +0000657 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
658 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
659 && "need to update code for modified C11 atomics");
660 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
661 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
662 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
663 Op == AtomicExpr::AO__atomic_store_n ||
664 Op == AtomicExpr::AO__atomic_exchange_n ||
665 Op == AtomicExpr::AO__atomic_compare_exchange_n;
666 bool IsAddSub = false;
667
668 switch (Op) {
669 case AtomicExpr::AO__c11_atomic_init:
670 Form = Init;
671 break;
672
673 case AtomicExpr::AO__c11_atomic_load:
674 case AtomicExpr::AO__atomic_load_n:
675 Form = Load;
676 break;
677
678 case AtomicExpr::AO__c11_atomic_store:
679 case AtomicExpr::AO__atomic_load:
680 case AtomicExpr::AO__atomic_store:
681 case AtomicExpr::AO__atomic_store_n:
682 Form = Copy;
683 break;
684
685 case AtomicExpr::AO__c11_atomic_fetch_add:
686 case AtomicExpr::AO__c11_atomic_fetch_sub:
687 case AtomicExpr::AO__atomic_fetch_add:
688 case AtomicExpr::AO__atomic_fetch_sub:
689 case AtomicExpr::AO__atomic_add_fetch:
690 case AtomicExpr::AO__atomic_sub_fetch:
691 IsAddSub = true;
692 // Fall through.
693 case AtomicExpr::AO__c11_atomic_fetch_and:
694 case AtomicExpr::AO__c11_atomic_fetch_or:
695 case AtomicExpr::AO__c11_atomic_fetch_xor:
696 case AtomicExpr::AO__atomic_fetch_and:
697 case AtomicExpr::AO__atomic_fetch_or:
698 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smith51b92402012-04-13 06:31:38 +0000699 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithff34d402012-04-12 05:08:17 +0000700 case AtomicExpr::AO__atomic_and_fetch:
701 case AtomicExpr::AO__atomic_or_fetch:
702 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smith51b92402012-04-13 06:31:38 +0000703 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithff34d402012-04-12 05:08:17 +0000704 Form = Arithmetic;
705 break;
706
707 case AtomicExpr::AO__c11_atomic_exchange:
708 case AtomicExpr::AO__atomic_exchange_n:
709 Form = Xchg;
710 break;
711
712 case AtomicExpr::AO__atomic_exchange:
713 Form = GNUXchg;
714 break;
715
716 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
717 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
718 Form = C11CmpXchg;
719 break;
720
721 case AtomicExpr::AO__atomic_compare_exchange:
722 case AtomicExpr::AO__atomic_compare_exchange_n:
723 Form = GNUCmpXchg;
724 break;
725 }
726
727 // Check we have the right number of arguments.
728 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedman276b0612011-10-11 02:20:01 +0000729 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithff34d402012-04-12 05:08:17 +0000730 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +0000731 << TheCall->getCallee()->getSourceRange();
732 return ExprError();
Richard Smithff34d402012-04-12 05:08:17 +0000733 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
734 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedman276b0612011-10-11 02:20:01 +0000735 diag::err_typecheck_call_too_many_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();
739 }
740
Richard Smithff34d402012-04-12 05:08:17 +0000741 // Inspect the first argument of the atomic operation.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000742 Expr *Ptr = TheCall->getArg(0);
Eli Friedman276b0612011-10-11 02:20:01 +0000743 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
744 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
745 if (!pointerType) {
Richard Smithff34d402012-04-12 05:08:17 +0000746 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedman276b0612011-10-11 02:20:01 +0000747 << Ptr->getType() << Ptr->getSourceRange();
748 return ExprError();
749 }
750
Richard Smithff34d402012-04-12 05:08:17 +0000751 // For a __c11 builtin, this should be a pointer to an _Atomic type.
752 QualType AtomTy = pointerType->getPointeeType(); // 'A'
753 QualType ValType = AtomTy; // 'C'
754 if (IsC11) {
755 if (!AtomTy->isAtomicType()) {
756 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
757 << Ptr->getType() << Ptr->getSourceRange();
758 return ExprError();
759 }
Richard Smithbc57b102012-09-15 06:09:58 +0000760 if (AtomTy.isConstQualified()) {
761 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
762 << Ptr->getType() << Ptr->getSourceRange();
763 return ExprError();
764 }
Richard Smithff34d402012-04-12 05:08:17 +0000765 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedman276b0612011-10-11 02:20:01 +0000766 }
Eli Friedman276b0612011-10-11 02:20:01 +0000767
Richard Smithff34d402012-04-12 05:08:17 +0000768 // For an arithmetic operation, the implied arithmetic must be well-formed.
769 if (Form == Arithmetic) {
770 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
771 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
772 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
773 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
774 return ExprError();
775 }
776 if (!IsAddSub && !ValType->isIntegerType()) {
777 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
778 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
779 return ExprError();
780 }
781 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
782 // For __atomic_*_n operations, the value type must be a scalar integral or
783 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedman276b0612011-10-11 02:20:01 +0000784 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithff34d402012-04-12 05:08:17 +0000785 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
786 return ExprError();
787 }
788
789 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context)) {
790 // For GNU atomics, require a trivially-copyable type. This is not part of
791 // the GNU atomics specification, but we enforce it for sanity.
792 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedman276b0612011-10-11 02:20:01 +0000793 << Ptr->getType() << Ptr->getSourceRange();
794 return ExprError();
795 }
796
Richard Smithff34d402012-04-12 05:08:17 +0000797 // FIXME: For any builtin other than a load, the ValType must not be
798 // const-qualified.
Eli Friedman276b0612011-10-11 02:20:01 +0000799
800 switch (ValType.getObjCLifetime()) {
801 case Qualifiers::OCL_None:
802 case Qualifiers::OCL_ExplicitNone:
803 // okay
804 break;
805
806 case Qualifiers::OCL_Weak:
807 case Qualifiers::OCL_Strong:
808 case Qualifiers::OCL_Autoreleasing:
Richard Smithff34d402012-04-12 05:08:17 +0000809 // FIXME: Can this happen? By this point, ValType should be known
810 // to be trivially copyable.
Eli Friedman276b0612011-10-11 02:20:01 +0000811 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
812 << ValType << Ptr->getSourceRange();
813 return ExprError();
814 }
815
816 QualType ResultType = ValType;
Richard Smithff34d402012-04-12 05:08:17 +0000817 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedman276b0612011-10-11 02:20:01 +0000818 ResultType = Context.VoidTy;
Richard Smithff34d402012-04-12 05:08:17 +0000819 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedman276b0612011-10-11 02:20:01 +0000820 ResultType = Context.BoolTy;
821
Richard Smithff34d402012-04-12 05:08:17 +0000822 // The type of a parameter passed 'by value'. In the GNU atomics, such
823 // arguments are actually passed as pointers.
824 QualType ByValType = ValType; // 'CP'
825 if (!IsC11 && !IsN)
826 ByValType = Ptr->getType();
827
Eli Friedman276b0612011-10-11 02:20:01 +0000828 // The first argument --- the pointer --- has a fixed type; we
829 // deduce the types of the rest of the arguments accordingly. Walk
830 // the remaining arguments, converting them to the deduced value type.
Richard Smithff34d402012-04-12 05:08:17 +0000831 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedman276b0612011-10-11 02:20:01 +0000832 QualType Ty;
Richard Smithff34d402012-04-12 05:08:17 +0000833 if (i < NumVals[Form] + 1) {
834 switch (i) {
835 case 1:
836 // The second argument is the non-atomic operand. For arithmetic, this
837 // is always passed by value, and for a compare_exchange it is always
838 // passed by address. For the rest, GNU uses by-address and C11 uses
839 // by-value.
840 assert(Form != Load);
841 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
842 Ty = ValType;
843 else if (Form == Copy || Form == Xchg)
844 Ty = ByValType;
845 else if (Form == Arithmetic)
846 Ty = Context.getPointerDiffType();
847 else
848 Ty = Context.getPointerType(ValType.getUnqualifiedType());
849 break;
850 case 2:
851 // The third argument to compare_exchange / GNU exchange is a
852 // (pointer to a) desired value.
853 Ty = ByValType;
854 break;
855 case 3:
856 // The fourth argument to GNU compare_exchange is a 'weak' flag.
857 Ty = Context.BoolTy;
858 break;
859 }
Eli Friedman276b0612011-10-11 02:20:01 +0000860 } else {
861 // The order(s) are always converted to int.
862 Ty = Context.IntTy;
863 }
Richard Smithff34d402012-04-12 05:08:17 +0000864
Eli Friedman276b0612011-10-11 02:20:01 +0000865 InitializedEntity Entity =
866 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithff34d402012-04-12 05:08:17 +0000867 ExprResult Arg = TheCall->getArg(i);
Eli Friedman276b0612011-10-11 02:20:01 +0000868 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
869 if (Arg.isInvalid())
870 return true;
871 TheCall->setArg(i, Arg.get());
872 }
873
Richard Smithff34d402012-04-12 05:08:17 +0000874 // Permute the arguments into a 'consistent' order.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000875 SmallVector<Expr*, 5> SubExprs;
876 SubExprs.push_back(Ptr);
Richard Smithff34d402012-04-12 05:08:17 +0000877 switch (Form) {
878 case Init:
879 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnall7a7ee302012-01-16 17:27:18 +0000880 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +0000881 break;
882 case Load:
883 SubExprs.push_back(TheCall->getArg(1)); // Order
884 break;
885 case Copy:
886 case Arithmetic:
887 case Xchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000888 SubExprs.push_back(TheCall->getArg(2)); // Order
889 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +0000890 break;
891 case GNUXchg:
892 // Note, AtomicExpr::getVal2() has a special case for this atomic.
893 SubExprs.push_back(TheCall->getArg(3)); // Order
894 SubExprs.push_back(TheCall->getArg(1)); // Val1
895 SubExprs.push_back(TheCall->getArg(2)); // Val2
896 break;
897 case C11CmpXchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000898 SubExprs.push_back(TheCall->getArg(3)); // Order
899 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000900 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall2ebb98a2012-03-29 17:58:59 +0000901 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithff34d402012-04-12 05:08:17 +0000902 break;
903 case GNUCmpXchg:
904 SubExprs.push_back(TheCall->getArg(4)); // Order
905 SubExprs.push_back(TheCall->getArg(1)); // Val1
906 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
907 SubExprs.push_back(TheCall->getArg(2)); // Val2
908 SubExprs.push_back(TheCall->getArg(3)); // Weak
909 break;
Eli Friedman276b0612011-10-11 02:20:01 +0000910 }
Fariborz Jahanian538bbe52013-05-28 17:37:39 +0000911
912 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
913 SubExprs, ResultType, Op,
914 TheCall->getRParenLoc());
915
916 if ((Op == AtomicExpr::AO__c11_atomic_load ||
917 (Op == AtomicExpr::AO__c11_atomic_store)) &&
918 Context.AtomicUsesUnsupportedLibcall(AE))
919 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
920 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000921
Fariborz Jahanian538bbe52013-05-28 17:37:39 +0000922 return Owned(AE);
Eli Friedman276b0612011-10-11 02:20:01 +0000923}
924
925
John McCall5f8d6042011-08-27 01:09:30 +0000926/// checkBuiltinArgument - Given a call to a builtin function, perform
927/// normal type-checking on the given argument, updating the call in
928/// place. This is useful when a builtin function requires custom
929/// type-checking for some of its arguments but not necessarily all of
930/// them.
931///
932/// Returns true on error.
933static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
934 FunctionDecl *Fn = E->getDirectCallee();
935 assert(Fn && "builtin call without direct callee!");
936
937 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
938 InitializedEntity Entity =
939 InitializedEntity::InitializeParameter(S.Context, Param);
940
941 ExprResult Arg = E->getArg(0);
942 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
943 if (Arg.isInvalid())
944 return true;
945
946 E->setArg(ArgIndex, Arg.take());
947 return false;
948}
949
Chris Lattner5caa3702009-05-08 06:58:22 +0000950/// SemaBuiltinAtomicOverloaded - We have a call to a function like
951/// __sync_fetch_and_add, which is an overloaded function based on the pointer
952/// type of its first argument. The main ActOnCallExpr routines have already
953/// promoted the types of arguments because all of these calls are prototyped as
954/// void(...).
955///
956/// This function goes through and does final semantic checking for these
957/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +0000958ExprResult
959Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000960 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +0000961 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
962 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
963
964 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +0000965 if (TheCall->getNumArgs() < 1) {
966 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
967 << 0 << 1 << TheCall->getNumArgs()
968 << TheCall->getCallee()->getSourceRange();
969 return ExprError();
970 }
Mike Stump1eb44332009-09-09 15:08:12 +0000971
Chris Lattner5caa3702009-05-08 06:58:22 +0000972 // Inspect the first argument of the atomic builtin. This should always be
973 // a pointer type, whose element is an integral scalar or pointer type.
974 // Because it is a pointer type, we don't have to worry about any implicit
975 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +0000976 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +0000977 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman8c382062012-01-23 02:35:22 +0000978 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
979 if (FirstArgResult.isInvalid())
980 return ExprError();
981 FirstArg = FirstArgResult.take();
982 TheCall->setArg(0, FirstArg);
983
John McCallf85e1932011-06-15 23:02:42 +0000984 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
985 if (!pointerType) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000986 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
987 << FirstArg->getType() << FirstArg->getSourceRange();
988 return ExprError();
989 }
Mike Stump1eb44332009-09-09 15:08:12 +0000990
John McCallf85e1932011-06-15 23:02:42 +0000991 QualType ValType = pointerType->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +0000992 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +0000993 !ValType->isBlockPointerType()) {
994 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
995 << FirstArg->getType() << FirstArg->getSourceRange();
996 return ExprError();
997 }
Chris Lattner5caa3702009-05-08 06:58:22 +0000998
John McCallf85e1932011-06-15 23:02:42 +0000999 switch (ValType.getObjCLifetime()) {
1000 case Qualifiers::OCL_None:
1001 case Qualifiers::OCL_ExplicitNone:
1002 // okay
1003 break;
1004
1005 case Qualifiers::OCL_Weak:
1006 case Qualifiers::OCL_Strong:
1007 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00001008 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCallf85e1932011-06-15 23:02:42 +00001009 << ValType << FirstArg->getSourceRange();
1010 return ExprError();
1011 }
1012
John McCallb45ae252011-10-05 07:41:44 +00001013 // Strip any qualifiers off ValType.
1014 ValType = ValType.getUnqualifiedType();
1015
Chandler Carruth8d13d222010-07-18 20:54:12 +00001016 // The majority of builtins return a value, but a few have special return
1017 // types, so allow them to override appropriately below.
1018 QualType ResultType = ValType;
1019
Chris Lattner5caa3702009-05-08 06:58:22 +00001020 // We need to figure out which concrete builtin this maps onto. For example,
1021 // __sync_fetch_and_add with a 2 byte object turns into
1022 // __sync_fetch_and_add_2.
1023#define BUILTIN_ROW(x) \
1024 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1025 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +00001026
Chris Lattner5caa3702009-05-08 06:58:22 +00001027 static const unsigned BuiltinIndices[][5] = {
1028 BUILTIN_ROW(__sync_fetch_and_add),
1029 BUILTIN_ROW(__sync_fetch_and_sub),
1030 BUILTIN_ROW(__sync_fetch_and_or),
1031 BUILTIN_ROW(__sync_fetch_and_and),
1032 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +00001033
Chris Lattner5caa3702009-05-08 06:58:22 +00001034 BUILTIN_ROW(__sync_add_and_fetch),
1035 BUILTIN_ROW(__sync_sub_and_fetch),
1036 BUILTIN_ROW(__sync_and_and_fetch),
1037 BUILTIN_ROW(__sync_or_and_fetch),
1038 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +00001039
Chris Lattner5caa3702009-05-08 06:58:22 +00001040 BUILTIN_ROW(__sync_val_compare_and_swap),
1041 BUILTIN_ROW(__sync_bool_compare_and_swap),
1042 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +00001043 BUILTIN_ROW(__sync_lock_release),
1044 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +00001045 };
Mike Stump1eb44332009-09-09 15:08:12 +00001046#undef BUILTIN_ROW
1047
Chris Lattner5caa3702009-05-08 06:58:22 +00001048 // Determine the index of the size.
1049 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +00001050 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +00001051 case 1: SizeIndex = 0; break;
1052 case 2: SizeIndex = 1; break;
1053 case 4: SizeIndex = 2; break;
1054 case 8: SizeIndex = 3; break;
1055 case 16: SizeIndex = 4; break;
1056 default:
Chandler Carruthd2014572010-07-09 18:59:35 +00001057 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1058 << FirstArg->getType() << FirstArg->getSourceRange();
1059 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +00001060 }
Mike Stump1eb44332009-09-09 15:08:12 +00001061
Chris Lattner5caa3702009-05-08 06:58:22 +00001062 // Each of these builtins has one pointer argument, followed by some number of
1063 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1064 // that we ignore. Find out which row of BuiltinIndices to read from as well
1065 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00001066 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +00001067 unsigned BuiltinIndex, NumFixed = 1;
1068 switch (BuiltinID) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001069 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregora9766412011-11-28 16:30:08 +00001070 case Builtin::BI__sync_fetch_and_add:
1071 case Builtin::BI__sync_fetch_and_add_1:
1072 case Builtin::BI__sync_fetch_and_add_2:
1073 case Builtin::BI__sync_fetch_and_add_4:
1074 case Builtin::BI__sync_fetch_and_add_8:
1075 case Builtin::BI__sync_fetch_and_add_16:
1076 BuiltinIndex = 0;
1077 break;
1078
1079 case Builtin::BI__sync_fetch_and_sub:
1080 case Builtin::BI__sync_fetch_and_sub_1:
1081 case Builtin::BI__sync_fetch_and_sub_2:
1082 case Builtin::BI__sync_fetch_and_sub_4:
1083 case Builtin::BI__sync_fetch_and_sub_8:
1084 case Builtin::BI__sync_fetch_and_sub_16:
1085 BuiltinIndex = 1;
1086 break;
1087
1088 case Builtin::BI__sync_fetch_and_or:
1089 case Builtin::BI__sync_fetch_and_or_1:
1090 case Builtin::BI__sync_fetch_and_or_2:
1091 case Builtin::BI__sync_fetch_and_or_4:
1092 case Builtin::BI__sync_fetch_and_or_8:
1093 case Builtin::BI__sync_fetch_and_or_16:
1094 BuiltinIndex = 2;
1095 break;
1096
1097 case Builtin::BI__sync_fetch_and_and:
1098 case Builtin::BI__sync_fetch_and_and_1:
1099 case Builtin::BI__sync_fetch_and_and_2:
1100 case Builtin::BI__sync_fetch_and_and_4:
1101 case Builtin::BI__sync_fetch_and_and_8:
1102 case Builtin::BI__sync_fetch_and_and_16:
1103 BuiltinIndex = 3;
1104 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001105
Douglas Gregora9766412011-11-28 16:30:08 +00001106 case Builtin::BI__sync_fetch_and_xor:
1107 case Builtin::BI__sync_fetch_and_xor_1:
1108 case Builtin::BI__sync_fetch_and_xor_2:
1109 case Builtin::BI__sync_fetch_and_xor_4:
1110 case Builtin::BI__sync_fetch_and_xor_8:
1111 case Builtin::BI__sync_fetch_and_xor_16:
1112 BuiltinIndex = 4;
1113 break;
1114
1115 case Builtin::BI__sync_add_and_fetch:
1116 case Builtin::BI__sync_add_and_fetch_1:
1117 case Builtin::BI__sync_add_and_fetch_2:
1118 case Builtin::BI__sync_add_and_fetch_4:
1119 case Builtin::BI__sync_add_and_fetch_8:
1120 case Builtin::BI__sync_add_and_fetch_16:
1121 BuiltinIndex = 5;
1122 break;
1123
1124 case Builtin::BI__sync_sub_and_fetch:
1125 case Builtin::BI__sync_sub_and_fetch_1:
1126 case Builtin::BI__sync_sub_and_fetch_2:
1127 case Builtin::BI__sync_sub_and_fetch_4:
1128 case Builtin::BI__sync_sub_and_fetch_8:
1129 case Builtin::BI__sync_sub_and_fetch_16:
1130 BuiltinIndex = 6;
1131 break;
1132
1133 case Builtin::BI__sync_and_and_fetch:
1134 case Builtin::BI__sync_and_and_fetch_1:
1135 case Builtin::BI__sync_and_and_fetch_2:
1136 case Builtin::BI__sync_and_and_fetch_4:
1137 case Builtin::BI__sync_and_and_fetch_8:
1138 case Builtin::BI__sync_and_and_fetch_16:
1139 BuiltinIndex = 7;
1140 break;
1141
1142 case Builtin::BI__sync_or_and_fetch:
1143 case Builtin::BI__sync_or_and_fetch_1:
1144 case Builtin::BI__sync_or_and_fetch_2:
1145 case Builtin::BI__sync_or_and_fetch_4:
1146 case Builtin::BI__sync_or_and_fetch_8:
1147 case Builtin::BI__sync_or_and_fetch_16:
1148 BuiltinIndex = 8;
1149 break;
1150
1151 case Builtin::BI__sync_xor_and_fetch:
1152 case Builtin::BI__sync_xor_and_fetch_1:
1153 case Builtin::BI__sync_xor_and_fetch_2:
1154 case Builtin::BI__sync_xor_and_fetch_4:
1155 case Builtin::BI__sync_xor_and_fetch_8:
1156 case Builtin::BI__sync_xor_and_fetch_16:
1157 BuiltinIndex = 9;
1158 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001159
Chris Lattner5caa3702009-05-08 06:58:22 +00001160 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001161 case Builtin::BI__sync_val_compare_and_swap_1:
1162 case Builtin::BI__sync_val_compare_and_swap_2:
1163 case Builtin::BI__sync_val_compare_and_swap_4:
1164 case Builtin::BI__sync_val_compare_and_swap_8:
1165 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001166 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +00001167 NumFixed = 2;
1168 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001169
Chris Lattner5caa3702009-05-08 06:58:22 +00001170 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001171 case Builtin::BI__sync_bool_compare_and_swap_1:
1172 case Builtin::BI__sync_bool_compare_and_swap_2:
1173 case Builtin::BI__sync_bool_compare_and_swap_4:
1174 case Builtin::BI__sync_bool_compare_and_swap_8:
1175 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001176 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +00001177 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001178 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001179 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001180
1181 case Builtin::BI__sync_lock_test_and_set:
1182 case Builtin::BI__sync_lock_test_and_set_1:
1183 case Builtin::BI__sync_lock_test_and_set_2:
1184 case Builtin::BI__sync_lock_test_and_set_4:
1185 case Builtin::BI__sync_lock_test_and_set_8:
1186 case Builtin::BI__sync_lock_test_and_set_16:
1187 BuiltinIndex = 12;
1188 break;
1189
Chris Lattner5caa3702009-05-08 06:58:22 +00001190 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +00001191 case Builtin::BI__sync_lock_release_1:
1192 case Builtin::BI__sync_lock_release_2:
1193 case Builtin::BI__sync_lock_release_4:
1194 case Builtin::BI__sync_lock_release_8:
1195 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001196 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +00001197 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001198 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001199 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001200
1201 case Builtin::BI__sync_swap:
1202 case Builtin::BI__sync_swap_1:
1203 case Builtin::BI__sync_swap_2:
1204 case Builtin::BI__sync_swap_4:
1205 case Builtin::BI__sync_swap_8:
1206 case Builtin::BI__sync_swap_16:
1207 BuiltinIndex = 14;
1208 break;
Chris Lattner5caa3702009-05-08 06:58:22 +00001209 }
Mike Stump1eb44332009-09-09 15:08:12 +00001210
Chris Lattner5caa3702009-05-08 06:58:22 +00001211 // Now that we know how many fixed arguments we expect, first check that we
1212 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +00001213 if (TheCall->getNumArgs() < 1+NumFixed) {
1214 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1215 << 0 << 1+NumFixed << TheCall->getNumArgs()
1216 << TheCall->getCallee()->getSourceRange();
1217 return ExprError();
1218 }
Mike Stump1eb44332009-09-09 15:08:12 +00001219
Chris Lattnere7ac0a92009-05-08 15:36:58 +00001220 // Get the decl for the concrete builtin from this, we can tell what the
1221 // concrete integer type we should convert to is.
1222 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1223 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara2ad11cd2012-09-22 09:05:22 +00001224 FunctionDecl *NewBuiltinDecl;
1225 if (NewBuiltinID == BuiltinID)
1226 NewBuiltinDecl = FDecl;
1227 else {
1228 // Perform builtin lookup to avoid redeclaring it.
1229 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1230 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1231 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1232 assert(Res.getFoundDecl());
1233 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
1234 if (NewBuiltinDecl == 0)
1235 return ExprError();
1236 }
Chandler Carruthd2014572010-07-09 18:59:35 +00001237
John McCallf871d0c2010-08-07 06:22:56 +00001238 // The first argument --- the pointer --- has a fixed type; we
1239 // deduce the types of the rest of the arguments accordingly. Walk
1240 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +00001241 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +00001242 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +00001243
Chris Lattner5caa3702009-05-08 06:58:22 +00001244 // GCC does an implicit conversion to the pointer or integer ValType. This
1245 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb45ae252011-10-05 07:41:44 +00001246 // Initialize the argument.
1247 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1248 ValType, /*consume*/ false);
1249 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley429bb272011-04-08 18:41:53 +00001250 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +00001251 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001252
Chris Lattner5caa3702009-05-08 06:58:22 +00001253 // Okay, we have something that *can* be converted to the right type. Check
1254 // to see if there is a potentially weird extension going on here. This can
1255 // happen when you do an atomic operation on something like an char* and
1256 // pass in 42. The 42 gets converted to char. This is even more strange
1257 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +00001258 // FIXME: Do this check.
John McCallb45ae252011-10-05 07:41:44 +00001259 TheCall->setArg(i+1, Arg.take());
Chris Lattner5caa3702009-05-08 06:58:22 +00001260 }
Mike Stump1eb44332009-09-09 15:08:12 +00001261
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001262 ASTContext& Context = this->getASTContext();
1263
1264 // Create a new DeclRefExpr to refer to the new decl.
1265 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1266 Context,
1267 DRE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001268 SourceLocation(),
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001269 NewBuiltinDecl,
John McCallf4b88a42012-03-10 09:33:50 +00001270 /*enclosing*/ false,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001271 DRE->getLocation(),
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001272 Context.BuiltinFnTy,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001273 DRE->getValueKind());
Mike Stump1eb44332009-09-09 15:08:12 +00001274
Chris Lattner5caa3702009-05-08 06:58:22 +00001275 // Set the callee in the CallExpr.
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001276 // FIXME: This loses syntactic information.
1277 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1278 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1279 CK_BuiltinFnToFnPtr);
John Wiegley429bb272011-04-08 18:41:53 +00001280 TheCall->setCallee(PromotedCall.take());
Mike Stump1eb44332009-09-09 15:08:12 +00001281
Chandler Carruthdb4325b2010-07-18 07:23:17 +00001282 // Change the result type of the call to match the original value type. This
1283 // is arbitrary, but the codegen for these builtins ins design to handle it
1284 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +00001285 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +00001286
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001287 return TheCallResult;
Chris Lattner5caa3702009-05-08 06:58:22 +00001288}
1289
Chris Lattner69039812009-02-18 06:01:06 +00001290/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +00001291/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +00001292/// Note: It might also make sense to do the UTF-16 conversion here (would
1293/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +00001294bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +00001295 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +00001296 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1297
Douglas Gregor5cee1192011-07-27 05:40:30 +00001298 if (!Literal || !Literal->isAscii()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001299 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1300 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001301 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +00001302 }
Mike Stump1eb44332009-09-09 15:08:12 +00001303
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001304 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001305 StringRef String = Literal->getString();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001306 unsigned NumBytes = String.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001307 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divacky31ba6132012-09-06 15:59:27 +00001308 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001309 UTF16 *ToPtr = &ToBuf[0];
1310
1311 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1312 &ToPtr, ToPtr + NumBytes,
1313 strictConversion);
1314 // Check for conversion failure.
1315 if (Result != conversionOK)
1316 Diag(Arg->getLocStart(),
1317 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1318 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001319 return false;
Chris Lattner59907c42007-08-10 20:18:51 +00001320}
1321
Chris Lattnerc27c6652007-12-20 00:05:45 +00001322/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1323/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +00001324bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1325 Expr *Fn = TheCall->getCallee();
1326 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +00001327 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001328 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001329 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1330 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +00001331 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001332 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +00001333 return true;
1334 }
Eli Friedman56f20ae2008-12-15 22:05:35 +00001335
1336 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +00001337 return Diag(TheCall->getLocEnd(),
1338 diag::err_typecheck_call_too_few_args_at_least)
1339 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +00001340 }
1341
John McCall5f8d6042011-08-27 01:09:30 +00001342 // Type-check the first argument normally.
1343 if (checkBuiltinArgument(*this, TheCall, 0))
1344 return true;
1345
Chris Lattnerc27c6652007-12-20 00:05:45 +00001346 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001347 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +00001348 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001349 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +00001350 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +00001351 else if (FunctionDecl *FD = getCurFunctionDecl())
1352 isVariadic = FD->isVariadic();
1353 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001354 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +00001355
Chris Lattnerc27c6652007-12-20 00:05:45 +00001356 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001357 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1358 return true;
1359 }
Mike Stump1eb44332009-09-09 15:08:12 +00001360
Chris Lattner30ce3442007-12-19 23:59:04 +00001361 // Verify that the second argument to the builtin is the last argument of the
1362 // current function or method.
1363 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +00001364 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001365
Nico Weberb07d4482013-05-24 23:31:57 +00001366 // These are valid if SecondArgIsLastNamedArgument is false after the next
1367 // block.
1368 QualType Type;
1369 SourceLocation ParamLoc;
1370
Anders Carlsson88cf2262008-02-11 04:20:54 +00001371 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1372 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001373 // FIXME: This isn't correct for methods (results in bogus warning).
1374 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +00001375 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001376 if (CurBlock)
1377 LastArg = *(CurBlock->TheDecl->param_end()-1);
1378 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +00001379 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001380 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001381 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001382 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weberb07d4482013-05-24 23:31:57 +00001383
1384 Type = PV->getType();
1385 ParamLoc = PV->getLocation();
Chris Lattner30ce3442007-12-19 23:59:04 +00001386 }
1387 }
Mike Stump1eb44332009-09-09 15:08:12 +00001388
Chris Lattner30ce3442007-12-19 23:59:04 +00001389 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001390 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +00001391 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weberb07d4482013-05-24 23:31:57 +00001392 else if (Type->isReferenceType()) {
1393 Diag(Arg->getLocStart(),
1394 diag::warn_va_start_of_reference_type_is_undefined);
1395 Diag(ParamLoc, diag::note_parameter_type) << Type;
1396 }
1397
Chris Lattner30ce3442007-12-19 23:59:04 +00001398 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +00001399}
Chris Lattner30ce3442007-12-19 23:59:04 +00001400
Chris Lattner1b9a0792007-12-20 00:26:33 +00001401/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1402/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +00001403bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1404 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +00001405 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001406 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +00001407 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +00001408 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001409 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001410 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001411 << SourceRange(TheCall->getArg(2)->getLocStart(),
1412 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001413
John Wiegley429bb272011-04-08 18:41:53 +00001414 ExprResult OrigArg0 = TheCall->getArg(0);
1415 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +00001416
Chris Lattner1b9a0792007-12-20 00:26:33 +00001417 // Do standard promotions between the two arguments, returning their common
1418 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +00001419 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +00001420 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1421 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +00001422
1423 // Make sure any conversions are pushed back into the call; this is
1424 // type safe since unordered compare builtins are declared as "_Bool
1425 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +00001426 TheCall->setArg(0, OrigArg0.get());
1427 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001428
John Wiegley429bb272011-04-08 18:41:53 +00001429 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +00001430 return false;
1431
Chris Lattner1b9a0792007-12-20 00:26:33 +00001432 // If the common type isn't a real floating type, then the arguments were
1433 // invalid for this operation.
Eli Friedman860a3192012-06-16 02:19:17 +00001434 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +00001435 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001436 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +00001437 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1438 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001439
Chris Lattner1b9a0792007-12-20 00:26:33 +00001440 return false;
1441}
1442
Benjamin Kramere771a7a2010-02-15 22:42:31 +00001443/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1444/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001445/// to check everything. We expect the last argument to be a floating point
1446/// value.
1447bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1448 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +00001449 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001450 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001451 if (TheCall->getNumArgs() > NumArgs)
1452 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001453 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001454 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001455 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001456 (*(TheCall->arg_end()-1))->getLocEnd());
1457
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001458 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001459
Eli Friedman9ac6f622009-08-31 20:06:00 +00001460 if (OrigArg->isTypeDependent())
1461 return false;
1462
Chris Lattner81368fb2010-05-06 05:50:07 +00001463 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +00001464 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +00001465 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001466 diag::err_typecheck_call_invalid_unary_fp)
1467 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001468
Chris Lattner81368fb2010-05-06 05:50:07 +00001469 // If this is an implicit conversion from float -> double, remove it.
1470 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1471 Expr *CastArg = Cast->getSubExpr();
1472 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1473 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1474 "promotion from float to double is the only expected cast here");
1475 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +00001476 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner81368fb2010-05-06 05:50:07 +00001477 }
1478 }
1479
Eli Friedman9ac6f622009-08-31 20:06:00 +00001480 return false;
1481}
1482
Eli Friedmand38617c2008-05-14 19:38:39 +00001483/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1484// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +00001485ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001486 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001487 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +00001488 diag::err_typecheck_call_too_few_args_at_least)
Nate Begeman37b6a572010-06-08 00:16:34 +00001489 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherd77b9a22010-04-16 04:48:22 +00001490 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001491
Nate Begeman37b6a572010-06-08 00:16:34 +00001492 // Determine which of the following types of shufflevector we're checking:
1493 // 1) unary, vector mask: (lhs, mask)
1494 // 2) binary, vector mask: (lhs, rhs, mask)
1495 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1496 QualType resType = TheCall->getArg(0)->getType();
1497 unsigned numElements = 0;
1498
Douglas Gregorcde01732009-05-19 22:10:17 +00001499 if (!TheCall->getArg(0)->isTypeDependent() &&
1500 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001501 QualType LHSType = TheCall->getArg(0)->getType();
1502 QualType RHSType = TheCall->getArg(1)->getType();
1503
1504 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001505 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001506 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001507 TheCall->getArg(1)->getLocEnd());
1508 return ExprError();
1509 }
Nate Begeman37b6a572010-06-08 00:16:34 +00001510
1511 numElements = LHSType->getAs<VectorType>()->getNumElements();
1512 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +00001513
Nate Begeman37b6a572010-06-08 00:16:34 +00001514 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1515 // with mask. If so, verify that RHS is an integer vector type with the
1516 // same number of elts as lhs.
1517 if (TheCall->getNumArgs() == 2) {
Douglas Gregorf6094622010-07-23 15:58:24 +00001518 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +00001519 RHSType->getAs<VectorType>()->getNumElements() != numElements)
1520 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1521 << SourceRange(TheCall->getArg(1)->getLocStart(),
1522 TheCall->getArg(1)->getLocEnd());
1523 numResElements = numElements;
1524 }
1525 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001526 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001527 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001528 TheCall->getArg(1)->getLocEnd());
1529 return ExprError();
Nate Begeman37b6a572010-06-08 00:16:34 +00001530 } else if (numElements != numResElements) {
1531 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +00001532 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001533 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +00001534 }
Eli Friedmand38617c2008-05-14 19:38:39 +00001535 }
1536
1537 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001538 if (TheCall->getArg(i)->isTypeDependent() ||
1539 TheCall->getArg(i)->isValueDependent())
1540 continue;
1541
Nate Begeman37b6a572010-06-08 00:16:34 +00001542 llvm::APSInt Result(32);
1543 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1544 return ExprError(Diag(TheCall->getLocStart(),
1545 diag::err_shufflevector_nonconstant_argument)
1546 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001547
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001548 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001549 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001550 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001551 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001552 }
1553
Chris Lattner5f9e2722011-07-23 10:55:15 +00001554 SmallVector<Expr*, 32> exprs;
Eli Friedmand38617c2008-05-14 19:38:39 +00001555
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001556 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +00001557 exprs.push_back(TheCall->getArg(i));
1558 TheCall->setArg(i, 0);
1559 }
1560
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001561 return Owned(new (Context) ShuffleVectorExpr(Context, exprs, resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001562 TheCall->getCallee()->getLocStart(),
1563 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +00001564}
Chris Lattner30ce3442007-12-19 23:59:04 +00001565
Daniel Dunbar4493f792008-07-21 22:59:13 +00001566/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1567// This is declared to take (const void*, ...) and can take two
1568// optional constant int args.
1569bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001570 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001571
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001572 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +00001573 return Diag(TheCall->getLocEnd(),
1574 diag::err_typecheck_call_too_many_args_at_most)
1575 << 0 /*function call*/ << 3 << NumArgs
1576 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001577
1578 // Argument 0 is checked for us and the remaining arguments must be
1579 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001580 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +00001581 Expr *Arg = TheCall->getArg(i);
Douglas Gregor592a4232012-06-29 01:05:22 +00001582
1583 // We can't check the value of a dependent argument.
1584 if (Arg->isTypeDependent() || Arg->isValueDependent())
1585 continue;
1586
Eli Friedman9aef7262009-12-04 00:30:06 +00001587 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +00001588 if (SemaBuiltinConstantArg(TheCall, i, Result))
1589 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001590
Daniel Dunbar4493f792008-07-21 22:59:13 +00001591 // FIXME: gcc issues a warning and rewrites these to 0. These
1592 // seems especially odd for the third argument since the default
1593 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001594 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +00001595 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001596 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001597 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001598 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +00001599 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001600 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001601 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001602 }
1603 }
1604
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001605 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +00001606}
1607
Eric Christopher691ebc32010-04-17 02:26:23 +00001608/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1609/// TheCall is a constant expression.
1610bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1611 llvm::APSInt &Result) {
1612 Expr *Arg = TheCall->getArg(ArgNum);
1613 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1614 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1615
1616 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1617
1618 if (!Arg->isIntegerConstantExpr(Result, Context))
1619 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +00001620 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +00001621
Chris Lattner21fb98e2009-09-23 06:06:36 +00001622 return false;
1623}
1624
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001625/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1626/// int type). This simply type checks that type is one of the defined
1627/// constants (0-3).
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001628// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001629bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +00001630 llvm::APSInt Result;
Douglas Gregor592a4232012-06-29 01:05:22 +00001631
1632 // We can't check the value of a dependent argument.
1633 if (TheCall->getArg(1)->isTypeDependent() ||
1634 TheCall->getArg(1)->isValueDependent())
1635 return false;
1636
Eric Christopher691ebc32010-04-17 02:26:23 +00001637 // Check constant-ness first.
1638 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1639 return true;
1640
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001641 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001642 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001643 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1644 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001645 }
1646
1647 return false;
1648}
1649
Eli Friedman586d6a82009-05-03 06:04:26 +00001650/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +00001651/// This checks that val is a constant 1.
1652bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1653 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +00001654 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +00001655
Eric Christopher691ebc32010-04-17 02:26:23 +00001656 // TODO: This is less than ideal. Overload this to take a value.
1657 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1658 return true;
1659
1660 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +00001661 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1662 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1663
1664 return false;
1665}
1666
Richard Smith831421f2012-06-25 20:30:08 +00001667// Determine if an expression is a string literal or constant string.
1668// If this function returns false on the arguments to a function expecting a
1669// format string, we will usually need to emit a warning.
1670// True string literals are then checked by CheckFormatString.
1671Sema::StringLiteralCheckType
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001672Sema::checkFormatStringExpr(const Expr *E, ArrayRef<const Expr *> Args,
1673 bool HasVAListArg,
Richard Smith831421f2012-06-25 20:30:08 +00001674 unsigned format_idx, unsigned firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001675 FormatStringType Type, VariadicCallType CallType,
1676 bool inFunctionCall) {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001677 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +00001678 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith831421f2012-06-25 20:30:08 +00001679 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001680
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001681 E = E->IgnoreParenCasts();
Peter Collingbournef111d932011-04-15 00:35:48 +00001682
David Blaikiea73cdcb2012-02-10 21:07:25 +00001683 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
1684 // Technically -Wformat-nonliteral does not warn about this case.
1685 // The behavior of printf and friends in this case is implementation
1686 // dependent. Ideally if the format string cannot be null then
1687 // it should have a 'nonnull' attribute in the function prototype.
Richard Smith831421f2012-06-25 20:30:08 +00001688 return SLCT_CheckedLiteral;
David Blaikiea73cdcb2012-02-10 21:07:25 +00001689
Ted Kremenekd30ef872009-01-12 23:09:09 +00001690 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +00001691 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +00001692 case Stmt::ConditionalOperatorClass: {
Richard Smith831421f2012-06-25 20:30:08 +00001693 // The expression is a literal if both sub-expressions were, and it was
1694 // completely checked only if both sub-expressions were checked.
1695 const AbstractConditionalOperator *C =
1696 cast<AbstractConditionalOperator>(E);
1697 StringLiteralCheckType Left =
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001698 checkFormatStringExpr(C->getTrueExpr(), Args,
Richard Smith831421f2012-06-25 20:30:08 +00001699 HasVAListArg, format_idx, firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001700 Type, CallType, inFunctionCall);
Richard Smith831421f2012-06-25 20:30:08 +00001701 if (Left == SLCT_NotALiteral)
1702 return SLCT_NotALiteral;
1703 StringLiteralCheckType Right =
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001704 checkFormatStringExpr(C->getFalseExpr(), 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 return Left < Right ? Left : Right;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001708 }
1709
1710 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001711 E = cast<ImplicitCastExpr>(E)->getSubExpr();
1712 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001713 }
1714
John McCall56ca35d2011-02-17 10:25:35 +00001715 case Stmt::OpaqueValueExprClass:
1716 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
1717 E = src;
1718 goto tryAgain;
1719 }
Richard Smith831421f2012-06-25 20:30:08 +00001720 return SLCT_NotALiteral;
John McCall56ca35d2011-02-17 10:25:35 +00001721
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001722 case Stmt::PredefinedExprClass:
1723 // While __func__, etc., are technically not string literals, they
1724 // cannot contain format specifiers and thus are not a security
1725 // liability.
Richard Smith831421f2012-06-25 20:30:08 +00001726 return SLCT_UncheckedLiteral;
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001727
Ted Kremenek082d9362009-03-20 21:35:28 +00001728 case Stmt::DeclRefExprClass: {
1729 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001730
Ted Kremenek082d9362009-03-20 21:35:28 +00001731 // As an exception, do not flag errors for variables binding to
1732 // const string literals.
1733 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1734 bool isConstant = false;
1735 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001736
Ted Kremenek082d9362009-03-20 21:35:28 +00001737 if (const ArrayType *AT = Context.getAsArrayType(T)) {
1738 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001739 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001740 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +00001741 PT->getPointeeType().isConstant(Context);
Jean-Daniel Dupase98e5b52012-01-25 10:35:33 +00001742 } else if (T->isObjCObjectPointerType()) {
1743 // In ObjC, there is usually no "const ObjectPointer" type,
1744 // so don't check if the pointee type is constant.
1745 isConstant = T.isConstant(Context);
Ted Kremenek082d9362009-03-20 21:35:28 +00001746 }
Mike Stump1eb44332009-09-09 15:08:12 +00001747
Ted Kremenek082d9362009-03-20 21:35:28 +00001748 if (isConstant) {
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00001749 if (const Expr *Init = VD->getAnyInitializer()) {
1750 // Look through initializers like const char c[] = { "foo" }
1751 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
1752 if (InitList->isStringLiteralInit())
1753 Init = InitList->getInit(0)->IgnoreParenImpCasts();
1754 }
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001755 return checkFormatStringExpr(Init, Args,
Richard Smith831421f2012-06-25 20:30:08 +00001756 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001757 firstDataArg, Type, CallType,
Richard Smith831421f2012-06-25 20:30:08 +00001758 /*inFunctionCall*/false);
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00001759 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001760 }
Mike Stump1eb44332009-09-09 15:08:12 +00001761
Anders Carlssond966a552009-06-28 19:55:58 +00001762 // For vprintf* functions (i.e., HasVAListArg==true), we add a
1763 // special check to see if the format string is a function parameter
1764 // of the function calling the printf function. If the function
1765 // has an attribute indicating it is a printf-like function, then we
1766 // should suppress warnings concerning non-literals being used in a call
1767 // to a vprintf function. For example:
1768 //
1769 // void
1770 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1771 // va_list ap;
1772 // va_start(ap, fmt);
1773 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
1774 // ...
1775 //
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00001776 if (HasVAListArg) {
1777 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
1778 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
1779 int PVIndex = PV->getFunctionScopeIndex() + 1;
1780 for (specific_attr_iterator<FormatAttr>
1781 i = ND->specific_attr_begin<FormatAttr>(),
1782 e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) {
1783 FormatAttr *PVFormat = *i;
1784 // adjust for implicit parameter
1785 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1786 if (MD->isInstance())
1787 ++PVIndex;
1788 // We also check if the formats are compatible.
1789 // We can't pass a 'scanf' string to a 'printf' function.
1790 if (PVIndex == PVFormat->getFormatIdx() &&
1791 Type == GetFormatStringType(PVFormat))
Richard Smith831421f2012-06-25 20:30:08 +00001792 return SLCT_UncheckedLiteral;
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00001793 }
1794 }
1795 }
1796 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001797 }
Mike Stump1eb44332009-09-09 15:08:12 +00001798
Richard Smith831421f2012-06-25 20:30:08 +00001799 return SLCT_NotALiteral;
Ted Kremenek082d9362009-03-20 21:35:28 +00001800 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00001801
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001802 case Stmt::CallExprClass:
1803 case Stmt::CXXMemberCallExprClass: {
Anders Carlsson8f031b32009-06-27 04:05:33 +00001804 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001805 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
1806 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
1807 unsigned ArgIndex = FA->getFormatIdx();
1808 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1809 if (MD->isInstance())
1810 --ArgIndex;
1811 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001812
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001813 return checkFormatStringExpr(Arg, Args,
Richard Smith831421f2012-06-25 20:30:08 +00001814 HasVAListArg, format_idx, firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001815 Type, CallType, inFunctionCall);
Jordan Rose50687312012-06-04 23:52:23 +00001816 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
1817 unsigned BuiltinID = FD->getBuiltinID();
1818 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
1819 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
1820 const Expr *Arg = CE->getArg(0);
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001821 return checkFormatStringExpr(Arg, Args,
Richard Smith831421f2012-06-25 20:30:08 +00001822 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001823 firstDataArg, Type, CallType,
1824 inFunctionCall);
Jordan Rose50687312012-06-04 23:52:23 +00001825 }
Anders Carlsson8f031b32009-06-27 04:05:33 +00001826 }
1827 }
Mike Stump1eb44332009-09-09 15:08:12 +00001828
Richard Smith831421f2012-06-25 20:30:08 +00001829 return SLCT_NotALiteral;
Anders Carlsson8f031b32009-06-27 04:05:33 +00001830 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001831 case Stmt::ObjCStringLiteralClass:
1832 case Stmt::StringLiteralClass: {
1833 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001834
Ted Kremenek082d9362009-03-20 21:35:28 +00001835 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00001836 StrE = ObjCFExpr->getString();
1837 else
Ted Kremenek082d9362009-03-20 21:35:28 +00001838 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001839
Ted Kremenekd30ef872009-01-12 23:09:09 +00001840 if (StrE) {
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001841 CheckFormatString(StrE, E, Args, HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001842 firstDataArg, Type, inFunctionCall, CallType);
Richard Smith831421f2012-06-25 20:30:08 +00001843 return SLCT_CheckedLiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001844 }
Mike Stump1eb44332009-09-09 15:08:12 +00001845
Richard Smith831421f2012-06-25 20:30:08 +00001846 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001847 }
Mike Stump1eb44332009-09-09 15:08:12 +00001848
Ted Kremenek082d9362009-03-20 21:35:28 +00001849 default:
Richard Smith831421f2012-06-25 20:30:08 +00001850 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001851 }
1852}
1853
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001854void
Mike Stump1eb44332009-09-09 15:08:12 +00001855Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewycky909a70d2011-03-25 01:44:32 +00001856 const Expr * const *ExprArgs,
1857 SourceLocation CallSiteLoc) {
Sean Huntcf807c42010-08-18 23:23:40 +00001858 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1859 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001860 i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +00001861 const Expr *ArgExpr = ExprArgs[*i];
Nick Lewycky3edf3872013-01-23 05:08:29 +00001862
1863 // As a special case, transparent unions initialized with zero are
1864 // considered null for the purposes of the nonnull attribute.
1865 if (const RecordType *UT = ArgExpr->getType()->getAsUnionType()) {
1866 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
1867 if (const CompoundLiteralExpr *CLE =
1868 dyn_cast<CompoundLiteralExpr>(ArgExpr))
1869 if (const InitListExpr *ILE =
1870 dyn_cast<InitListExpr>(CLE->getInitializer()))
1871 ArgExpr = ILE->getInit(0);
1872 }
1873
1874 bool Result;
1875 if (ArgExpr->EvaluateAsBooleanCondition(Result, Context) && !Result)
Nick Lewycky909a70d2011-03-25 01:44:32 +00001876 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001877 }
1878}
Ted Kremenekd30ef872009-01-12 23:09:09 +00001879
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001880Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
1881 return llvm::StringSwitch<FormatStringType>(Format->getType())
1882 .Case("scanf", FST_Scanf)
1883 .Cases("printf", "printf0", FST_Printf)
1884 .Cases("NSString", "CFString", FST_NSString)
1885 .Case("strftime", FST_Strftime)
1886 .Case("strfmon", FST_Strfmon)
1887 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
1888 .Default(FST_Unknown);
1889}
1890
Jordan Roseddcfbc92012-07-19 18:10:23 +00001891/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek826a3452010-07-16 02:11:22 +00001892/// functions) for correct use of format strings.
Richard Smith831421f2012-06-25 20:30:08 +00001893/// Returns true if a format string has been fully checked.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001894bool Sema::CheckFormatArguments(const FormatAttr *Format,
1895 ArrayRef<const Expr *> Args,
1896 bool IsCXXMember,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001897 VariadicCallType CallType,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001898 SourceLocation Loc, SourceRange Range) {
Richard Smith831421f2012-06-25 20:30:08 +00001899 FormatStringInfo FSI;
1900 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001901 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith831421f2012-06-25 20:30:08 +00001902 FSI.FirstDataArg, GetFormatStringType(Format),
Jordan Roseddcfbc92012-07-19 18:10:23 +00001903 CallType, Loc, Range);
Richard Smith831421f2012-06-25 20:30:08 +00001904 return false;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001905}
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001906
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001907bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001908 bool HasVAListArg, unsigned format_idx,
1909 unsigned firstDataArg, FormatStringType Type,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001910 VariadicCallType CallType,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001911 SourceLocation Loc, SourceRange Range) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001912 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001913 if (format_idx >= Args.size()) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001914 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith831421f2012-06-25 20:30:08 +00001915 return false;
Ted Kremenek71895b92007-08-14 17:39:48 +00001916 }
Mike Stump1eb44332009-09-09 15:08:12 +00001917
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001918 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001919
Chris Lattner59907c42007-08-10 20:18:51 +00001920 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001921 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001922 // Dynamically generated format strings are difficult to
1923 // automatically vet at compile time. Requiring that format strings
1924 // are string literals: (1) permits the checking of format strings by
1925 // the compiler and thereby (2) can practically remove the source of
1926 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001927
Mike Stump1eb44332009-09-09 15:08:12 +00001928 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001929 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001930 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001931 // the same format string checking logic for both ObjC and C strings.
Richard Smith831421f2012-06-25 20:30:08 +00001932 StringLiteralCheckType CT =
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001933 checkFormatStringExpr(OrigFormatExpr, Args, HasVAListArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001934 format_idx, firstDataArg, Type, CallType);
Richard Smith831421f2012-06-25 20:30:08 +00001935 if (CT != SLCT_NotALiteral)
1936 // Literal format string found, check done!
1937 return CT == SLCT_CheckedLiteral;
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001938
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00001939 // Strftime is particular as it always uses a single 'time' argument,
1940 // so it is safe to pass a non-literal string.
1941 if (Type == FST_Strftime)
Richard Smith831421f2012-06-25 20:30:08 +00001942 return false;
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00001943
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00001944 // Do not emit diag when the string param is a macro expansion and the
1945 // format is either NSString or CFString. This is a hack to prevent
1946 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
1947 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupasdc170202012-05-04 21:08:08 +00001948 if (Type == FST_NSString &&
1949 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith831421f2012-06-25 20:30:08 +00001950 return false;
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00001951
Chris Lattner655f1412009-04-29 04:59:47 +00001952 // If there are no arguments specified, warn with -Wformat-security, otherwise
1953 // warn only with -Wformat-nonliteral.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001954 if (Args.size() == format_idx+1)
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001955 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001956 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00001957 << OrigFormatExpr->getSourceRange();
1958 else
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001959 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001960 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00001961 << OrigFormatExpr->getSourceRange();
Richard Smith831421f2012-06-25 20:30:08 +00001962 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001963}
Ted Kremenek71895b92007-08-14 17:39:48 +00001964
Ted Kremeneke0e53132010-01-28 23:39:18 +00001965namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00001966class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1967protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001968 Sema &S;
1969 const StringLiteral *FExpr;
1970 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001971 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001972 const unsigned NumDataArgs;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001973 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001974 const bool HasVAListArg;
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001975 ArrayRef<const Expr *> Args;
Ted Kremenek0d277352010-01-29 01:06:55 +00001976 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001977 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00001978 bool usesPositionalArgs;
1979 bool atFirstArg;
Richard Trieu55733de2011-10-28 00:41:25 +00001980 bool inFunctionCall;
Jordan Roseddcfbc92012-07-19 18:10:23 +00001981 Sema::VariadicCallType CallType;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001982public:
Ted Kremenek826a3452010-07-16 02:11:22 +00001983 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00001984 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00001985 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001986 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001987 unsigned formatIdx, bool inFunctionCall,
1988 Sema::VariadicCallType callType)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001989 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose50687312012-06-04 23:52:23 +00001990 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
1991 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001992 Args(Args), FormatIdx(formatIdx),
Richard Trieu55733de2011-10-28 00:41:25 +00001993 usesPositionalArgs(false), atFirstArg(true),
Jordan Roseddcfbc92012-07-19 18:10:23 +00001994 inFunctionCall(inFunctionCall), CallType(callType) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001995 CoveredArgs.resize(numDataArgs);
1996 CoveredArgs.reset();
1997 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001998
Ted Kremenek07d161f2010-01-29 01:50:07 +00001999 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002000
Ted Kremenek826a3452010-07-16 02:11:22 +00002001 void HandleIncompleteSpecifier(const char *startSpecifier,
2002 unsigned specifierLen);
Hans Wennborg76517422012-02-22 10:17:01 +00002003
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002004 void HandleInvalidLengthModifier(
2005 const analyze_format_string::FormatSpecifier &FS,
2006 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose8be066e2012-09-08 04:00:12 +00002007 const char *startSpecifier, unsigned specifierLen, unsigned DiagID);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002008
Hans Wennborg76517422012-02-22 10:17:01 +00002009 void HandleNonStandardLengthModifier(
Jordan Rose8be066e2012-09-08 04:00:12 +00002010 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborg76517422012-02-22 10:17:01 +00002011 const char *startSpecifier, unsigned specifierLen);
2012
2013 void HandleNonStandardConversionSpecifier(
2014 const analyze_format_string::ConversionSpecifier &CS,
2015 const char *startSpecifier, unsigned specifierLen);
2016
Hans Wennborgf8562642012-03-09 10:10:54 +00002017 virtual void HandlePosition(const char *startPos, unsigned posLen);
2018
Ted Kremenekefaff192010-02-27 01:41:03 +00002019 virtual void HandleInvalidPosition(const char *startSpecifier,
2020 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00002021 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00002022
2023 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
2024
Ted Kremeneke0e53132010-01-28 23:39:18 +00002025 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002026
Richard Trieu55733de2011-10-28 00:41:25 +00002027 template <typename Range>
2028 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2029 const Expr *ArgumentExpr,
2030 PartialDiagnostic PDiag,
2031 SourceLocation StringLoc,
2032 bool IsStringLocation, Range StringRange,
Dmitri Gribenko55431692013-05-05 00:41:58 +00002033 ArrayRef<FixItHint> Fixit = None);
Richard Trieu55733de2011-10-28 00:41:25 +00002034
Ted Kremenek826a3452010-07-16 02:11:22 +00002035protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002036 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2037 const char *startSpec,
2038 unsigned specifierLen,
2039 const char *csStart, unsigned csLen);
Richard Trieu55733de2011-10-28 00:41:25 +00002040
2041 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2042 const char *startSpec,
2043 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002044
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002045 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00002046 CharSourceRange getSpecifierRange(const char *startSpecifier,
2047 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002048 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002049
Ted Kremenek0d277352010-01-29 01:06:55 +00002050 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00002051
2052 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2053 const analyze_format_string::ConversionSpecifier &CS,
2054 const char *startSpecifier, unsigned specifierLen,
2055 unsigned argIndex);
Richard Trieu55733de2011-10-28 00:41:25 +00002056
2057 template <typename Range>
2058 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2059 bool IsStringLocation, Range StringRange,
Dmitri Gribenko55431692013-05-05 00:41:58 +00002060 ArrayRef<FixItHint> Fixit = None);
Richard Trieu55733de2011-10-28 00:41:25 +00002061
2062 void CheckPositionalAndNonpositionalArgs(
2063 const analyze_format_string::FormatSpecifier *FS);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002064};
2065}
2066
Ted Kremenek826a3452010-07-16 02:11:22 +00002067SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00002068 return OrigFormatExpr->getSourceRange();
2069}
2070
Ted Kremenek826a3452010-07-16 02:11:22 +00002071CharSourceRange CheckFormatHandler::
2072getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002073 SourceLocation Start = getLocationOfByte(startSpecifier);
2074 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2075
2076 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002077 End = End.getLocWithOffset(1);
Tom Care45f9b7e2010-06-21 21:21:01 +00002078
2079 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002080}
2081
Ted Kremenek826a3452010-07-16 02:11:22 +00002082SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002083 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002084}
2085
Ted Kremenek826a3452010-07-16 02:11:22 +00002086void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2087 unsigned specifierLen){
Richard Trieu55733de2011-10-28 00:41:25 +00002088 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2089 getLocationOfByte(startSpecifier),
2090 /*IsStringLocation*/true,
2091 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek808015a2010-01-29 03:16:21 +00002092}
2093
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002094void CheckFormatHandler::HandleInvalidLengthModifier(
2095 const analyze_format_string::FormatSpecifier &FS,
2096 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose8be066e2012-09-08 04:00:12 +00002097 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002098 using namespace analyze_format_string;
2099
2100 const LengthModifier &LM = FS.getLengthModifier();
2101 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2102
2103 // See if we know how to fix this length modifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002104 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002105 if (FixedLM) {
Jordan Rose8be066e2012-09-08 04:00:12 +00002106 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002107 getLocationOfByte(LM.getStart()),
2108 /*IsStringLocation*/true,
2109 getSpecifierRange(startSpecifier, specifierLen));
2110
2111 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2112 << FixedLM->toString()
2113 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2114
2115 } else {
Jordan Rose8be066e2012-09-08 04:00:12 +00002116 FixItHint Hint;
2117 if (DiagID == diag::warn_format_nonsensical_length)
2118 Hint = FixItHint::CreateRemoval(LMRange);
2119
2120 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002121 getLocationOfByte(LM.getStart()),
2122 /*IsStringLocation*/true,
2123 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose8be066e2012-09-08 04:00:12 +00002124 Hint);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002125 }
2126}
2127
Hans Wennborg76517422012-02-22 10:17:01 +00002128void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose8be066e2012-09-08 04:00:12 +00002129 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborg76517422012-02-22 10:17:01 +00002130 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose8be066e2012-09-08 04:00:12 +00002131 using namespace analyze_format_string;
2132
2133 const LengthModifier &LM = FS.getLengthModifier();
2134 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2135
2136 // See if we know how to fix this length modifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002137 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose8be066e2012-09-08 04:00:12 +00002138 if (FixedLM) {
2139 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2140 << LM.toString() << 0,
2141 getLocationOfByte(LM.getStart()),
2142 /*IsStringLocation*/true,
2143 getSpecifierRange(startSpecifier, specifierLen));
2144
2145 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2146 << FixedLM->toString()
2147 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2148
2149 } else {
2150 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2151 << LM.toString() << 0,
2152 getLocationOfByte(LM.getStart()),
2153 /*IsStringLocation*/true,
2154 getSpecifierRange(startSpecifier, specifierLen));
2155 }
Hans Wennborg76517422012-02-22 10:17:01 +00002156}
2157
2158void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2159 const analyze_format_string::ConversionSpecifier &CS,
2160 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose670941c2012-09-13 02:11:15 +00002161 using namespace analyze_format_string;
2162
2163 // See if we know how to fix this conversion specifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002164 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose670941c2012-09-13 02:11:15 +00002165 if (FixedCS) {
2166 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2167 << CS.toString() << /*conversion specifier*/1,
2168 getLocationOfByte(CS.getStart()),
2169 /*IsStringLocation*/true,
2170 getSpecifierRange(startSpecifier, specifierLen));
2171
2172 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2173 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2174 << FixedCS->toString()
2175 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2176 } else {
2177 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2178 << CS.toString() << /*conversion specifier*/1,
2179 getLocationOfByte(CS.getStart()),
2180 /*IsStringLocation*/true,
2181 getSpecifierRange(startSpecifier, specifierLen));
2182 }
Hans Wennborg76517422012-02-22 10:17:01 +00002183}
2184
Hans Wennborgf8562642012-03-09 10:10:54 +00002185void CheckFormatHandler::HandlePosition(const char *startPos,
2186 unsigned posLen) {
2187 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2188 getLocationOfByte(startPos),
2189 /*IsStringLocation*/true,
2190 getSpecifierRange(startPos, posLen));
2191}
2192
Ted Kremenekefaff192010-02-27 01:41:03 +00002193void
Ted Kremenek826a3452010-07-16 02:11:22 +00002194CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2195 analyze_format_string::PositionContext p) {
Richard Trieu55733de2011-10-28 00:41:25 +00002196 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2197 << (unsigned) p,
2198 getLocationOfByte(startPos), /*IsStringLocation*/true,
2199 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002200}
2201
Ted Kremenek826a3452010-07-16 02:11:22 +00002202void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00002203 unsigned posLen) {
Richard Trieu55733de2011-10-28 00:41:25 +00002204 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2205 getLocationOfByte(startPos),
2206 /*IsStringLocation*/true,
2207 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002208}
2209
Ted Kremenek826a3452010-07-16 02:11:22 +00002210void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose50687312012-06-04 23:52:23 +00002211 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0c069442011-03-15 21:18:48 +00002212 // The presence of a null character is likely an error.
Richard Trieu55733de2011-10-28 00:41:25 +00002213 EmitFormatDiagnostic(
2214 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2215 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2216 getFormatStringRange());
Ted Kremenek0c069442011-03-15 21:18:48 +00002217 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002218}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002219
Jordan Rose48716662012-07-19 18:10:08 +00002220// Note that this may return NULL if there was an error parsing or building
2221// one of the argument expressions.
Ted Kremenek826a3452010-07-16 02:11:22 +00002222const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002223 return Args[FirstDataArg + i];
Ted Kremenek826a3452010-07-16 02:11:22 +00002224}
2225
2226void CheckFormatHandler::DoneProcessing() {
2227 // Does the number of data arguments exceed the number of
2228 // format conversions in the format string?
2229 if (!HasVAListArg) {
2230 // Find any arguments that weren't covered.
2231 CoveredArgs.flip();
2232 signed notCoveredArg = CoveredArgs.find_first();
2233 if (notCoveredArg >= 0) {
2234 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose48716662012-07-19 18:10:08 +00002235 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2236 SourceLocation Loc = E->getLocStart();
2237 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2238 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2239 Loc, /*IsStringLocation*/false,
2240 getFormatStringRange());
2241 }
Bob Wilsonc03f2df2012-05-03 19:47:19 +00002242 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002243 }
2244 }
2245}
2246
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002247bool
2248CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2249 SourceLocation Loc,
2250 const char *startSpec,
2251 unsigned specifierLen,
2252 const char *csStart,
2253 unsigned csLen) {
2254
2255 bool keepGoing = true;
2256 if (argIndex < NumDataArgs) {
2257 // Consider the argument coverered, even though the specifier doesn't
2258 // make sense.
2259 CoveredArgs.set(argIndex);
2260 }
2261 else {
2262 // If argIndex exceeds the number of data arguments we
2263 // don't issue a warning because that is just a cascade of warnings (and
2264 // they may have intended '%%' anyway). We don't want to continue processing
2265 // the format string after this point, however, as we will like just get
2266 // gibberish when trying to match arguments.
2267 keepGoing = false;
2268 }
2269
Richard Trieu55733de2011-10-28 00:41:25 +00002270 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2271 << StringRef(csStart, csLen),
2272 Loc, /*IsStringLocation*/true,
2273 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002274
2275 return keepGoing;
2276}
2277
Richard Trieu55733de2011-10-28 00:41:25 +00002278void
2279CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2280 const char *startSpec,
2281 unsigned specifierLen) {
2282 EmitFormatDiagnostic(
2283 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2284 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2285}
2286
Ted Kremenek666a1972010-07-26 19:45:42 +00002287bool
2288CheckFormatHandler::CheckNumArgs(
2289 const analyze_format_string::FormatSpecifier &FS,
2290 const analyze_format_string::ConversionSpecifier &CS,
2291 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2292
2293 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002294 PartialDiagnostic PDiag = FS.usesPositionalArg()
2295 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2296 << (argIndex+1) << NumDataArgs)
2297 : S.PDiag(diag::warn_printf_insufficient_data_args);
2298 EmitFormatDiagnostic(
2299 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2300 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek666a1972010-07-26 19:45:42 +00002301 return false;
2302 }
2303 return true;
2304}
2305
Richard Trieu55733de2011-10-28 00:41:25 +00002306template<typename Range>
2307void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2308 SourceLocation Loc,
2309 bool IsStringLocation,
2310 Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002311 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002312 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu55733de2011-10-28 00:41:25 +00002313 Loc, IsStringLocation, StringRange, FixIt);
2314}
2315
2316/// \brief If the format string is not within the funcion call, emit a note
2317/// so that the function call and string are in diagnostic messages.
2318///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00002319/// \param InFunctionCall if true, the format string is within the function
Richard Trieu55733de2011-10-28 00:41:25 +00002320/// call and only one diagnostic message will be produced. Otherwise, an
2321/// extra note will be emitted pointing to location of the format string.
2322///
2323/// \param ArgumentExpr the expression that is passed as the format string
2324/// argument in the function call. Used for getting locations when two
2325/// diagnostics are emitted.
2326///
2327/// \param PDiag the callee should already have provided any strings for the
2328/// diagnostic message. This function only adds locations and fixits
2329/// to diagnostics.
2330///
2331/// \param Loc primary location for diagnostic. If two diagnostics are
2332/// required, one will be at Loc and a new SourceLocation will be created for
2333/// the other one.
2334///
2335/// \param IsStringLocation if true, Loc points to the format string should be
2336/// used for the note. Otherwise, Loc points to the argument list and will
2337/// be used with PDiag.
2338///
2339/// \param StringRange some or all of the string to highlight. This is
2340/// templated so it can accept either a CharSourceRange or a SourceRange.
2341///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00002342/// \param FixIt optional fix it hint for the format string.
Richard Trieu55733de2011-10-28 00:41:25 +00002343template<typename Range>
2344void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2345 const Expr *ArgumentExpr,
2346 PartialDiagnostic PDiag,
2347 SourceLocation Loc,
2348 bool IsStringLocation,
2349 Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002350 ArrayRef<FixItHint> FixIt) {
2351 if (InFunctionCall) {
2352 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2353 D << StringRange;
2354 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2355 I != E; ++I) {
2356 D << *I;
2357 }
2358 } else {
Richard Trieu55733de2011-10-28 00:41:25 +00002359 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2360 << ArgumentExpr->getSourceRange();
Jordan Roseec087352012-09-05 22:56:26 +00002361
2362 const Sema::SemaDiagnosticBuilder &Note =
2363 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2364 diag::note_format_string_defined);
2365
2366 Note << StringRange;
2367 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2368 I != E; ++I) {
2369 Note << *I;
2370 }
Richard Trieu55733de2011-10-28 00:41:25 +00002371 }
2372}
2373
Ted Kremenek826a3452010-07-16 02:11:22 +00002374//===--- CHECK: Printf format string checking ------------------------------===//
2375
2376namespace {
2377class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose50687312012-06-04 23:52:23 +00002378 bool ObjCContext;
Ted Kremenek826a3452010-07-16 02:11:22 +00002379public:
2380 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2381 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002382 unsigned numDataArgs, bool isObjC,
Ted Kremenek826a3452010-07-16 02:11:22 +00002383 const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002384 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002385 unsigned formatIdx, bool inFunctionCall,
2386 Sema::VariadicCallType CallType)
Ted Kremenek826a3452010-07-16 02:11:22 +00002387 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002388 numDataArgs, beg, hasVAListArg, Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002389 formatIdx, inFunctionCall, CallType), ObjCContext(isObjC)
2390 {}
2391
Ted Kremenek826a3452010-07-16 02:11:22 +00002392
2393 bool HandleInvalidPrintfConversionSpecifier(
2394 const analyze_printf::PrintfSpecifier &FS,
2395 const char *startSpecifier,
2396 unsigned specifierLen);
2397
2398 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2399 const char *startSpecifier,
2400 unsigned specifierLen);
Richard Smith831421f2012-06-25 20:30:08 +00002401 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2402 const char *StartSpecifier,
2403 unsigned SpecifierLen,
2404 const Expr *E);
2405
Ted Kremenek826a3452010-07-16 02:11:22 +00002406 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2407 const char *startSpecifier, unsigned specifierLen);
2408 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2409 const analyze_printf::OptionalAmount &Amt,
2410 unsigned type,
2411 const char *startSpecifier, unsigned specifierLen);
2412 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2413 const analyze_printf::OptionalFlag &flag,
2414 const char *startSpecifier, unsigned specifierLen);
2415 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2416 const analyze_printf::OptionalFlag &ignoredFlag,
2417 const analyze_printf::OptionalFlag &flag,
2418 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgf3749f42012-08-07 08:11:26 +00002419 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith831421f2012-06-25 20:30:08 +00002420 const Expr *E, const CharSourceRange &CSR);
2421
Ted Kremenek826a3452010-07-16 02:11:22 +00002422};
2423}
2424
2425bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2426 const analyze_printf::PrintfSpecifier &FS,
2427 const char *startSpecifier,
2428 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002429 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002430 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002431
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002432 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2433 getLocationOfByte(CS.getStart()),
2434 startSpecifier, specifierLen,
2435 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00002436}
2437
Ted Kremenek826a3452010-07-16 02:11:22 +00002438bool CheckPrintfHandler::HandleAmount(
2439 const analyze_format_string::OptionalAmount &Amt,
2440 unsigned k, const char *startSpecifier,
2441 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002442
2443 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002444 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002445 unsigned argIndex = Amt.getArgIndex();
2446 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002447 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2448 << k,
2449 getLocationOfByte(Amt.getStart()),
2450 /*IsStringLocation*/true,
2451 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002452 // Don't do any more checking. We will just emit
2453 // spurious errors.
2454 return false;
2455 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002456
Ted Kremenek0d277352010-01-29 01:06:55 +00002457 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00002458 // Although not in conformance with C99, we also allow the argument to be
2459 // an 'unsigned int' as that is a reasonably safe case. GCC also
2460 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002461 CoveredArgs.set(argIndex);
2462 const Expr *Arg = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00002463 if (!Arg)
2464 return false;
2465
Ted Kremenek0d277352010-01-29 01:06:55 +00002466 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002467
Hans Wennborgf3749f42012-08-07 08:11:26 +00002468 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
2469 assert(AT.isValid());
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002470
Hans Wennborgf3749f42012-08-07 08:11:26 +00002471 if (!AT.matchesType(S.Context, T)) {
Richard Trieu55733de2011-10-28 00:41:25 +00002472 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgf3749f42012-08-07 08:11:26 +00002473 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu55733de2011-10-28 00:41:25 +00002474 << T << Arg->getSourceRange(),
2475 getLocationOfByte(Amt.getStart()),
2476 /*IsStringLocation*/true,
2477 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002478 // Don't do any more checking. We will just emit
2479 // spurious errors.
2480 return false;
2481 }
2482 }
2483 }
2484 return true;
2485}
Ted Kremenek0d277352010-01-29 01:06:55 +00002486
Tom Caree4ee9662010-06-17 19:00:27 +00002487void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00002488 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002489 const analyze_printf::OptionalAmount &Amt,
2490 unsigned type,
2491 const char *startSpecifier,
2492 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002493 const analyze_printf::PrintfConversionSpecifier &CS =
2494 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00002495
Richard Trieu55733de2011-10-28 00:41:25 +00002496 FixItHint fixit =
2497 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2498 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2499 Amt.getConstantLength()))
2500 : FixItHint();
2501
2502 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2503 << type << CS.toString(),
2504 getLocationOfByte(Amt.getStart()),
2505 /*IsStringLocation*/true,
2506 getSpecifierRange(startSpecifier, specifierLen),
2507 fixit);
Tom Caree4ee9662010-06-17 19:00:27 +00002508}
2509
Ted Kremenek826a3452010-07-16 02:11:22 +00002510void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002511 const analyze_printf::OptionalFlag &flag,
2512 const char *startSpecifier,
2513 unsigned specifierLen) {
2514 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002515 const analyze_printf::PrintfConversionSpecifier &CS =
2516 FS.getConversionSpecifier();
Richard Trieu55733de2011-10-28 00:41:25 +00002517 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2518 << flag.toString() << CS.toString(),
2519 getLocationOfByte(flag.getPosition()),
2520 /*IsStringLocation*/true,
2521 getSpecifierRange(startSpecifier, specifierLen),
2522 FixItHint::CreateRemoval(
2523 getSpecifierRange(flag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002524}
2525
2526void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00002527 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002528 const analyze_printf::OptionalFlag &ignoredFlag,
2529 const analyze_printf::OptionalFlag &flag,
2530 const char *startSpecifier,
2531 unsigned specifierLen) {
2532 // Warn about ignored flag with a fixit removal.
Richard Trieu55733de2011-10-28 00:41:25 +00002533 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2534 << ignoredFlag.toString() << flag.toString(),
2535 getLocationOfByte(ignoredFlag.getPosition()),
2536 /*IsStringLocation*/true,
2537 getSpecifierRange(startSpecifier, specifierLen),
2538 FixItHint::CreateRemoval(
2539 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002540}
2541
Richard Smith831421f2012-06-25 20:30:08 +00002542// Determines if the specified is a C++ class or struct containing
2543// a member with the specified name and kind (e.g. a CXXMethodDecl named
2544// "c_str()").
2545template<typename MemberKind>
2546static llvm::SmallPtrSet<MemberKind*, 1>
2547CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2548 const RecordType *RT = Ty->getAs<RecordType>();
2549 llvm::SmallPtrSet<MemberKind*, 1> Results;
2550
2551 if (!RT)
2552 return Results;
2553 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
2554 if (!RD)
2555 return Results;
2556
2557 LookupResult R(S, &S.PP.getIdentifierTable().get(Name), SourceLocation(),
2558 Sema::LookupMemberName);
2559
2560 // We just need to include all members of the right kind turned up by the
2561 // filter, at this point.
2562 if (S.LookupQualifiedName(R, RT->getDecl()))
2563 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2564 NamedDecl *decl = (*I)->getUnderlyingDecl();
2565 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
2566 Results.insert(FK);
2567 }
2568 return Results;
2569}
2570
2571// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgf3749f42012-08-07 08:11:26 +00002572// better diagnostic if so. AT is assumed to be valid.
Richard Smith831421f2012-06-25 20:30:08 +00002573// Returns true when a c_str() conversion method is found.
2574bool CheckPrintfHandler::checkForCStrMembers(
Hans Wennborgf3749f42012-08-07 08:11:26 +00002575 const analyze_printf::ArgType &AT, const Expr *E,
Richard Smith831421f2012-06-25 20:30:08 +00002576 const CharSourceRange &CSR) {
2577 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2578
2579 MethodSet Results =
2580 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
2581
2582 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2583 MI != ME; ++MI) {
2584 const CXXMethodDecl *Method = *MI;
2585 if (Method->getNumParams() == 0 &&
Hans Wennborgf3749f42012-08-07 08:11:26 +00002586 AT.matchesType(S.Context, Method->getResultType())) {
Richard Smith831421f2012-06-25 20:30:08 +00002587 // FIXME: Suggest parens if the expression needs them.
2588 SourceLocation EndLoc =
2589 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd());
2590 S.Diag(E->getLocStart(), diag::note_printf_c_str)
2591 << "c_str()"
2592 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
2593 return true;
2594 }
2595 }
2596
2597 return false;
2598}
2599
Ted Kremeneke0e53132010-01-28 23:39:18 +00002600bool
Ted Kremenek826a3452010-07-16 02:11:22 +00002601CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002602 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00002603 const char *startSpecifier,
2604 unsigned specifierLen) {
2605
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002606 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00002607 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002608 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00002609
Ted Kremenekbaa40062010-07-19 22:01:06 +00002610 if (FS.consumesDataArgument()) {
2611 if (atFirstArg) {
2612 atFirstArg = false;
2613 usesPositionalArgs = FS.usesPositionalArg();
2614 }
2615 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002616 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2617 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002618 return false;
2619 }
Ted Kremenek0d277352010-01-29 01:06:55 +00002620 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002621
Ted Kremenekefaff192010-02-27 01:41:03 +00002622 // First check if the field width, precision, and conversion specifier
2623 // have matching data arguments.
2624 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2625 startSpecifier, specifierLen)) {
2626 return false;
2627 }
2628
2629 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2630 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002631 return false;
2632 }
2633
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002634 if (!CS.consumesDataArgument()) {
2635 // FIXME: Technically specifying a precision or field width here
2636 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002637 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002638 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002639
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002640 // Consume the argument.
2641 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00002642 if (argIndex < NumDataArgs) {
2643 // The check to see if the argIndex is valid will come later.
2644 // We set the bit here because we may exit early from this
2645 // function if we encounter some other error.
2646 CoveredArgs.set(argIndex);
2647 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002648
2649 // Check for using an Objective-C specific conversion specifier
2650 // in a non-ObjC literal.
Jordan Rose50687312012-06-04 23:52:23 +00002651 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002652 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2653 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002654 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002655
Tom Caree4ee9662010-06-17 19:00:27 +00002656 // Check for invalid use of field width
2657 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002658 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00002659 startSpecifier, specifierLen);
2660 }
2661
2662 // Check for invalid use of precision
2663 if (!FS.hasValidPrecision()) {
2664 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
2665 startSpecifier, specifierLen);
2666 }
2667
2668 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00002669 if (!FS.hasValidThousandsGroupingPrefix())
2670 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002671 if (!FS.hasValidLeadingZeros())
2672 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
2673 if (!FS.hasValidPlusPrefix())
2674 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00002675 if (!FS.hasValidSpacePrefix())
2676 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002677 if (!FS.hasValidAlternativeForm())
2678 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
2679 if (!FS.hasValidLeftJustified())
2680 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
2681
2682 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00002683 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
2684 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
2685 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002686 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
2687 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
2688 startSpecifier, specifierLen);
2689
2690 // Check the length modifier is valid with the given conversion specifier.
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002691 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose8be066e2012-09-08 04:00:12 +00002692 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
2693 diag::warn_format_nonsensical_length);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002694 else if (!FS.hasStandardLengthModifier())
Jordan Rose8be066e2012-09-08 04:00:12 +00002695 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002696 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose8be066e2012-09-08 04:00:12 +00002697 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
2698 diag::warn_format_non_standard_conversion_spec);
Tom Caree4ee9662010-06-17 19:00:27 +00002699
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002700 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
2701 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
2702
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002703 // The remaining checks depend on the data arguments.
2704 if (HasVAListArg)
2705 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002706
Ted Kremenek666a1972010-07-26 19:45:42 +00002707 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002708 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002709
Jordan Rose48716662012-07-19 18:10:08 +00002710 const Expr *Arg = getDataArg(argIndex);
2711 if (!Arg)
2712 return true;
2713
2714 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith831421f2012-06-25 20:30:08 +00002715}
2716
Jordan Roseec087352012-09-05 22:56:26 +00002717static bool requiresParensToAddCast(const Expr *E) {
2718 // FIXME: We should have a general way to reason about operator
2719 // precedence and whether parens are actually needed here.
2720 // Take care of a few common cases where they aren't.
2721 const Expr *Inside = E->IgnoreImpCasts();
2722 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
2723 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
2724
2725 switch (Inside->getStmtClass()) {
2726 case Stmt::ArraySubscriptExprClass:
2727 case Stmt::CallExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00002728 case Stmt::CharacterLiteralClass:
2729 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00002730 case Stmt::DeclRefExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00002731 case Stmt::FloatingLiteralClass:
2732 case Stmt::IntegerLiteralClass:
Jordan Roseec087352012-09-05 22:56:26 +00002733 case Stmt::MemberExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00002734 case Stmt::ObjCArrayLiteralClass:
2735 case Stmt::ObjCBoolLiteralExprClass:
2736 case Stmt::ObjCBoxedExprClass:
2737 case Stmt::ObjCDictionaryLiteralClass:
2738 case Stmt::ObjCEncodeExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00002739 case Stmt::ObjCIvarRefExprClass:
2740 case Stmt::ObjCMessageExprClass:
2741 case Stmt::ObjCPropertyRefExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00002742 case Stmt::ObjCStringLiteralClass:
2743 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00002744 case Stmt::ParenExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00002745 case Stmt::StringLiteralClass:
Jordan Roseec087352012-09-05 22:56:26 +00002746 case Stmt::UnaryOperatorClass:
2747 return false;
2748 default:
2749 return true;
2750 }
2751}
2752
Richard Smith831421f2012-06-25 20:30:08 +00002753bool
2754CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2755 const char *StartSpecifier,
2756 unsigned SpecifierLen,
2757 const Expr *E) {
2758 using namespace analyze_format_string;
2759 using namespace analyze_printf;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002760 // Now type check the data expression that matches the
2761 // format specifier.
Hans Wennborgf3749f42012-08-07 08:11:26 +00002762 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
2763 ObjCContext);
Jordan Rose614a8652012-09-05 22:56:19 +00002764 if (!AT.isValid())
2765 return true;
Jordan Roseec087352012-09-05 22:56:26 +00002766
Jordan Rose448ac3e2012-12-05 18:44:40 +00002767 QualType ExprTy = E->getType();
Ted Kremenek02be9682013-04-10 06:26:26 +00002768 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
2769 ExprTy = TET->getUnderlyingExpr()->getType();
2770 }
2771
Jordan Rose448ac3e2012-12-05 18:44:40 +00002772 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose614a8652012-09-05 22:56:19 +00002773 return true;
Jordan Roseee0259d2012-06-04 22:48:57 +00002774
Jordan Rose614a8652012-09-05 22:56:19 +00002775 // Look through argument promotions for our error message's reported type.
2776 // This includes the integral and floating promotions, but excludes array
2777 // and function pointer decay; seeing that an argument intended to be a
2778 // string has type 'char [6]' is probably more confusing than 'char *'.
2779 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2780 if (ICE->getCastKind() == CK_IntegralCast ||
2781 ICE->getCastKind() == CK_FloatingCast) {
2782 E = ICE->getSubExpr();
Jordan Rose448ac3e2012-12-05 18:44:40 +00002783 ExprTy = E->getType();
Jordan Rose614a8652012-09-05 22:56:19 +00002784
2785 // Check if we didn't match because of an implicit cast from a 'char'
2786 // or 'short' to an 'int'. This is done because printf is a varargs
2787 // function.
2788 if (ICE->getType() == S.Context.IntTy ||
2789 ICE->getType() == S.Context.UnsignedIntTy) {
2790 // All further checking is done on the subexpression.
Jordan Rose448ac3e2012-12-05 18:44:40 +00002791 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose614a8652012-09-05 22:56:19 +00002792 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00002793 }
Jordan Roseee0259d2012-06-04 22:48:57 +00002794 }
Jordan Rose448ac3e2012-12-05 18:44:40 +00002795 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
2796 // Special case for 'a', which has type 'int' in C.
2797 // Note, however, that we do /not/ want to treat multibyte constants like
2798 // 'MooV' as characters! This form is deprecated but still exists.
2799 if (ExprTy == S.Context.IntTy)
2800 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
2801 ExprTy = S.Context.CharTy;
Jordan Rose614a8652012-09-05 22:56:19 +00002802 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002803
Jordan Rose2cd34402012-12-05 18:44:49 +00002804 // %C in an Objective-C context prints a unichar, not a wchar_t.
2805 // If the argument is an integer of some kind, believe the %C and suggest
2806 // a cast instead of changing the conversion specifier.
Jordan Rose448ac3e2012-12-05 18:44:40 +00002807 QualType IntendedTy = ExprTy;
Jordan Rose2cd34402012-12-05 18:44:49 +00002808 if (ObjCContext &&
2809 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
2810 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
2811 !ExprTy->isCharType()) {
2812 // 'unichar' is defined as a typedef of unsigned short, but we should
2813 // prefer using the typedef if it is visible.
2814 IntendedTy = S.Context.UnsignedShortTy;
2815
2816 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
2817 Sema::LookupOrdinaryName);
2818 if (S.LookupName(Result, S.getCurScope())) {
2819 NamedDecl *ND = Result.getFoundDecl();
2820 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
2821 if (TD->getUnderlyingType() == IntendedTy)
2822 IntendedTy = S.Context.getTypedefType(TD);
2823 }
2824 }
2825 }
2826
2827 // Special-case some of Darwin's platform-independence types by suggesting
2828 // casts to primitive types that are known to be large enough.
2829 bool ShouldNotPrintDirectly = false;
Jordan Roseec087352012-09-05 22:56:26 +00002830 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Ted Kremenek6edb0292013-03-25 22:28:37 +00002831 // Use a 'while' to peel off layers of typedefs.
2832 QualType TyTy = IntendedTy;
2833 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
Jordan Roseec087352012-09-05 22:56:26 +00002834 StringRef Name = UserTy->getDecl()->getName();
Jordan Rose2cd34402012-12-05 18:44:49 +00002835 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Jordan Roseec087352012-09-05 22:56:26 +00002836 .Case("NSInteger", S.Context.LongTy)
2837 .Case("NSUInteger", S.Context.UnsignedLongTy)
2838 .Case("SInt32", S.Context.IntTy)
2839 .Case("UInt32", S.Context.UnsignedIntTy)
Jordan Rose2cd34402012-12-05 18:44:49 +00002840 .Default(QualType());
2841
2842 if (!CastTy.isNull()) {
2843 ShouldNotPrintDirectly = true;
2844 IntendedTy = CastTy;
Ted Kremenek6edb0292013-03-25 22:28:37 +00002845 break;
Jordan Rose2cd34402012-12-05 18:44:49 +00002846 }
Ted Kremenek6edb0292013-03-25 22:28:37 +00002847 TyTy = UserTy->desugar();
Jordan Roseec087352012-09-05 22:56:26 +00002848 }
2849 }
2850
Jordan Rose614a8652012-09-05 22:56:19 +00002851 // We may be able to offer a FixItHint if it is a supported type.
2852 PrintfSpecifier fixedFS = FS;
Jordan Roseec087352012-09-05 22:56:26 +00002853 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose614a8652012-09-05 22:56:19 +00002854 S.Context, ObjCContext);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002855
Jordan Rose614a8652012-09-05 22:56:19 +00002856 if (success) {
2857 // Get the fix string from the fixed format specifier
2858 SmallString<16> buf;
2859 llvm::raw_svector_ostream os(buf);
2860 fixedFS.toString(os);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002861
Jordan Roseec087352012-09-05 22:56:26 +00002862 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
2863
Jordan Rose2cd34402012-12-05 18:44:49 +00002864 if (IntendedTy == ExprTy) {
2865 // In this case, the specifier is wrong and should be changed to match
2866 // the argument.
2867 EmitFormatDiagnostic(
2868 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2869 << AT.getRepresentativeTypeName(S.Context) << IntendedTy
2870 << E->getSourceRange(),
2871 E->getLocStart(),
2872 /*IsStringLocation*/false,
2873 SpecRange,
2874 FixItHint::CreateReplacement(SpecRange, os.str()));
2875
2876 } else {
Jordan Roseec087352012-09-05 22:56:26 +00002877 // The canonical type for formatting this value is different from the
2878 // actual type of the expression. (This occurs, for example, with Darwin's
2879 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
2880 // should be printed as 'long' for 64-bit compatibility.)
2881 // Rather than emitting a normal format/argument mismatch, we want to
2882 // add a cast to the recommended type (and correct the format string
2883 // if necessary).
2884 SmallString<16> CastBuf;
2885 llvm::raw_svector_ostream CastFix(CastBuf);
2886 CastFix << "(";
2887 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
2888 CastFix << ")";
2889
2890 SmallVector<FixItHint,4> Hints;
2891 if (!AT.matchesType(S.Context, IntendedTy))
2892 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
2893
2894 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
2895 // If there's already a cast present, just replace it.
2896 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
2897 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
2898
2899 } else if (!requiresParensToAddCast(E)) {
2900 // If the expression has high enough precedence,
2901 // just write the C-style cast.
2902 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
2903 CastFix.str()));
2904 } else {
2905 // Otherwise, add parens around the expression as well as the cast.
2906 CastFix << "(";
2907 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
2908 CastFix.str()));
2909
2910 SourceLocation After = S.PP.getLocForEndOfToken(E->getLocEnd());
2911 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
2912 }
2913
Jordan Rose2cd34402012-12-05 18:44:49 +00002914 if (ShouldNotPrintDirectly) {
2915 // The expression has a type that should not be printed directly.
2916 // We extract the name from the typedef because we don't want to show
2917 // the underlying type in the diagnostic.
2918 StringRef Name = cast<TypedefType>(ExprTy)->getDecl()->getName();
Jordan Roseec087352012-09-05 22:56:26 +00002919
Jordan Rose2cd34402012-12-05 18:44:49 +00002920 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
2921 << Name << IntendedTy
2922 << E->getSourceRange(),
2923 E->getLocStart(), /*IsStringLocation=*/false,
2924 SpecRange, Hints);
2925 } else {
2926 // In this case, the expression could be printed using a different
2927 // specifier, but we've decided that the specifier is probably correct
2928 // and we should cast instead. Just use the normal warning message.
2929 EmitFormatDiagnostic(
2930 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2931 << AT.getRepresentativeTypeName(S.Context) << ExprTy
2932 << E->getSourceRange(),
2933 E->getLocStart(), /*IsStringLocation*/false,
2934 SpecRange, Hints);
2935 }
Jordan Roseec087352012-09-05 22:56:26 +00002936 }
Jordan Rose614a8652012-09-05 22:56:19 +00002937 } else {
2938 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
2939 SpecifierLen);
2940 // Since the warning for passing non-POD types to variadic functions
2941 // was deferred until now, we emit a warning for non-POD
2942 // arguments here.
Jordan Rose448ac3e2012-12-05 18:44:40 +00002943 if (S.isValidVarArgType(ExprTy) == Sema::VAK_Invalid) {
Jordan Rose614a8652012-09-05 22:56:19 +00002944 unsigned DiagKind;
Jordan Rose448ac3e2012-12-05 18:44:40 +00002945 if (ExprTy->isObjCObjectType())
Jordan Rose614a8652012-09-05 22:56:19 +00002946 DiagKind = diag::err_cannot_pass_objc_interface_to_vararg_format;
2947 else
2948 DiagKind = diag::warn_non_pod_vararg_with_format_string;
2949
2950 EmitFormatDiagnostic(
2951 S.PDiag(DiagKind)
Richard Smith80ad52f2013-01-02 11:42:31 +00002952 << S.getLangOpts().CPlusPlus11
Jordan Rose448ac3e2012-12-05 18:44:40 +00002953 << ExprTy
Jordan Rose614a8652012-09-05 22:56:19 +00002954 << CallType
2955 << AT.getRepresentativeTypeName(S.Context)
2956 << CSR
2957 << E->getSourceRange(),
2958 E->getLocStart(), /*IsStringLocation*/false, CSR);
2959
2960 checkForCStrMembers(AT, E, CSR);
2961 } else
Richard Trieu55733de2011-10-28 00:41:25 +00002962 EmitFormatDiagnostic(
2963 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Jordan Rose448ac3e2012-12-05 18:44:40 +00002964 << AT.getRepresentativeTypeName(S.Context) << ExprTy
Jordan Rose614a8652012-09-05 22:56:19 +00002965 << CSR
Richard Smith831421f2012-06-25 20:30:08 +00002966 << E->getSourceRange(),
Jordan Rose614a8652012-09-05 22:56:19 +00002967 E->getLocStart(), /*IsStringLocation*/false, CSR);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002968 }
2969
Ted Kremeneke0e53132010-01-28 23:39:18 +00002970 return true;
2971}
2972
Ted Kremenek826a3452010-07-16 02:11:22 +00002973//===--- CHECK: Scanf format string checking ------------------------------===//
2974
2975namespace {
2976class CheckScanfHandler : public CheckFormatHandler {
2977public:
2978 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
2979 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002980 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002981 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002982 unsigned formatIdx, bool inFunctionCall,
2983 Sema::VariadicCallType CallType)
Ted Kremenek826a3452010-07-16 02:11:22 +00002984 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002985 numDataArgs, beg, hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002986 Args, formatIdx, inFunctionCall, CallType)
Jordan Roseddcfbc92012-07-19 18:10:23 +00002987 {}
Ted Kremenek826a3452010-07-16 02:11:22 +00002988
2989 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
2990 const char *startSpecifier,
2991 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002992
2993 bool HandleInvalidScanfConversionSpecifier(
2994 const analyze_scanf::ScanfSpecifier &FS,
2995 const char *startSpecifier,
2996 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00002997
2998 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00002999};
Ted Kremenek07d161f2010-01-29 01:50:07 +00003000}
Ted Kremeneke0e53132010-01-28 23:39:18 +00003001
Ted Kremenekb7c21012010-07-16 18:28:03 +00003002void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3003 const char *end) {
Richard Trieu55733de2011-10-28 00:41:25 +00003004 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3005 getLocationOfByte(end), /*IsStringLocation*/true,
3006 getSpecifierRange(start, end - start));
Ted Kremenekb7c21012010-07-16 18:28:03 +00003007}
3008
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003009bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3010 const analyze_scanf::ScanfSpecifier &FS,
3011 const char *startSpecifier,
3012 unsigned specifierLen) {
3013
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003014 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003015 FS.getConversionSpecifier();
3016
3017 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3018 getLocationOfByte(CS.getStart()),
3019 startSpecifier, specifierLen,
3020 CS.getStart(), CS.getLength());
3021}
3022
Ted Kremenek826a3452010-07-16 02:11:22 +00003023bool CheckScanfHandler::HandleScanfSpecifier(
3024 const analyze_scanf::ScanfSpecifier &FS,
3025 const char *startSpecifier,
3026 unsigned specifierLen) {
3027
3028 using namespace analyze_scanf;
3029 using namespace analyze_format_string;
3030
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003031 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00003032
Ted Kremenekbaa40062010-07-19 22:01:06 +00003033 // Handle case where '%' and '*' don't consume an argument. These shouldn't
3034 // be used to decide if we are using positional arguments consistently.
3035 if (FS.consumesDataArgument()) {
3036 if (atFirstArg) {
3037 atFirstArg = false;
3038 usesPositionalArgs = FS.usesPositionalArg();
3039 }
3040 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00003041 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3042 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00003043 return false;
3044 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003045 }
3046
3047 // Check if the field with is non-zero.
3048 const OptionalAmount &Amt = FS.getFieldWidth();
3049 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3050 if (Amt.getConstantAmount() == 0) {
3051 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3052 Amt.getConstantLength());
Richard Trieu55733de2011-10-28 00:41:25 +00003053 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3054 getLocationOfByte(Amt.getStart()),
3055 /*IsStringLocation*/true, R,
3056 FixItHint::CreateRemoval(R));
Ted Kremenek826a3452010-07-16 02:11:22 +00003057 }
3058 }
3059
3060 if (!FS.consumesDataArgument()) {
3061 // FIXME: Technically specifying a precision or field width here
3062 // makes no sense. Worth issuing a warning at some point.
3063 return true;
3064 }
3065
3066 // Consume the argument.
3067 unsigned argIndex = FS.getArgIndex();
3068 if (argIndex < NumDataArgs) {
3069 // The check to see if the argIndex is valid will come later.
3070 // We set the bit here because we may exit early from this
3071 // function if we encounter some other error.
3072 CoveredArgs.set(argIndex);
3073 }
3074
Ted Kremenek1e51c202010-07-20 20:04:47 +00003075 // Check the length modifier is valid with the given conversion specifier.
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003076 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose8be066e2012-09-08 04:00:12 +00003077 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3078 diag::warn_format_nonsensical_length);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003079 else if (!FS.hasStandardLengthModifier())
Jordan Rose8be066e2012-09-08 04:00:12 +00003080 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003081 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose8be066e2012-09-08 04:00:12 +00003082 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3083 diag::warn_format_non_standard_conversion_spec);
Hans Wennborg76517422012-02-22 10:17:01 +00003084
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003085 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3086 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3087
Ted Kremenek826a3452010-07-16 02:11:22 +00003088 // The remaining checks depend on the data arguments.
3089 if (HasVAListArg)
3090 return true;
3091
Ted Kremenek666a1972010-07-26 19:45:42 +00003092 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00003093 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00003094
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003095 // Check that the argument type matches the format specifier.
3096 const Expr *Ex = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00003097 if (!Ex)
3098 return true;
3099
Hans Wennborg58e1e542012-08-07 08:59:46 +00003100 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3101 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003102 ScanfSpecifier fixedFS = FS;
David Blaikie4e4d0842012-03-11 07:00:24 +00003103 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
Hans Wennborgbe6126a2012-02-15 09:59:46 +00003104 S.Context);
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003105
3106 if (success) {
3107 // Get the fix string from the fixed format specifier.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003108 SmallString<128> buf;
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003109 llvm::raw_svector_ostream os(buf);
3110 fixedFS.toString(os);
3111
3112 EmitFormatDiagnostic(
3113 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg58e1e542012-08-07 08:59:46 +00003114 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003115 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00003116 Ex->getLocStart(),
3117 /*IsStringLocation*/false,
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003118 getSpecifierRange(startSpecifier, specifierLen),
3119 FixItHint::CreateReplacement(
3120 getSpecifierRange(startSpecifier, specifierLen),
3121 os.str()));
3122 } else {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003123 EmitFormatDiagnostic(
3124 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg58e1e542012-08-07 08:59:46 +00003125 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003126 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00003127 Ex->getLocStart(),
3128 /*IsStringLocation*/false,
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003129 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003130 }
3131 }
3132
Ted Kremenek826a3452010-07-16 02:11:22 +00003133 return true;
3134}
3135
3136void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00003137 const Expr *OrigFormatExpr,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003138 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003139 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003140 unsigned firstDataArg, FormatStringType Type,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003141 bool inFunctionCall, VariadicCallType CallType) {
Ted Kremenek826a3452010-07-16 02:11:22 +00003142
Ted Kremeneke0e53132010-01-28 23:39:18 +00003143 // CHECK: is the format string a wide literal?
Richard Smithdf9ef1b2012-06-13 05:37:23 +00003144 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu55733de2011-10-28 00:41:25 +00003145 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003146 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00003147 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3148 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00003149 return;
3150 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003151
Ted Kremeneke0e53132010-01-28 23:39:18 +00003152 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner5f9e2722011-07-23 10:55:15 +00003153 StringRef StrRef = FExpr->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00003154 const char *Str = StrRef.data();
3155 unsigned StrLen = StrRef.size();
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003156 const unsigned numDataArgs = Args.size() - firstDataArg;
Ted Kremenek826a3452010-07-16 02:11:22 +00003157
Ted Kremeneke0e53132010-01-28 23:39:18 +00003158 // CHECK: empty format string?
Ted Kremenek4cd57912011-09-29 05:52:16 +00003159 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu55733de2011-10-28 00:41:25 +00003160 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003161 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00003162 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3163 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00003164 return;
3165 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003166
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003167 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek826a3452010-07-16 02:11:22 +00003168 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00003169 numDataArgs, (Type == FST_NSString),
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003170 Str, HasVAListArg, Args, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003171 inFunctionCall, CallType);
Ted Kremenek826a3452010-07-16 02:11:22 +00003172
Hans Wennborgd02deeb2011-12-15 10:25:47 +00003173 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose275b6f52012-09-13 02:11:03 +00003174 getLangOpts(),
3175 Context.getTargetInfo()))
Ted Kremenek826a3452010-07-16 02:11:22 +00003176 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003177 } else if (Type == FST_Scanf) {
Jordan Rose50687312012-06-04 23:52:23 +00003178 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003179 Str, HasVAListArg, Args, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003180 inFunctionCall, CallType);
Ted Kremenek826a3452010-07-16 02:11:22 +00003181
Hans Wennborgd02deeb2011-12-15 10:25:47 +00003182 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose275b6f52012-09-13 02:11:03 +00003183 getLangOpts(),
3184 Context.getTargetInfo()))
Ted Kremenek826a3452010-07-16 02:11:22 +00003185 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003186 } // TODO: handle other formats
Ted Kremenekce7024e2010-01-28 01:18:22 +00003187}
3188
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003189//===--- CHECK: Standard memory functions ---------------------------------===//
3190
Douglas Gregor2a053a32011-05-03 20:05:22 +00003191/// \brief Determine whether the given type is a dynamic class type (e.g.,
3192/// whether it has a vtable).
3193static bool isDynamicClassType(QualType T) {
3194 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3195 if (CXXRecordDecl *Definition = Record->getDefinition())
3196 if (Definition->isDynamicClass())
3197 return true;
3198
3199 return false;
3200}
3201
Chandler Carrutha72a12f2011-06-21 23:04:20 +00003202/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth000d4282011-06-16 09:09:40 +00003203/// otherwise returns NULL.
3204static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Webere4a1c642011-06-14 16:14:58 +00003205 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth000d4282011-06-16 09:09:40 +00003206 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3207 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
3208 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00003209
Chandler Carruth000d4282011-06-16 09:09:40 +00003210 return 0;
3211}
3212
Chandler Carrutha72a12f2011-06-21 23:04:20 +00003213/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth000d4282011-06-16 09:09:40 +00003214static QualType getSizeOfArgType(const Expr* E) {
3215 if (const UnaryExprOrTypeTraitExpr *SizeOf =
3216 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3217 if (SizeOf->getKind() == clang::UETT_SizeOf)
3218 return SizeOf->getTypeOfArgument();
3219
3220 return QualType();
Nico Webere4a1c642011-06-14 16:14:58 +00003221}
3222
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003223/// \brief Check for dangerous or invalid arguments to memset().
3224///
Chandler Carruth929f0132011-06-03 06:23:57 +00003225/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003226/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
3227/// function calls.
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003228///
3229/// \param Call The call expression to diagnose.
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003230void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks0a151a12012-01-17 00:37:07 +00003231 unsigned BId,
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003232 IdentifierInfo *FnName) {
Anna Zaks0a151a12012-01-17 00:37:07 +00003233 assert(BId != 0);
3234
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00003235 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor707a23e2011-06-16 17:56:04 +00003236 // we have enough arguments, and if not, abort further checking.
Anna Zaks0a151a12012-01-17 00:37:07 +00003237 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Webercda57822011-10-13 22:30:23 +00003238 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00003239 return;
3240
Anna Zaks0a151a12012-01-17 00:37:07 +00003241 unsigned LastArg = (BId == Builtin::BImemset ||
3242 BId == Builtin::BIstrndup ? 1 : 2);
3243 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Webercda57822011-10-13 22:30:23 +00003244 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth000d4282011-06-16 09:09:40 +00003245
3246 // We have special checking when the length is a sizeof expression.
3247 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
3248 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
3249 llvm::FoldingSetNodeID SizeOfArgID;
3250
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003251 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
3252 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00003253 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003254
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003255 QualType DestTy = Dest->getType();
3256 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
3257 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00003258
Chandler Carruth000d4282011-06-16 09:09:40 +00003259 // Never warn about void type pointers. This can be used to suppress
3260 // false positives.
3261 if (PointeeTy->isVoidType())
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003262 continue;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003263
Chandler Carruth000d4282011-06-16 09:09:40 +00003264 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
3265 // actually comparing the expressions for equality. Because computing the
3266 // expression IDs can be expensive, we only do this if the diagnostic is
3267 // enabled.
3268 if (SizeOfArg &&
3269 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
3270 SizeOfArg->getExprLoc())) {
3271 // We only compute IDs for expressions if the warning is enabled, and
3272 // cache the sizeof arg's ID.
3273 if (SizeOfArgID == llvm::FoldingSetNodeID())
3274 SizeOfArg->Profile(SizeOfArgID, Context, true);
3275 llvm::FoldingSetNodeID DestID;
3276 Dest->Profile(DestID, Context, true);
3277 if (DestID == SizeOfArgID) {
Nico Webercda57822011-10-13 22:30:23 +00003278 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
3279 // over sizeof(src) as well.
Chandler Carruth000d4282011-06-16 09:09:40 +00003280 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks6fcb3722012-05-30 00:34:21 +00003281 StringRef ReadableName = FnName->getName();
3282
Chandler Carruth000d4282011-06-16 09:09:40 +00003283 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaks90c78322012-05-30 23:14:52 +00003284 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth000d4282011-06-16 09:09:40 +00003285 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian7adf4172013-01-30 01:12:44 +00003286 if (!PointeeTy->isIncompleteType() &&
3287 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth000d4282011-06-16 09:09:40 +00003288 ActionIdx = 2; // If the pointee's size is sizeof(char),
3289 // suggest an explicit length.
Anna Zaks6fcb3722012-05-30 00:34:21 +00003290
3291 // If the function is defined as a builtin macro, do not show macro
3292 // expansion.
3293 SourceLocation SL = SizeOfArg->getExprLoc();
3294 SourceRange DSR = Dest->getSourceRange();
3295 SourceRange SSR = SizeOfArg->getSourceRange();
3296 SourceManager &SM = PP.getSourceManager();
3297
3298 if (SM.isMacroArgExpansion(SL)) {
3299 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
3300 SL = SM.getSpellingLoc(SL);
3301 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
3302 SM.getSpellingLoc(DSR.getEnd()));
3303 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
3304 SM.getSpellingLoc(SSR.getEnd()));
3305 }
3306
Anna Zaks90c78322012-05-30 23:14:52 +00003307 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth000d4282011-06-16 09:09:40 +00003308 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks6fcb3722012-05-30 00:34:21 +00003309 << ReadableName
Anna Zaks90c78322012-05-30 23:14:52 +00003310 << PointeeTy
3311 << DestTy
Anna Zaks6fcb3722012-05-30 00:34:21 +00003312 << DSR
Anna Zaks90c78322012-05-30 23:14:52 +00003313 << SSR);
3314 DiagRuntimeBehavior(SL, SizeOfArg,
3315 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
3316 << ActionIdx
3317 << SSR);
3318
Chandler Carruth000d4282011-06-16 09:09:40 +00003319 break;
3320 }
3321 }
3322
3323 // Also check for cases where the sizeof argument is the exact same
3324 // type as the memory argument, and where it points to a user-defined
3325 // record type.
3326 if (SizeOfArgTy != QualType()) {
3327 if (PointeeTy->isRecordType() &&
3328 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
3329 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
3330 PDiag(diag::warn_sizeof_pointer_type_memaccess)
3331 << FnName << SizeOfArgTy << ArgIdx
3332 << PointeeTy << Dest->getSourceRange()
3333 << LenExpr->getSourceRange());
3334 break;
3335 }
Nico Webere4a1c642011-06-14 16:14:58 +00003336 }
3337
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003338 // Always complain about dynamic classes.
Anna Zaks0a151a12012-01-17 00:37:07 +00003339 if (isDynamicClassType(PointeeTy)) {
3340
3341 unsigned OperationType = 0;
3342 // "overwritten" if we're warning about the destination for any call
3343 // but memcmp; otherwise a verb appropriate to the call.
3344 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
3345 if (BId == Builtin::BImemcpy)
3346 OperationType = 1;
3347 else if(BId == Builtin::BImemmove)
3348 OperationType = 2;
3349 else if (BId == Builtin::BImemcmp)
3350 OperationType = 3;
3351 }
3352
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003353 DiagRuntimeBehavior(
3354 Dest->getExprLoc(), Dest,
3355 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks0a151a12012-01-17 00:37:07 +00003356 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Anna Zaksd9b859a2012-01-13 21:52:01 +00003357 << FnName << PointeeTy
Anna Zaks0a151a12012-01-17 00:37:07 +00003358 << OperationType
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003359 << Call->getCallee()->getSourceRange());
Anna Zaks0a151a12012-01-17 00:37:07 +00003360 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
3361 BId != Builtin::BImemset)
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003362 DiagRuntimeBehavior(
3363 Dest->getExprLoc(), Dest,
3364 PDiag(diag::warn_arc_object_memaccess)
3365 << ArgIdx << FnName << PointeeTy
3366 << Call->getCallee()->getSourceRange());
John McCallf85e1932011-06-15 23:02:42 +00003367 else
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003368 continue;
John McCallf85e1932011-06-15 23:02:42 +00003369
3370 DiagRuntimeBehavior(
3371 Dest->getExprLoc(), Dest,
Chandler Carruth929f0132011-06-03 06:23:57 +00003372 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003373 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
3374 break;
3375 }
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003376 }
3377}
3378
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003379// A little helper routine: ignore addition and subtraction of integer literals.
3380// This intentionally does not ignore all integer constant expressions because
3381// we don't want to remove sizeof().
3382static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
3383 Ex = Ex->IgnoreParenCasts();
3384
3385 for (;;) {
3386 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
3387 if (!BO || !BO->isAdditiveOp())
3388 break;
3389
3390 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
3391 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
3392
3393 if (isa<IntegerLiteral>(RHS))
3394 Ex = LHS;
3395 else if (isa<IntegerLiteral>(LHS))
3396 Ex = RHS;
3397 else
3398 break;
3399 }
3400
3401 return Ex;
3402}
3403
Anna Zaks0f38ace2012-08-08 21:42:23 +00003404static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
3405 ASTContext &Context) {
3406 // Only handle constant-sized or VLAs, but not flexible members.
3407 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
3408 // Only issue the FIXIT for arrays of size > 1.
3409 if (CAT->getSize().getSExtValue() <= 1)
3410 return false;
3411 } else if (!Ty->isVariableArrayType()) {
3412 return false;
3413 }
3414 return true;
3415}
3416
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003417// Warn if the user has made the 'size' argument to strlcpy or strlcat
3418// be the size of the source, instead of the destination.
3419void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
3420 IdentifierInfo *FnName) {
3421
3422 // Don't crash if the user has the wrong number of arguments
3423 if (Call->getNumArgs() != 3)
3424 return;
3425
3426 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
3427 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
3428 const Expr *CompareWithSrc = NULL;
3429
3430 // Look for 'strlcpy(dst, x, sizeof(x))'
3431 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
3432 CompareWithSrc = Ex;
3433 else {
3434 // Look for 'strlcpy(dst, x, strlen(x))'
3435 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Richard Smith180f4792011-11-10 06:34:14 +00003436 if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003437 && SizeCall->getNumArgs() == 1)
3438 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
3439 }
3440 }
3441
3442 if (!CompareWithSrc)
3443 return;
3444
3445 // Determine if the argument to sizeof/strlen is equal to the source
3446 // argument. In principle there's all kinds of things you could do
3447 // here, for instance creating an == expression and evaluating it with
3448 // EvaluateAsBooleanCondition, but this uses a more direct technique:
3449 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
3450 if (!SrcArgDRE)
3451 return;
3452
3453 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
3454 if (!CompareWithSrcDRE ||
3455 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
3456 return;
3457
3458 const Expr *OriginalSizeArg = Call->getArg(2);
3459 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
3460 << OriginalSizeArg->getSourceRange() << FnName;
3461
3462 // Output a FIXIT hint if the destination is an array (rather than a
3463 // pointer to an array). This could be enhanced to handle some
3464 // pointers if we know the actual size, like if DstArg is 'array+2'
3465 // we could say 'sizeof(array)-2'.
3466 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks0f38ace2012-08-08 21:42:23 +00003467 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek8f746222011-08-18 22:48:41 +00003468 return;
Ted Kremenek8f746222011-08-18 22:48:41 +00003469
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003470 SmallString<128> sizeString;
Ted Kremenek8f746222011-08-18 22:48:41 +00003471 llvm::raw_svector_ostream OS(sizeString);
3472 OS << "sizeof(";
Richard Smithd1420c62012-08-16 03:56:14 +00003473 DstArg->printPretty(OS, 0, getPrintingPolicy());
Ted Kremenek8f746222011-08-18 22:48:41 +00003474 OS << ")";
3475
3476 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
3477 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
3478 OS.str());
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003479}
3480
Anna Zaksc36bedc2012-02-01 19:08:57 +00003481/// Check if two expressions refer to the same declaration.
3482static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
3483 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
3484 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
3485 return D1->getDecl() == D2->getDecl();
3486 return false;
3487}
3488
3489static const Expr *getStrlenExprArg(const Expr *E) {
3490 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
3491 const FunctionDecl *FD = CE->getDirectCallee();
3492 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
3493 return 0;
3494 return CE->getArg(0)->IgnoreParenCasts();
3495 }
3496 return 0;
3497}
3498
3499// Warn on anti-patterns as the 'size' argument to strncat.
3500// The correct size argument should look like following:
3501// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
3502void Sema::CheckStrncatArguments(const CallExpr *CE,
3503 IdentifierInfo *FnName) {
3504 // Don't crash if the user has the wrong number of arguments.
3505 if (CE->getNumArgs() < 3)
3506 return;
3507 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
3508 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
3509 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
3510
3511 // Identify common expressions, which are wrongly used as the size argument
3512 // to strncat and may lead to buffer overflows.
3513 unsigned PatternType = 0;
3514 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
3515 // - sizeof(dst)
3516 if (referToTheSameDecl(SizeOfArg, DstArg))
3517 PatternType = 1;
3518 // - sizeof(src)
3519 else if (referToTheSameDecl(SizeOfArg, SrcArg))
3520 PatternType = 2;
3521 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
3522 if (BE->getOpcode() == BO_Sub) {
3523 const Expr *L = BE->getLHS()->IgnoreParenCasts();
3524 const Expr *R = BE->getRHS()->IgnoreParenCasts();
3525 // - sizeof(dst) - strlen(dst)
3526 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
3527 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
3528 PatternType = 1;
3529 // - sizeof(src) - (anything)
3530 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
3531 PatternType = 2;
3532 }
3533 }
3534
3535 if (PatternType == 0)
3536 return;
3537
Anna Zaksafdb0412012-02-03 01:27:37 +00003538 // Generate the diagnostic.
3539 SourceLocation SL = LenArg->getLocStart();
3540 SourceRange SR = LenArg->getSourceRange();
3541 SourceManager &SM = PP.getSourceManager();
3542
3543 // If the function is defined as a builtin macro, do not show macro expansion.
3544 if (SM.isMacroArgExpansion(SL)) {
3545 SL = SM.getSpellingLoc(SL);
3546 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
3547 SM.getSpellingLoc(SR.getEnd()));
3548 }
3549
Anna Zaks0f38ace2012-08-08 21:42:23 +00003550 // Check if the destination is an array (rather than a pointer to an array).
3551 QualType DstTy = DstArg->getType();
3552 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
3553 Context);
3554 if (!isKnownSizeArray) {
3555 if (PatternType == 1)
3556 Diag(SL, diag::warn_strncat_wrong_size) << SR;
3557 else
3558 Diag(SL, diag::warn_strncat_src_size) << SR;
3559 return;
3560 }
3561
Anna Zaksc36bedc2012-02-01 19:08:57 +00003562 if (PatternType == 1)
Anna Zaksafdb0412012-02-03 01:27:37 +00003563 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003564 else
Anna Zaksafdb0412012-02-03 01:27:37 +00003565 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003566
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003567 SmallString<128> sizeString;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003568 llvm::raw_svector_ostream OS(sizeString);
3569 OS << "sizeof(";
Richard Smithd1420c62012-08-16 03:56:14 +00003570 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003571 OS << ") - ";
3572 OS << "strlen(";
Richard Smithd1420c62012-08-16 03:56:14 +00003573 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003574 OS << ") - 1";
3575
Anna Zaksafdb0412012-02-03 01:27:37 +00003576 Diag(SL, diag::note_strncat_wrong_size)
3577 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003578}
3579
Ted Kremenek06de2762007-08-17 16:46:58 +00003580//===--- CHECK: Return Address of Stack Variable --------------------------===//
3581
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003582static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3583 Decl *ParentDecl);
3584static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
3585 Decl *ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003586
3587/// CheckReturnStackAddr - Check if a return statement returns the address
3588/// of a stack variable.
3589void
3590Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
3591 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00003592
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003593 Expr *stackE = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003594 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003595
3596 // Perform checking for returned stack addresses, local blocks,
3597 // label addresses or references to temporaries.
John McCallf85e1932011-06-15 23:02:42 +00003598 if (lhsType->isPointerType() ||
David Blaikie4e4d0842012-03-11 07:00:24 +00003599 (!getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003600 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003601 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003602 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003603 }
3604
3605 if (stackE == 0)
3606 return; // Nothing suspicious was found.
3607
3608 SourceLocation diagLoc;
3609 SourceRange diagRange;
3610 if (refVars.empty()) {
3611 diagLoc = stackE->getLocStart();
3612 diagRange = stackE->getSourceRange();
3613 } else {
3614 // We followed through a reference variable. 'stackE' contains the
3615 // problematic expression but we will warn at the return statement pointing
3616 // at the reference variable. We will later display the "trail" of
3617 // reference variables using notes.
3618 diagLoc = refVars[0]->getLocStart();
3619 diagRange = refVars[0]->getSourceRange();
3620 }
3621
3622 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
3623 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
3624 : diag::warn_ret_stack_addr)
3625 << DR->getDecl()->getDeclName() << diagRange;
3626 } else if (isa<BlockExpr>(stackE)) { // local block.
3627 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
3628 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
3629 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
3630 } else { // local temporary.
3631 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
3632 : diag::warn_ret_local_temp_addr)
3633 << diagRange;
3634 }
3635
3636 // Display the "trail" of reference variables that we followed until we
3637 // found the problematic expression using notes.
3638 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
3639 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
3640 // If this var binds to another reference var, show the range of the next
3641 // var, otherwise the var binds to the problematic expression, in which case
3642 // show the range of the expression.
3643 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
3644 : stackE->getSourceRange();
3645 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
3646 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00003647 }
3648}
3649
3650/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
3651/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003652/// to a location on the stack, a local block, an address of a label, or a
3653/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00003654/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003655/// encounter a subexpression that (1) clearly does not lead to one of the
3656/// above problematic expressions (2) is something we cannot determine leads to
3657/// a problematic expression based on such local checking.
3658///
3659/// Both EvalAddr and EvalVal follow through reference variables to evaluate
3660/// the expression that they point to. Such variables are added to the
3661/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00003662///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00003663/// EvalAddr processes expressions that are pointers that are used as
3664/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003665/// At the base case of the recursion is a check for the above problematic
3666/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00003667///
3668/// This implementation handles:
3669///
3670/// * pointer-to-pointer casts
3671/// * implicit conversions from array references to pointers
3672/// * taking the address of fields
3673/// * arbitrary interplay between "&" and "*" operators
3674/// * pointer arithmetic from an address of a stack variable
3675/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003676static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3677 Decl *ParentDecl) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003678 if (E->isTypeDependent())
3679 return NULL;
3680
Ted Kremenek06de2762007-08-17 16:46:58 +00003681 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00003682 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00003683 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003684 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003685 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00003686
Peter Collingbournef111d932011-04-15 00:35:48 +00003687 E = E->IgnoreParens();
3688
Ted Kremenek06de2762007-08-17 16:46:58 +00003689 // Our "symbolic interpreter" is just a dispatch off the currently
3690 // viewed AST node. We then recursively traverse the AST by calling
3691 // EvalAddr and EvalVal appropriately.
3692 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003693 case Stmt::DeclRefExprClass: {
3694 DeclRefExpr *DR = cast<DeclRefExpr>(E);
3695
3696 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
3697 // If this is a reference variable, follow through to the expression that
3698 // it points to.
3699 if (V->hasLocalStorage() &&
3700 V->getType()->isReferenceType() && V->hasInit()) {
3701 // Add the reference variable to the "trail".
3702 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003703 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003704 }
3705
3706 return NULL;
3707 }
Ted Kremenek06de2762007-08-17 16:46:58 +00003708
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003709 case Stmt::UnaryOperatorClass: {
3710 // The only unary operator that make sense to handle here
3711 // is AddrOf. All others don't make sense as pointers.
3712 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003713
John McCall2de56d12010-08-25 11:45:40 +00003714 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003715 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003716 else
Ted Kremenek06de2762007-08-17 16:46:58 +00003717 return NULL;
3718 }
Mike Stump1eb44332009-09-09 15:08:12 +00003719
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003720 case Stmt::BinaryOperatorClass: {
3721 // Handle pointer arithmetic. All other binary operators are not valid
3722 // in this context.
3723 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00003724 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00003725
John McCall2de56d12010-08-25 11:45:40 +00003726 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003727 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00003728
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003729 Expr *Base = B->getLHS();
3730
3731 // Determine which argument is the real pointer base. It could be
3732 // the RHS argument instead of the LHS.
3733 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00003734
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003735 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003736 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003737 }
Steve Naroff61f40a22008-09-10 19:17:48 +00003738
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003739 // For conditional operators we need to see if either the LHS or RHS are
3740 // valid DeclRefExpr*s. If one of them is valid, we return it.
3741 case Stmt::ConditionalOperatorClass: {
3742 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003743
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003744 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003745 if (Expr *lhsExpr = C->getLHS()) {
3746 // In C++, we can have a throw-expression, which has 'void' type.
3747 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003748 if (Expr* LHS = EvalAddr(lhsExpr, refVars, ParentDecl))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003749 return LHS;
3750 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003751
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003752 // In C++, we can have a throw-expression, which has 'void' type.
3753 if (C->getRHS()->getType()->isVoidType())
3754 return NULL;
3755
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003756 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003757 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003758
3759 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00003760 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003761 return E; // local block.
3762 return NULL;
3763
3764 case Stmt::AddrLabelExprClass:
3765 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00003766
John McCall80ee6e82011-11-10 05:35:25 +00003767 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003768 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
3769 ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00003770
Ted Kremenek54b52742008-08-07 00:49:01 +00003771 // For casts, we need to handle conversions from arrays to
3772 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00003773 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00003774 case Stmt::CStyleCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00003775 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8b9414e2012-02-23 23:04:32 +00003776 case Stmt::ObjCBridgedCastExprClass:
Mike Stump1eb44332009-09-09 15:08:12 +00003777 case Stmt::CXXStaticCastExprClass:
3778 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00003779 case Stmt::CXXConstCastExprClass:
3780 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8b9414e2012-02-23 23:04:32 +00003781 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
3782 switch (cast<CastExpr>(E)->getCastKind()) {
3783 case CK_BitCast:
3784 case CK_LValueToRValue:
3785 case CK_NoOp:
3786 case CK_BaseToDerived:
3787 case CK_DerivedToBase:
3788 case CK_UncheckedDerivedToBase:
3789 case CK_Dynamic:
3790 case CK_CPointerToObjCPointerCast:
3791 case CK_BlockPointerToObjCPointerCast:
3792 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003793 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00003794
3795 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003796 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00003797
3798 default:
3799 return 0;
3800 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003801 }
Mike Stump1eb44332009-09-09 15:08:12 +00003802
Douglas Gregor03e80032011-06-21 17:03:29 +00003803 case Stmt::MaterializeTemporaryExprClass:
3804 if (Expr *Result = EvalAddr(
3805 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003806 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00003807 return Result;
3808
3809 return E;
3810
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003811 // Everything else: we simply don't reason about them.
3812 default:
3813 return NULL;
3814 }
Ted Kremenek06de2762007-08-17 16:46:58 +00003815}
Mike Stump1eb44332009-09-09 15:08:12 +00003816
Ted Kremenek06de2762007-08-17 16:46:58 +00003817
3818/// EvalVal - This function is complements EvalAddr in the mutual recursion.
3819/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003820static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3821 Decl *ParentDecl) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003822do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00003823 // We should only be called for evaluating non-pointer expressions, or
3824 // expressions with a pointer type that are not used as references but instead
3825 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00003826
Ted Kremenek06de2762007-08-17 16:46:58 +00003827 // Our "symbolic interpreter" is just a dispatch off the currently
3828 // viewed AST node. We then recursively traverse the AST by calling
3829 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00003830
3831 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00003832 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003833 case Stmt::ImplicitCastExprClass: {
3834 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00003835 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003836 E = IE->getSubExpr();
3837 continue;
3838 }
3839 return NULL;
3840 }
3841
John McCall80ee6e82011-11-10 05:35:25 +00003842 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003843 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00003844
Douglas Gregora2813ce2009-10-23 18:54:35 +00003845 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003846 // When we hit a DeclRefExpr we are looking at code that refers to a
3847 // variable's name. If it's not a reference variable we check if it has
3848 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00003849 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003850
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003851 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
3852 // Check if it refers to itself, e.g. "int& i = i;".
3853 if (V == ParentDecl)
3854 return DR;
3855
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003856 if (V->hasLocalStorage()) {
3857 if (!V->getType()->isReferenceType())
3858 return DR;
3859
3860 // Reference variable, follow through to the expression that
3861 // it points to.
3862 if (V->hasInit()) {
3863 // Add the reference variable to the "trail".
3864 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003865 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003866 }
3867 }
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003868 }
Mike Stump1eb44332009-09-09 15:08:12 +00003869
Ted Kremenek06de2762007-08-17 16:46:58 +00003870 return NULL;
3871 }
Mike Stump1eb44332009-09-09 15:08:12 +00003872
Ted Kremenek06de2762007-08-17 16:46:58 +00003873 case Stmt::UnaryOperatorClass: {
3874 // The only unary operator that make sense to handle here
3875 // is Deref. All others don't resolve to a "name." This includes
3876 // handling all sorts of rvalues passed to a unary operator.
3877 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003878
John McCall2de56d12010-08-25 11:45:40 +00003879 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003880 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003881
3882 return NULL;
3883 }
Mike Stump1eb44332009-09-09 15:08:12 +00003884
Ted Kremenek06de2762007-08-17 16:46:58 +00003885 case Stmt::ArraySubscriptExprClass: {
3886 // Array subscripts are potential references to data on the stack. We
3887 // retrieve the DeclRefExpr* for the array variable if it indeed
3888 // has local storage.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003889 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003890 }
Mike Stump1eb44332009-09-09 15:08:12 +00003891
Ted Kremenek06de2762007-08-17 16:46:58 +00003892 case Stmt::ConditionalOperatorClass: {
3893 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003894 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00003895 ConditionalOperator *C = cast<ConditionalOperator>(E);
3896
Anders Carlsson39073232007-11-30 19:04:31 +00003897 // Handle the GNU extension for missing LHS.
3898 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003899 if (Expr *LHS = EvalVal(lhsExpr, refVars, ParentDecl))
Anders Carlsson39073232007-11-30 19:04:31 +00003900 return LHS;
3901
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003902 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003903 }
Mike Stump1eb44332009-09-09 15:08:12 +00003904
Ted Kremenek06de2762007-08-17 16:46:58 +00003905 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00003906 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00003907 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003908
Ted Kremenek06de2762007-08-17 16:46:58 +00003909 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00003910 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00003911 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00003912
3913 // Check whether the member type is itself a reference, in which case
3914 // we're not going to refer to the member, but to what the member refers to.
3915 if (M->getMemberDecl()->getType()->isReferenceType())
3916 return NULL;
3917
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003918 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003919 }
Mike Stump1eb44332009-09-09 15:08:12 +00003920
Douglas Gregor03e80032011-06-21 17:03:29 +00003921 case Stmt::MaterializeTemporaryExprClass:
3922 if (Expr *Result = EvalVal(
3923 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003924 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00003925 return Result;
3926
3927 return E;
3928
Ted Kremenek06de2762007-08-17 16:46:58 +00003929 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003930 // Check that we don't return or take the address of a reference to a
3931 // temporary. This is only useful in C++.
3932 if (!E->isTypeDependent() && E->isRValue())
3933 return E;
3934
3935 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00003936 return NULL;
3937 }
Ted Kremenek68957a92010-08-04 20:01:07 +00003938} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00003939}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003940
3941//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
3942
3943/// Check for comparisons of floating point operands using != and ==.
3944/// Issue a warning if these are no self-comparisons, as they are not likely
3945/// to do what the programmer intended.
Richard Trieudd225092011-09-15 21:56:47 +00003946void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieudd225092011-09-15 21:56:47 +00003947 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
3948 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003949
3950 // Special case: check for x == x (which is OK).
3951 // Do not emit warnings for such cases.
3952 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
3953 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
3954 if (DRL->getDecl() == DRR->getDecl())
David Blaikie980343b2012-07-16 20:47:22 +00003955 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003956
3957
Ted Kremenek1b500bb2007-11-29 00:59:04 +00003958 // Special case: check for comparisons against literals that can be exactly
3959 // represented by APFloat. In such cases, do not emit a warning. This
3960 // is a heuristic: often comparison against such literals are used to
3961 // detect if a value in a variable has not changed. This clearly can
3962 // lead to false negatives.
David Blaikie980343b2012-07-16 20:47:22 +00003963 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
3964 if (FLL->isExact())
3965 return;
3966 } else
3967 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
3968 if (FLR->isExact())
3969 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003970
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003971 // Check for comparisons with builtin types.
David Blaikie980343b2012-07-16 20:47:22 +00003972 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
3973 if (CL->isBuiltinCall())
3974 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003975
David Blaikie980343b2012-07-16 20:47:22 +00003976 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
3977 if (CR->isBuiltinCall())
3978 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003979
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003980 // Emit the diagnostic.
David Blaikie980343b2012-07-16 20:47:22 +00003981 Diag(Loc, diag::warn_floatingpoint_eq)
3982 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003983}
John McCallba26e582010-01-04 23:21:16 +00003984
John McCallf2370c92010-01-06 05:24:50 +00003985//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
3986//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00003987
John McCallf2370c92010-01-06 05:24:50 +00003988namespace {
John McCallba26e582010-01-04 23:21:16 +00003989
John McCallf2370c92010-01-06 05:24:50 +00003990/// Structure recording the 'active' range of an integer-valued
3991/// expression.
3992struct IntRange {
3993 /// The number of bits active in the int.
3994 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00003995
John McCallf2370c92010-01-06 05:24:50 +00003996 /// True if the int is known not to have negative values.
3997 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00003998
John McCallf2370c92010-01-06 05:24:50 +00003999 IntRange(unsigned Width, bool NonNegative)
4000 : Width(Width), NonNegative(NonNegative)
4001 {}
John McCallba26e582010-01-04 23:21:16 +00004002
John McCall1844a6e2010-11-10 23:38:19 +00004003 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00004004 static IntRange forBoolType() {
4005 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00004006 }
4007
John McCall1844a6e2010-11-10 23:38:19 +00004008 /// Returns the range of an opaque value of the given integral type.
4009 static IntRange forValueOfType(ASTContext &C, QualType T) {
4010 return forValueOfCanonicalType(C,
4011 T->getCanonicalTypeInternal().getTypePtr());
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 a canonical integral type.
4015 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00004016 assert(T->isCanonicalUnqualified());
4017
4018 if (const VectorType *VT = dyn_cast<VectorType>(T))
4019 T = VT->getElementType().getTypePtr();
4020 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4021 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00004022
John McCall091f23f2010-11-09 22:22:12 +00004023 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00004024 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
4025 EnumDecl *Enum = ET->getDecl();
John McCall5e1cdac2011-10-07 06:10:15 +00004026 if (!Enum->isCompleteDefinition())
John McCall091f23f2010-11-09 22:22:12 +00004027 return IntRange(C.getIntWidth(QualType(T, 0)), false);
4028
John McCall323ed742010-05-06 08:58:33 +00004029 unsigned NumPositive = Enum->getNumPositiveBits();
4030 unsigned NumNegative = Enum->getNumNegativeBits();
4031
Richard Trieu8f50b242012-11-16 01:32:40 +00004032 if (NumNegative == 0)
4033 return IntRange(NumPositive, true/*NonNegative*/);
4034 else
4035 return IntRange(std::max(NumPositive + 1, NumNegative),
4036 false/*NonNegative*/);
John McCall323ed742010-05-06 08:58:33 +00004037 }
John McCallf2370c92010-01-06 05:24:50 +00004038
4039 const BuiltinType *BT = cast<BuiltinType>(T);
4040 assert(BT->isInteger());
4041
4042 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4043 }
4044
John McCall1844a6e2010-11-10 23:38:19 +00004045 /// Returns the "target" range of a canonical integral type, i.e.
4046 /// the range of values expressible in the type.
4047 ///
4048 /// This matches forValueOfCanonicalType except that enums have the
4049 /// full range of their type, not the range of their enumerators.
4050 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
4051 assert(T->isCanonicalUnqualified());
4052
4053 if (const VectorType *VT = dyn_cast<VectorType>(T))
4054 T = VT->getElementType().getTypePtr();
4055 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4056 T = CT->getElementType().getTypePtr();
4057 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor69ff26b2011-09-08 23:29:05 +00004058 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall1844a6e2010-11-10 23:38:19 +00004059
4060 const BuiltinType *BT = cast<BuiltinType>(T);
4061 assert(BT->isInteger());
4062
4063 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4064 }
4065
4066 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00004067 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00004068 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00004069 L.NonNegative && R.NonNegative);
4070 }
4071
John McCall1844a6e2010-11-10 23:38:19 +00004072 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00004073 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00004074 return IntRange(std::min(L.Width, R.Width),
4075 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00004076 }
4077};
4078
Ted Kremenek0692a192012-01-31 05:37:37 +00004079static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
4080 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004081 if (value.isSigned() && value.isNegative())
4082 return IntRange(value.getMinSignedBits(), false);
4083
4084 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00004085 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00004086
4087 // isNonNegative() just checks the sign bit without considering
4088 // signedness.
4089 return IntRange(value.getActiveBits(), true);
4090}
4091
Ted Kremenek0692a192012-01-31 05:37:37 +00004092static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
4093 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004094 if (result.isInt())
4095 return GetValueRange(C, result.getInt(), MaxWidth);
4096
4097 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00004098 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
4099 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
4100 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
4101 R = IntRange::join(R, El);
4102 }
John McCallf2370c92010-01-06 05:24:50 +00004103 return R;
4104 }
4105
4106 if (result.isComplexInt()) {
4107 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
4108 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
4109 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00004110 }
4111
4112 // This can happen with lossless casts to intptr_t of "based" lvalues.
4113 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00004114 // FIXME: The only reason we need to pass the type in here is to get
4115 // the sign right on this one case. It would be nice if APValue
4116 // preserved this.
Eli Friedman65639282012-01-04 23:13:47 +00004117 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00004118 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall51313c32010-01-04 23:31:57 +00004119}
John McCallf2370c92010-01-06 05:24:50 +00004120
4121/// Pseudo-evaluate the given integer expression, estimating the
4122/// range of values it might take.
4123///
4124/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek0692a192012-01-31 05:37:37 +00004125static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004126 E = E->IgnoreParens();
4127
4128 // Try a full evaluation first.
4129 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00004130 if (E->EvaluateAsRValue(result, C))
John McCall0acc3112010-01-06 22:57:21 +00004131 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00004132
4133 // I think we only want to look through implicit casts here; if the
4134 // user has an explicit widening cast, we should treat the value as
4135 // being of the new, wider type.
4136 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedmanb17ee5b2011-12-15 02:41:52 +00004137 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCallf2370c92010-01-06 05:24:50 +00004138 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
4139
John McCall1844a6e2010-11-10 23:38:19 +00004140 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCallf2370c92010-01-06 05:24:50 +00004141
John McCall2de56d12010-08-25 11:45:40 +00004142 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00004143
John McCallf2370c92010-01-06 05:24:50 +00004144 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00004145 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00004146 return OutputTypeRange;
4147
4148 IntRange SubRange
4149 = GetExprRange(C, CE->getSubExpr(),
4150 std::min(MaxWidth, OutputTypeRange.Width));
4151
4152 // Bail out if the subexpr's range is as wide as the cast type.
4153 if (SubRange.Width >= OutputTypeRange.Width)
4154 return OutputTypeRange;
4155
4156 // Otherwise, we take the smaller width, and we're non-negative if
4157 // either the output type or the subexpr is.
4158 return IntRange(SubRange.Width,
4159 SubRange.NonNegative || OutputTypeRange.NonNegative);
4160 }
4161
4162 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4163 // If we can fold the condition, just take that operand.
4164 bool CondResult;
4165 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
4166 return GetExprRange(C, CondResult ? CO->getTrueExpr()
4167 : CO->getFalseExpr(),
4168 MaxWidth);
4169
4170 // Otherwise, conservatively merge.
4171 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
4172 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
4173 return IntRange::join(L, R);
4174 }
4175
4176 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4177 switch (BO->getOpcode()) {
4178
4179 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00004180 case BO_LAnd:
4181 case BO_LOr:
4182 case BO_LT:
4183 case BO_GT:
4184 case BO_LE:
4185 case BO_GE:
4186 case BO_EQ:
4187 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00004188 return IntRange::forBoolType();
4189
John McCall862ff872011-07-13 06:35:24 +00004190 // The type of the assignments is the type of the LHS, so the RHS
4191 // is not necessarily the same type.
John McCall2de56d12010-08-25 11:45:40 +00004192 case BO_MulAssign:
4193 case BO_DivAssign:
4194 case BO_RemAssign:
4195 case BO_AddAssign:
4196 case BO_SubAssign:
John McCall862ff872011-07-13 06:35:24 +00004197 case BO_XorAssign:
4198 case BO_OrAssign:
4199 // TODO: bitfields?
John McCall1844a6e2010-11-10 23:38:19 +00004200 return IntRange::forValueOfType(C, E->getType());
John McCallc0cd21d2010-02-23 19:22:29 +00004201
John McCall862ff872011-07-13 06:35:24 +00004202 // Simple assignments just pass through the RHS, which will have
4203 // been coerced to the LHS type.
4204 case BO_Assign:
4205 // TODO: bitfields?
4206 return GetExprRange(C, BO->getRHS(), MaxWidth);
4207
John McCallf2370c92010-01-06 05:24:50 +00004208 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00004209 case BO_PtrMemD:
4210 case BO_PtrMemI:
John McCall1844a6e2010-11-10 23:38:19 +00004211 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00004212
John McCall60fad452010-01-06 22:07:33 +00004213 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00004214 case BO_And:
4215 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00004216 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
4217 GetExprRange(C, BO->getRHS(), MaxWidth));
4218
John McCallf2370c92010-01-06 05:24:50 +00004219 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00004220 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00004221 // ...except that we want to treat '1 << (blah)' as logically
4222 // positive. It's an important idiom.
4223 if (IntegerLiteral *I
4224 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
4225 if (I->getValue() == 1) {
John McCall1844a6e2010-11-10 23:38:19 +00004226 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall3aae6092010-04-07 01:14:35 +00004227 return IntRange(R.Width, /*NonNegative*/ true);
4228 }
4229 }
4230 // fallthrough
4231
John McCall2de56d12010-08-25 11:45:40 +00004232 case BO_ShlAssign:
John McCall1844a6e2010-11-10 23:38:19 +00004233 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00004234
John McCall60fad452010-01-06 22:07:33 +00004235 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00004236 case BO_Shr:
4237 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00004238 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4239
4240 // If the shift amount is a positive constant, drop the width by
4241 // that much.
4242 llvm::APSInt shift;
4243 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
4244 shift.isNonNegative()) {
4245 unsigned zext = shift.getZExtValue();
4246 if (zext >= L.Width)
4247 L.Width = (L.NonNegative ? 0 : 1);
4248 else
4249 L.Width -= zext;
4250 }
4251
4252 return L;
4253 }
4254
4255 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00004256 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00004257 return GetExprRange(C, BO->getRHS(), MaxWidth);
4258
John McCall60fad452010-01-06 22:07:33 +00004259 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00004260 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00004261 if (BO->getLHS()->getType()->isPointerType())
John McCall1844a6e2010-11-10 23:38:19 +00004262 return IntRange::forValueOfType(C, E->getType());
John McCall00fe7612011-07-14 22:39:48 +00004263 break;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00004264
John McCall00fe7612011-07-14 22:39:48 +00004265 // The width of a division result is mostly determined by the size
4266 // of the LHS.
4267 case BO_Div: {
4268 // Don't 'pre-truncate' the operands.
4269 unsigned opWidth = C.getIntWidth(E->getType());
4270 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4271
4272 // If the divisor is constant, use that.
4273 llvm::APSInt divisor;
4274 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
4275 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
4276 if (log2 >= L.Width)
4277 L.Width = (L.NonNegative ? 0 : 1);
4278 else
4279 L.Width = std::min(L.Width - log2, MaxWidth);
4280 return L;
4281 }
4282
4283 // Otherwise, just use the LHS's width.
4284 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4285 return IntRange(L.Width, L.NonNegative && R.NonNegative);
4286 }
4287
4288 // The result of a remainder can't be larger than the result of
4289 // either side.
4290 case BO_Rem: {
4291 // Don't 'pre-truncate' the operands.
4292 unsigned opWidth = C.getIntWidth(E->getType());
4293 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4294 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4295
4296 IntRange meet = IntRange::meet(L, R);
4297 meet.Width = std::min(meet.Width, MaxWidth);
4298 return meet;
4299 }
4300
4301 // The default behavior is okay for these.
4302 case BO_Mul:
4303 case BO_Add:
4304 case BO_Xor:
4305 case BO_Or:
John McCallf2370c92010-01-06 05:24:50 +00004306 break;
4307 }
4308
John McCall00fe7612011-07-14 22:39:48 +00004309 // The default case is to treat the operation as if it were closed
4310 // on the narrowest type that encompasses both operands.
John McCallf2370c92010-01-06 05:24:50 +00004311 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4312 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
4313 return IntRange::join(L, R);
4314 }
4315
4316 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
4317 switch (UO->getOpcode()) {
4318 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00004319 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00004320 return IntRange::forBoolType();
4321
4322 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00004323 case UO_Deref:
4324 case UO_AddrOf: // should be impossible
John McCall1844a6e2010-11-10 23:38:19 +00004325 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00004326
4327 default:
4328 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
4329 }
4330 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004331
4332 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall1844a6e2010-11-10 23:38:19 +00004333 IntRange::forValueOfType(C, E->getType());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004334 }
John McCallf2370c92010-01-06 05:24:50 +00004335
John McCall993f43f2013-05-06 21:39:12 +00004336 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004337 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00004338 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00004339
John McCall1844a6e2010-11-10 23:38:19 +00004340 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00004341}
John McCall51313c32010-01-04 23:31:57 +00004342
Ted Kremenek0692a192012-01-31 05:37:37 +00004343static IntRange GetExprRange(ASTContext &C, Expr *E) {
John McCall323ed742010-05-06 08:58:33 +00004344 return GetExprRange(C, E, C.getIntWidth(E->getType()));
4345}
4346
John McCall51313c32010-01-04 23:31:57 +00004347/// Checks whether the given value, which currently has the given
4348/// source semantics, has the same value when coerced through the
4349/// target semantics.
Ted Kremenek0692a192012-01-31 05:37:37 +00004350static bool IsSameFloatAfterCast(const llvm::APFloat &value,
4351 const llvm::fltSemantics &Src,
4352 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00004353 llvm::APFloat truncated = value;
4354
4355 bool ignored;
4356 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
4357 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
4358
4359 return truncated.bitwiseIsEqual(value);
4360}
4361
4362/// Checks whether the given value, which currently has the given
4363/// source semantics, has the same value when coerced through the
4364/// target semantics.
4365///
4366/// The value might be a vector of floats (or a complex number).
Ted Kremenek0692a192012-01-31 05:37:37 +00004367static bool IsSameFloatAfterCast(const APValue &value,
4368 const llvm::fltSemantics &Src,
4369 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00004370 if (value.isFloat())
4371 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
4372
4373 if (value.isVector()) {
4374 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
4375 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
4376 return false;
4377 return true;
4378 }
4379
4380 assert(value.isComplexFloat());
4381 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
4382 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
4383}
4384
Ted Kremenek0692a192012-01-31 05:37:37 +00004385static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00004386
Ted Kremeneke3b159c2010-09-23 21:43:44 +00004387static bool IsZero(Sema &S, Expr *E) {
4388 // Suppress cases where we are comparing against an enum constant.
4389 if (const DeclRefExpr *DR =
4390 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
4391 if (isa<EnumConstantDecl>(DR->getDecl()))
4392 return false;
4393
4394 // Suppress cases where the '0' value is expanded from a macro.
4395 if (E->getLocStart().isMacroID())
4396 return false;
4397
John McCall323ed742010-05-06 08:58:33 +00004398 llvm::APSInt Value;
4399 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
4400}
4401
John McCall372e1032010-10-06 00:25:24 +00004402static bool HasEnumType(Expr *E) {
4403 // Strip off implicit integral promotions.
4404 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00004405 if (ICE->getCastKind() != CK_IntegralCast &&
4406 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00004407 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00004408 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00004409 }
4410
4411 return E->getType()->isEnumeralType();
4412}
4413
Ted Kremenek0692a192012-01-31 05:37:37 +00004414static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00004415 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00004416 if (E->isValueDependent())
4417 return;
4418
John McCall2de56d12010-08-25 11:45:40 +00004419 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00004420 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004421 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00004422 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004423 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00004424 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004425 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00004426 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004427 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00004428 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004429 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00004430 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004431 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00004432 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004433 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00004434 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4435 }
4436}
4437
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004438static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004439 Expr *Constant, Expr *Other,
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004440 llvm::APSInt Value,
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004441 bool RhsConstant) {
Richard Trieu526e6272012-11-14 22:50:24 +00004442 // 0 values are handled later by CheckTrivialUnsignedComparison().
4443 if (Value == 0)
4444 return;
4445
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004446 BinaryOperatorKind op = E->getOpcode();
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004447 QualType OtherT = Other->getType();
4448 QualType ConstantT = Constant->getType();
Richard Trieu526e6272012-11-14 22:50:24 +00004449 QualType CommonT = E->getLHS()->getType();
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004450 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004451 return;
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004452 assert((OtherT->isIntegerType() && ConstantT->isIntegerType())
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004453 && "comparison with non-integer type");
Richard Trieu526e6272012-11-14 22:50:24 +00004454
4455 bool ConstantSigned = ConstantT->isSignedIntegerType();
Richard Trieu526e6272012-11-14 22:50:24 +00004456 bool CommonSigned = CommonT->isSignedIntegerType();
4457
4458 bool EqualityOnly = false;
4459
4460 // TODO: Investigate using GetExprRange() to get tighter bounds on
4461 // on the bit ranges.
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004462 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
Richard Trieu526e6272012-11-14 22:50:24 +00004463 unsigned OtherWidth = OtherRange.Width;
4464
4465 if (CommonSigned) {
4466 // The common type is signed, therefore no signed to unsigned conversion.
Eli Friedmand87de7b2012-11-30 23:09:29 +00004467 if (!OtherRange.NonNegative) {
Richard Trieu526e6272012-11-14 22:50:24 +00004468 // Check that the constant is representable in type OtherT.
4469 if (ConstantSigned) {
4470 if (OtherWidth >= Value.getMinSignedBits())
4471 return;
4472 } else { // !ConstantSigned
4473 if (OtherWidth >= Value.getActiveBits() + 1)
4474 return;
4475 }
4476 } else { // !OtherSigned
4477 // Check that the constant is representable in type OtherT.
4478 // Negative values are out of range.
4479 if (ConstantSigned) {
4480 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
4481 return;
4482 } else { // !ConstantSigned
4483 if (OtherWidth >= Value.getActiveBits())
4484 return;
4485 }
4486 }
4487 } else { // !CommonSigned
Eli Friedmand87de7b2012-11-30 23:09:29 +00004488 if (OtherRange.NonNegative) {
Richard Trieu526e6272012-11-14 22:50:24 +00004489 if (OtherWidth >= Value.getActiveBits())
4490 return;
Eli Friedmand87de7b2012-11-30 23:09:29 +00004491 } else if (!OtherRange.NonNegative && !ConstantSigned) {
Richard Trieu526e6272012-11-14 22:50:24 +00004492 // Check to see if the constant is representable in OtherT.
4493 if (OtherWidth > Value.getActiveBits())
4494 return;
4495 // Check to see if the constant is equivalent to a negative value
4496 // cast to CommonT.
4497 if (S.Context.getIntWidth(ConstantT) == S.Context.getIntWidth(CommonT) &&
Richard Trieu5d1cf4f2012-11-15 03:43:50 +00004498 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
Richard Trieu526e6272012-11-14 22:50:24 +00004499 return;
4500 // The constant value rests between values that OtherT can represent after
4501 // conversion. Relational comparison still works, but equality
4502 // comparisons will be tautological.
4503 EqualityOnly = true;
4504 } else { // OtherSigned && ConstantSigned
4505 assert(0 && "Two signed types converted to unsigned types.");
4506 }
4507 }
4508
4509 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
4510
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004511 bool IsTrue = true;
Richard Trieu526e6272012-11-14 22:50:24 +00004512 if (op == BO_EQ || op == BO_NE) {
4513 IsTrue = op == BO_NE;
4514 } else if (EqualityOnly) {
4515 return;
4516 } else if (RhsConstant) {
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004517 if (op == BO_GT || op == BO_GE)
Richard Trieu526e6272012-11-14 22:50:24 +00004518 IsTrue = !PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004519 else // op == BO_LT || op == BO_LE
Richard Trieu526e6272012-11-14 22:50:24 +00004520 IsTrue = PositiveConstant;
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004521 } else {
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004522 if (op == BO_LT || op == BO_LE)
Richard Trieu526e6272012-11-14 22:50:24 +00004523 IsTrue = !PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004524 else // op == BO_GT || op == BO_GE
Richard Trieu526e6272012-11-14 22:50:24 +00004525 IsTrue = PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004526 }
Ted Kremenek7adf3a92013-03-15 21:50:10 +00004527
4528 // If this is a comparison to an enum constant, include that
4529 // constant in the diagnostic.
4530 const EnumConstantDecl *ED = 0;
4531 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
4532 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
4533
4534 SmallString<64> PrettySourceValue;
4535 llvm::raw_svector_ostream OS(PrettySourceValue);
4536 if (ED)
Ted Kremenek9de50942013-03-15 22:02:46 +00004537 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenek7adf3a92013-03-15 21:50:10 +00004538 else
4539 OS << Value;
4540
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004541 S.Diag(E->getOperatorLoc(), diag::warn_out_of_range_compare)
Ted Kremenek7adf3a92013-03-15 21:50:10 +00004542 << OS.str() << OtherT << IsTrue
Richard Trieu526e6272012-11-14 22:50:24 +00004543 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004544}
4545
John McCall323ed742010-05-06 08:58:33 +00004546/// Analyze the operands of the given comparison. Implements the
4547/// fallback case from AnalyzeComparison.
Ted Kremenek0692a192012-01-31 05:37:37 +00004548static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00004549 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4550 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00004551}
John McCall51313c32010-01-04 23:31:57 +00004552
John McCallba26e582010-01-04 23:21:16 +00004553/// \brief Implements -Wsign-compare.
4554///
Richard Trieudd225092011-09-15 21:56:47 +00004555/// \param E the binary operator to check for warnings
Ted Kremenek0692a192012-01-31 05:37:37 +00004556static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCall323ed742010-05-06 08:58:33 +00004557 // The type the comparison is being performed in.
4558 QualType T = E->getLHS()->getType();
4559 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
4560 && "comparison with mismatched types");
Fariborz Jahanianab4702f2012-09-18 17:46:26 +00004561 if (E->isValueDependent())
4562 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004563
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004564 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
4565 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004566
4567 bool IsComparisonConstant = false;
4568
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004569 // Check whether an integer constant comparison results in a value
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004570 // of 'true' or 'false'.
4571 if (T->isIntegralType(S.Context)) {
4572 llvm::APSInt RHSValue;
4573 bool IsRHSIntegralLiteral =
4574 RHS->isIntegerConstantExpr(RHSValue, S.Context);
4575 llvm::APSInt LHSValue;
4576 bool IsLHSIntegralLiteral =
4577 LHS->isIntegerConstantExpr(LHSValue, S.Context);
4578 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
4579 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
4580 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
4581 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
4582 else
4583 IsComparisonConstant =
4584 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004585 } else if (!T->hasUnsignedIntegerRepresentation())
4586 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004587
John McCall323ed742010-05-06 08:58:33 +00004588 // We don't do anything special if this isn't an unsigned integral
4589 // comparison: we're only interested in integral comparisons, and
4590 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00004591 //
4592 // We also don't care about value-dependent expressions or expressions
4593 // whose result is a constant.
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004594 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCall323ed742010-05-06 08:58:33 +00004595 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004596
John McCall323ed742010-05-06 08:58:33 +00004597 // Check to see if one of the (unmodified) operands is of different
4598 // signedness.
4599 Expr *signedOperand, *unsignedOperand;
Richard Trieudd225092011-09-15 21:56:47 +00004600 if (LHS->getType()->hasSignedIntegerRepresentation()) {
4601 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00004602 "unsigned comparison between two signed integer expressions?");
Richard Trieudd225092011-09-15 21:56:47 +00004603 signedOperand = LHS;
4604 unsignedOperand = RHS;
4605 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
4606 signedOperand = RHS;
4607 unsignedOperand = LHS;
John McCallba26e582010-01-04 23:21:16 +00004608 } else {
John McCall323ed742010-05-06 08:58:33 +00004609 CheckTrivialUnsignedComparison(S, E);
4610 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004611 }
4612
John McCall323ed742010-05-06 08:58:33 +00004613 // Otherwise, calculate the effective range of the signed operand.
4614 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00004615
John McCall323ed742010-05-06 08:58:33 +00004616 // Go ahead and analyze implicit conversions in the operands. Note
4617 // that we skip the implicit conversions on both sides.
Richard Trieudd225092011-09-15 21:56:47 +00004618 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
4619 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00004620
John McCall323ed742010-05-06 08:58:33 +00004621 // If the signed range is non-negative, -Wsign-compare won't fire,
4622 // but we should still check for comparisons which are always true
4623 // or false.
4624 if (signedRange.NonNegative)
4625 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004626
4627 // For (in)equality comparisons, if the unsigned operand is a
4628 // constant which cannot collide with a overflowed signed operand,
4629 // then reinterpreting the signed operand as unsigned will not
4630 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00004631 if (E->isEqualityOp()) {
4632 unsigned comparisonWidth = S.Context.getIntWidth(T);
4633 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00004634
John McCall323ed742010-05-06 08:58:33 +00004635 // We should never be unable to prove that the unsigned operand is
4636 // non-negative.
4637 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
4638
4639 if (unsignedRange.Width < comparisonWidth)
4640 return;
4641 }
4642
Douglas Gregor6d3b93d2012-05-01 01:53:49 +00004643 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
4644 S.PDiag(diag::warn_mixed_sign_comparison)
4645 << LHS->getType() << RHS->getType()
4646 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallba26e582010-01-04 23:21:16 +00004647}
4648
John McCall15d7d122010-11-11 03:21:53 +00004649/// Analyzes an attempt to assign the given value to a bitfield.
4650///
4651/// Returns true if there was something fishy about the attempt.
Ted Kremenek0692a192012-01-31 05:37:37 +00004652static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
4653 SourceLocation InitLoc) {
John McCall15d7d122010-11-11 03:21:53 +00004654 assert(Bitfield->isBitField());
4655 if (Bitfield->isInvalidDecl())
4656 return false;
4657
John McCall91b60142010-11-11 05:33:51 +00004658 // White-list bool bitfields.
4659 if (Bitfield->getType()->isBooleanType())
4660 return false;
4661
Douglas Gregor46ff3032011-02-04 13:09:01 +00004662 // Ignore value- or type-dependent expressions.
4663 if (Bitfield->getBitWidth()->isValueDependent() ||
4664 Bitfield->getBitWidth()->isTypeDependent() ||
4665 Init->isValueDependent() ||
4666 Init->isTypeDependent())
4667 return false;
4668
John McCall15d7d122010-11-11 03:21:53 +00004669 Expr *OriginalInit = Init->IgnoreParenImpCasts();
4670
Richard Smith80d4b552011-12-28 19:48:30 +00004671 llvm::APSInt Value;
4672 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall15d7d122010-11-11 03:21:53 +00004673 return false;
4674
John McCall15d7d122010-11-11 03:21:53 +00004675 unsigned OriginalWidth = Value.getBitWidth();
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004676 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall15d7d122010-11-11 03:21:53 +00004677
4678 if (OriginalWidth <= FieldWidth)
4679 return false;
4680
Eli Friedman3a643af2012-01-26 23:11:39 +00004681 // Compute the value which the bitfield will contain.
Jay Foad9f71a8f2010-12-07 08:25:34 +00004682 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedman3a643af2012-01-26 23:11:39 +00004683 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall15d7d122010-11-11 03:21:53 +00004684
Eli Friedman3a643af2012-01-26 23:11:39 +00004685 // Check whether the stored value is equal to the original value.
4686 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieue1ecdc12012-07-23 20:21:35 +00004687 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall15d7d122010-11-11 03:21:53 +00004688 return false;
4689
Eli Friedman3a643af2012-01-26 23:11:39 +00004690 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedman34ff0622012-02-02 00:40:20 +00004691 // therefore don't strictly fit into a signed bitfield of width 1.
4692 if (FieldWidth == 1 && Value == 1)
Eli Friedman3a643af2012-01-26 23:11:39 +00004693 return false;
4694
John McCall15d7d122010-11-11 03:21:53 +00004695 std::string PrettyValue = Value.toString(10);
4696 std::string PrettyTrunc = TruncatedValue.toString(10);
4697
4698 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
4699 << PrettyValue << PrettyTrunc << OriginalInit->getType()
4700 << Init->getSourceRange();
4701
4702 return true;
4703}
4704
John McCallbeb22aa2010-11-09 23:24:47 +00004705/// Analyze the given simple or compound assignment for warning-worthy
4706/// operations.
Ted Kremenek0692a192012-01-31 05:37:37 +00004707static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCallbeb22aa2010-11-09 23:24:47 +00004708 // Just recurse on the LHS.
4709 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4710
4711 // We want to recurse on the RHS as normal unless we're assigning to
4712 // a bitfield.
John McCall993f43f2013-05-06 21:39:12 +00004713 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00004714 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall15d7d122010-11-11 03:21:53 +00004715 E->getOperatorLoc())) {
4716 // Recurse, ignoring any implicit conversions on the RHS.
4717 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
4718 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00004719 }
4720 }
4721
4722 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
4723}
4724
John McCall51313c32010-01-04 23:31:57 +00004725/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00004726static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00004727 SourceLocation CContext, unsigned diag,
4728 bool pruneControlFlow = false) {
4729 if (pruneControlFlow) {
4730 S.DiagRuntimeBehavior(E->getExprLoc(), E,
4731 S.PDiag(diag)
4732 << SourceType << T << E->getSourceRange()
4733 << SourceRange(CContext));
4734 return;
4735 }
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004736 S.Diag(E->getExprLoc(), diag)
4737 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
4738}
4739
Chandler Carruthe1b02e02011-04-05 06:47:57 +00004740/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00004741static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00004742 SourceLocation CContext, unsigned diag,
4743 bool pruneControlFlow = false) {
4744 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruthe1b02e02011-04-05 06:47:57 +00004745}
4746
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004747/// Diagnose an implicit cast from a literal expression. Does not warn when the
4748/// cast wouldn't lose information.
Chandler Carruthf65076e2011-04-10 08:36:24 +00004749void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
4750 SourceLocation CContext) {
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004751 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruthf65076e2011-04-10 08:36:24 +00004752 bool isExact = false;
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004753 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00004754 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
4755 T->hasUnsignedIntegerRepresentation());
4756 if (Value.convertToInteger(IntegerValue,
Chandler Carruthf65076e2011-04-10 08:36:24 +00004757 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004758 == llvm::APFloat::opOK && isExact)
Chandler Carruthf65076e2011-04-10 08:36:24 +00004759 return;
4760
David Blaikiebe0ee872012-05-15 16:56:36 +00004761 SmallString<16> PrettySourceValue;
4762 Value.toString(PrettySourceValue);
David Blaikiede7e7b82012-05-15 17:18:27 +00004763 SmallString<16> PrettyTargetValue;
David Blaikiebe0ee872012-05-15 16:56:36 +00004764 if (T->isSpecificBuiltinType(BuiltinType::Bool))
4765 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
4766 else
David Blaikiede7e7b82012-05-15 17:18:27 +00004767 IntegerValue.toString(PrettyTargetValue);
David Blaikiebe0ee872012-05-15 16:56:36 +00004768
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004769 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikiebe0ee872012-05-15 16:56:36 +00004770 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
4771 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruthf65076e2011-04-10 08:36:24 +00004772}
4773
John McCall091f23f2010-11-09 22:22:12 +00004774std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
4775 if (!Range.Width) return "0";
4776
4777 llvm::APSInt ValueInRange = Value;
4778 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00004779 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00004780 return ValueInRange.toString(10);
4781}
4782
Hans Wennborg88617a22012-08-28 15:44:30 +00004783static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
4784 if (!isa<ImplicitCastExpr>(Ex))
4785 return false;
4786
4787 Expr *InnerE = Ex->IgnoreParenImpCasts();
4788 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
4789 const Type *Source =
4790 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
4791 if (Target->isDependentType())
4792 return false;
4793
4794 const BuiltinType *FloatCandidateBT =
4795 dyn_cast<BuiltinType>(ToBool ? Source : Target);
4796 const Type *BoolCandidateType = ToBool ? Target : Source;
4797
4798 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
4799 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
4800}
4801
4802void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
4803 SourceLocation CC) {
4804 unsigned NumArgs = TheCall->getNumArgs();
4805 for (unsigned i = 0; i < NumArgs; ++i) {
4806 Expr *CurrA = TheCall->getArg(i);
4807 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
4808 continue;
4809
4810 bool IsSwapped = ((i > 0) &&
4811 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
4812 IsSwapped |= ((i < (NumArgs - 1)) &&
4813 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
4814 if (IsSwapped) {
4815 // Warn on this floating-point to bool conversion.
4816 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
4817 CurrA->getType(), CC,
4818 diag::warn_impcast_floating_point_to_bool);
4819 }
4820 }
4821}
4822
John McCall323ed742010-05-06 08:58:33 +00004823void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00004824 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00004825 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00004826
John McCall323ed742010-05-06 08:58:33 +00004827 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
4828 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
4829 if (Source == Target) return;
4830 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00004831
Chandler Carruth108f7562011-07-26 05:40:03 +00004832 // If the conversion context location is invalid don't complain. We also
4833 // don't want to emit a warning if the issue occurs from the expansion of
4834 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
4835 // delay this check as long as possible. Once we detect we are in that
4836 // scenario, we just return.
Ted Kremenekef9ff882011-03-10 20:03:42 +00004837 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00004838 return;
4839
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004840 // Diagnose implicit casts to bool.
4841 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
4842 if (isa<StringLiteral>(E))
4843 // Warn on string literal to bool. Checks for string literals in logical
4844 // expressions, for instances, assert(0 && "error here"), is prevented
4845 // by a check in AnalyzeImplicitConversions().
4846 return DiagnoseImpCast(S, E, T, CC,
4847 diag::warn_impcast_string_literal_to_bool);
Lang Hamese14ca9f2011-12-05 20:49:50 +00004848 if (Source->isFunctionType()) {
4849 // Warn on function to bool. Checks free functions and static member
4850 // functions. Weakly imported functions are excluded from the check,
4851 // since it's common to test their value to check whether the linker
4852 // found a definition for them.
4853 ValueDecl *D = 0;
4854 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
4855 D = R->getDecl();
4856 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
4857 D = M->getMemberDecl();
4858 }
4859
4860 if (D && !D->isWeak()) {
Richard Trieu26b45d82011-12-06 04:48:01 +00004861 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
4862 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
4863 << F << E->getSourceRange() << SourceRange(CC);
David Blaikie2def7732011-12-09 21:42:37 +00004864 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
4865 << FixItHint::CreateInsertion(E->getExprLoc(), "&");
4866 QualType ReturnType;
4867 UnresolvedSet<4> NonTemplateOverloads;
4868 S.isExprCallable(*E, ReturnType, NonTemplateOverloads);
4869 if (!ReturnType.isNull()
4870 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
4871 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
4872 << FixItHint::CreateInsertion(
4873 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu26b45d82011-12-06 04:48:01 +00004874 return;
4875 }
Lang Hamese14ca9f2011-12-05 20:49:50 +00004876 }
4877 }
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004878 }
John McCall51313c32010-01-04 23:31:57 +00004879
4880 // Strip vector types.
4881 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004882 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004883 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004884 return;
John McCallb4eb64d2010-10-08 02:01:28 +00004885 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004886 }
Chris Lattnerb792b302011-06-14 04:51:15 +00004887
4888 // If the vector cast is cast between two vectors of the same size, it is
4889 // a bitcast, not a conversion.
4890 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
4891 return;
John McCall51313c32010-01-04 23:31:57 +00004892
4893 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
4894 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
4895 }
4896
4897 // Strip complex types.
4898 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004899 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004900 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004901 return;
4902
John McCallb4eb64d2010-10-08 02:01:28 +00004903 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004904 }
John McCall51313c32010-01-04 23:31:57 +00004905
4906 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
4907 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
4908 }
4909
4910 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
4911 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
4912
4913 // If the source is floating point...
4914 if (SourceBT && SourceBT->isFloatingPoint()) {
4915 // ...and the target is floating point...
4916 if (TargetBT && TargetBT->isFloatingPoint()) {
4917 // ...then warn if we're dropping FP rank.
4918
4919 // Builtin FP kinds are ordered by increasing FP rank.
4920 if (SourceBT->getKind() > TargetBT->getKind()) {
4921 // Don't warn about float constants that are precisely
4922 // representable in the target type.
4923 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00004924 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00004925 // Value might be a float, a float vector, or a float complex.
4926 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00004927 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
4928 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00004929 return;
4930 }
4931
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004932 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004933 return;
4934
John McCallb4eb64d2010-10-08 02:01:28 +00004935 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00004936 }
4937 return;
4938 }
4939
Ted Kremenekef9ff882011-03-10 20:03:42 +00004940 // If the target is integral, always warn.
David Blaikiebe0ee872012-05-15 16:56:36 +00004941 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004942 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004943 return;
4944
Chandler Carrutha5b93322011-02-17 11:05:49 +00004945 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay634c8af2011-09-08 22:30:47 +00004946 // We also want to warn on, e.g., "int i = -1.234"
4947 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
4948 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
4949 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
4950
Chandler Carruthf65076e2011-04-10 08:36:24 +00004951 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
4952 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00004953 } else {
4954 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
4955 }
4956 }
John McCall51313c32010-01-04 23:31:57 +00004957
Hans Wennborg88617a22012-08-28 15:44:30 +00004958 // If the target is bool, warn if expr is a function or method call.
4959 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
4960 isa<CallExpr>(E)) {
4961 // Check last argument of function call to see if it is an
4962 // implicit cast from a type matching the type the result
4963 // is being cast to.
4964 CallExpr *CEx = cast<CallExpr>(E);
4965 unsigned NumArgs = CEx->getNumArgs();
4966 if (NumArgs > 0) {
4967 Expr *LastA = CEx->getArg(NumArgs - 1);
4968 Expr *InnerE = LastA->IgnoreParenImpCasts();
4969 const Type *InnerType =
4970 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
4971 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
4972 // Warn on this floating-point to bool conversion
4973 DiagnoseImpCast(S, E, T, CC,
4974 diag::warn_impcast_floating_point_to_bool);
4975 }
4976 }
4977 }
John McCall51313c32010-01-04 23:31:57 +00004978 return;
4979 }
4980
Richard Trieu1838ca52011-05-29 19:59:02 +00004981 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
David Blaikieb26331b2012-06-19 21:19:06 +00004982 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
David Blaikiee81b43b2012-11-08 00:41:20 +00004983 && !Target->isBlockPointerType() && !Target->isMemberPointerType()
David Blaikie896c7dd2013-02-16 00:56:22 +00004984 && Target->isScalarType() && !Target->isNullPtrType()) {
David Blaikieb1360492012-03-16 20:30:12 +00004985 SourceLocation Loc = E->getSourceRange().getBegin();
4986 if (Loc.isMacroID())
4987 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
David Blaikie9fb1ac52012-05-15 21:57:38 +00004988 if (!Loc.isMacroID() || CC.isMacroID())
4989 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
4990 << T << clang::SourceRange(CC)
4991 << FixItHint::CreateReplacement(Loc, S.getFixItZeroLiteralForType(T));
Richard Trieu1838ca52011-05-29 19:59:02 +00004992 }
4993
David Blaikieb26331b2012-06-19 21:19:06 +00004994 if (!Source->isIntegerType() || !Target->isIntegerType())
4995 return;
4996
David Blaikiebe0ee872012-05-15 16:56:36 +00004997 // TODO: remove this early return once the false positives for constant->bool
4998 // in templates, macros, etc, are reduced or removed.
4999 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
5000 return;
5001
John McCall323ed742010-05-06 08:58:33 +00005002 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00005003 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00005004
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005005 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer25ffbef2013-03-28 19:07:11 +00005006 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005007 // TODO: this should happen for bitfield stores, too.
5008 llvm::APSInt Value(32);
5009 if (E->isIntegerConstantExpr(Value, S.Context)) {
5010 if (S.SourceMgr.isInSystemMacro(CC))
5011 return;
5012
John McCall091f23f2010-11-09 22:22:12 +00005013 std::string PrettySourceValue = Value.toString(10);
5014 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005015
Ted Kremenek5e745da2011-10-22 02:37:33 +00005016 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5017 S.PDiag(diag::warn_impcast_integer_precision_constant)
5018 << PrettySourceValue << PrettyTargetValue
5019 << E->getType() << T << E->getSourceRange()
5020 << clang::SourceRange(CC));
John McCall091f23f2010-11-09 22:22:12 +00005021 return;
5022 }
5023
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005024 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
5025 if (S.SourceMgr.isInSystemMacro(CC))
5026 return;
5027
David Blaikie37050842012-04-12 22:40:54 +00005028 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaksc36bedc2012-02-01 19:08:57 +00005029 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
5030 /* pruneControlFlow */ true);
John McCallb4eb64d2010-10-08 02:01:28 +00005031 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00005032 }
5033
5034 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
5035 (!TargetRange.NonNegative && SourceRange.NonNegative &&
5036 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00005037
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005038 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005039 return;
5040
John McCall323ed742010-05-06 08:58:33 +00005041 unsigned DiagID = diag::warn_impcast_integer_sign;
5042
5043 // Traditionally, gcc has warned about this under -Wsign-compare.
5044 // We also want to warn about it in -Wconversion.
5045 // So if -Wconversion is off, use a completely identical diagnostic
5046 // in the sign-compare group.
5047 // The conditional-checking code will
5048 if (ICContext) {
5049 DiagID = diag::warn_impcast_integer_sign_conditional;
5050 *ICContext = true;
5051 }
5052
John McCallb4eb64d2010-10-08 02:01:28 +00005053 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00005054 }
5055
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005056 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005057 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
5058 // type, to give us better diagnostics.
5059 QualType SourceType = E->getType();
David Blaikie4e4d0842012-03-11 07:00:24 +00005060 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005061 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5062 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
5063 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
5064 SourceType = S.Context.getTypeDeclType(Enum);
5065 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
5066 }
5067 }
5068
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005069 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
5070 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall83972f12013-03-09 00:54:27 +00005071 if (SourceEnum->getDecl()->hasNameForLinkage() &&
5072 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00005073 SourceEnum != TargetEnum) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005074 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005075 return;
5076
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005077 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005078 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00005079 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005080
John McCall51313c32010-01-04 23:31:57 +00005081 return;
5082}
5083
David Blaikie9fb1ac52012-05-15 21:57:38 +00005084void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5085 SourceLocation CC, QualType T);
John McCall323ed742010-05-06 08:58:33 +00005086
5087void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00005088 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00005089 E = E->IgnoreParenImpCasts();
5090
5091 if (isa<ConditionalOperator>(E))
David Blaikie9fb1ac52012-05-15 21:57:38 +00005092 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCall323ed742010-05-06 08:58:33 +00005093
John McCallb4eb64d2010-10-08 02:01:28 +00005094 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005095 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00005096 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00005097 return;
5098}
5099
David Blaikie9fb1ac52012-05-15 21:57:38 +00005100void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5101 SourceLocation CC, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00005102 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00005103
5104 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00005105 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
5106 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00005107
5108 // If -Wconversion would have warned about either of the candidates
5109 // for a signedness conversion to the context type...
5110 if (!Suspicious) return;
5111
5112 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00005113 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
5114 CC))
John McCall323ed742010-05-06 08:58:33 +00005115 return;
5116
John McCall323ed742010-05-06 08:58:33 +00005117 // ...then check whether it would have warned about either of the
5118 // candidates for a signedness conversion to the condition type.
Richard Trieu52541612011-07-21 02:46:28 +00005119 if (E->getType() == T) return;
5120
5121 Suspicious = false;
5122 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
5123 E->getType(), CC, &Suspicious);
5124 if (!Suspicious)
5125 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00005126 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00005127}
5128
5129/// AnalyzeImplicitConversions - Find and report any interesting
5130/// implicit conversions in the given expression. There are a couple
5131/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00005132void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00005133 QualType T = OrigE->getType();
5134 Expr *E = OrigE->IgnoreParenImpCasts();
5135
Douglas Gregorf8b6e152011-10-10 17:38:18 +00005136 if (E->isTypeDependent() || E->isValueDependent())
5137 return;
5138
John McCall323ed742010-05-06 08:58:33 +00005139 // For conditional operators, we analyze the arguments as if they
5140 // were being fed directly into the output.
5141 if (isa<ConditionalOperator>(E)) {
5142 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie9fb1ac52012-05-15 21:57:38 +00005143 CheckConditionalOperator(S, CO, CC, T);
John McCall323ed742010-05-06 08:58:33 +00005144 return;
5145 }
5146
Hans Wennborg88617a22012-08-28 15:44:30 +00005147 // Check implicit argument conversions for function calls.
5148 if (CallExpr *Call = dyn_cast<CallExpr>(E))
5149 CheckImplicitArgumentConversions(S, Call, CC);
5150
John McCall323ed742010-05-06 08:58:33 +00005151 // Go ahead and check any implicit conversions we might have skipped.
5152 // The non-canonical typecheck is just an optimization;
5153 // CheckImplicitConversion will filter out dead implicit conversions.
5154 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00005155 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00005156
5157 // Now continue drilling into this expression.
Fariborz Jahanian6f2a9fa2013-05-15 19:03:04 +00005158
5159 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahaniana1bfe1c2013-05-15 22:25:03 +00005160 if (POE->getResultExpr())
5161 E = POE->getResultExpr();
Fariborz Jahanian6f2a9fa2013-05-15 19:03:04 +00005162 }
5163
Fariborz Jahaniana1bfe1c2013-05-15 22:25:03 +00005164 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5165 return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
5166
John McCall323ed742010-05-06 08:58:33 +00005167 // Skip past explicit casts.
5168 if (isa<ExplicitCastExpr>(E)) {
5169 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00005170 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005171 }
5172
John McCallbeb22aa2010-11-09 23:24:47 +00005173 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5174 // Do a somewhat different check with comparison operators.
5175 if (BO->isComparisonOp())
5176 return AnalyzeComparison(S, BO);
5177
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005178 // And with simple assignments.
5179 if (BO->getOpcode() == BO_Assign)
John McCallbeb22aa2010-11-09 23:24:47 +00005180 return AnalyzeAssignment(S, BO);
5181 }
John McCall323ed742010-05-06 08:58:33 +00005182
5183 // These break the otherwise-useful invariant below. Fortunately,
5184 // we don't really need to recurse into them, because any internal
5185 // expressions should have been analyzed already when they were
5186 // built into statements.
5187 if (isa<StmtExpr>(E)) return;
5188
5189 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005190 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00005191
5192 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00005193 CC = E->getExprLoc();
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005194 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
5195 bool IsLogicalOperator = BO && BO->isLogicalOp();
5196 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor54042f12012-02-09 10:18:50 +00005197 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor503384f2012-02-09 00:47:04 +00005198 if (!ChildExpr)
5199 continue;
5200
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005201 if (IsLogicalOperator &&
5202 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
5203 // Ignore checking string literals that are in logical operators.
5204 continue;
5205 AnalyzeImplicitConversions(S, ChildExpr, CC);
5206 }
John McCall323ed742010-05-06 08:58:33 +00005207}
5208
5209} // end anonymous namespace
5210
5211/// Diagnoses "dangerous" implicit conversions within the given
5212/// expression (which is a full expression). Implements -Wconversion
5213/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00005214///
5215/// \param CC the "context" location of the implicit conversion, i.e.
5216/// the most location of the syntactic entity requiring the implicit
5217/// conversion
5218void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00005219 // Don't diagnose in unevaluated contexts.
David Blaikie71f55f72012-08-06 22:47:24 +00005220 if (isUnevaluatedContext())
John McCall323ed742010-05-06 08:58:33 +00005221 return;
5222
5223 // Don't diagnose for value- or type-dependent expressions.
5224 if (E->isTypeDependent() || E->isValueDependent())
5225 return;
5226
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005227 // Check for array bounds violations in cases where the check isn't triggered
5228 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
5229 // ArraySubscriptExpr is on the RHS of a variable initialization.
5230 CheckArrayAccess(E);
5231
John McCallb4eb64d2010-10-08 02:01:28 +00005232 // This is not the right CC for (e.g.) a variable initialization.
5233 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005234}
5235
Fariborz Jahanianad48a502013-01-24 22:11:45 +00005236/// Diagnose when expression is an integer constant expression and its evaluation
5237/// results in integer overflow
5238void Sema::CheckForIntOverflow (Expr *E) {
Fariborz Jahanian1fd8d462013-03-15 20:47:07 +00005239 if (isa<BinaryOperator>(E->IgnoreParens())) {
Fariborz Jahanianad48a502013-01-24 22:11:45 +00005240 llvm::SmallVector<PartialDiagnosticAt, 4> Diags;
5241 E->EvaluateForOverflow(Context, &Diags);
5242 }
5243}
5244
Richard Smith6c3af3d2013-01-17 01:17:56 +00005245namespace {
5246/// \brief Visitor for expressions which looks for unsequenced operations on the
5247/// same object.
5248class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
5249 /// \brief A tree of sequenced regions within an expression. Two regions are
5250 /// unsequenced if one is an ancestor or a descendent of the other. When we
5251 /// finish processing an expression with sequencing, such as a comma
5252 /// expression, we fold its tree nodes into its parent, since they are
5253 /// unsequenced with respect to nodes we will visit later.
5254 class SequenceTree {
5255 struct Value {
5256 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
5257 unsigned Parent : 31;
5258 bool Merged : 1;
5259 };
5260 llvm::SmallVector<Value, 8> Values;
5261
5262 public:
5263 /// \brief A region within an expression which may be sequenced with respect
5264 /// to some other region.
5265 class Seq {
5266 explicit Seq(unsigned N) : Index(N) {}
5267 unsigned Index;
5268 friend class SequenceTree;
5269 public:
5270 Seq() : Index(0) {}
5271 };
5272
5273 SequenceTree() { Values.push_back(Value(0)); }
5274 Seq root() const { return Seq(0); }
5275
5276 /// \brief Create a new sequence of operations, which is an unsequenced
5277 /// subset of \p Parent. This sequence of operations is sequenced with
5278 /// respect to other children of \p Parent.
5279 Seq allocate(Seq Parent) {
5280 Values.push_back(Value(Parent.Index));
5281 return Seq(Values.size() - 1);
5282 }
5283
5284 /// \brief Merge a sequence of operations into its parent.
5285 void merge(Seq S) {
5286 Values[S.Index].Merged = true;
5287 }
5288
5289 /// \brief Determine whether two operations are unsequenced. This operation
5290 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
5291 /// should have been merged into its parent as appropriate.
5292 bool isUnsequenced(Seq Cur, Seq Old) {
5293 unsigned C = representative(Cur.Index);
5294 unsigned Target = representative(Old.Index);
5295 while (C >= Target) {
5296 if (C == Target)
5297 return true;
5298 C = Values[C].Parent;
5299 }
5300 return false;
5301 }
5302
5303 private:
5304 /// \brief Pick a representative for a sequence.
5305 unsigned representative(unsigned K) {
5306 if (Values[K].Merged)
5307 // Perform path compression as we go.
5308 return Values[K].Parent = representative(Values[K].Parent);
5309 return K;
5310 }
5311 };
5312
5313 /// An object for which we can track unsequenced uses.
5314 typedef NamedDecl *Object;
5315
5316 /// Different flavors of object usage which we track. We only track the
5317 /// least-sequenced usage of each kind.
5318 enum UsageKind {
5319 /// A read of an object. Multiple unsequenced reads are OK.
5320 UK_Use,
5321 /// A modification of an object which is sequenced before the value
5322 /// computation of the expression, such as ++n.
5323 UK_ModAsValue,
5324 /// A modification of an object which is not sequenced before the value
5325 /// computation of the expression, such as n++.
5326 UK_ModAsSideEffect,
5327
5328 UK_Count = UK_ModAsSideEffect + 1
5329 };
5330
5331 struct Usage {
5332 Usage() : Use(0), Seq() {}
5333 Expr *Use;
5334 SequenceTree::Seq Seq;
5335 };
5336
5337 struct UsageInfo {
5338 UsageInfo() : Diagnosed(false) {}
5339 Usage Uses[UK_Count];
5340 /// Have we issued a diagnostic for this variable already?
5341 bool Diagnosed;
5342 };
5343 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
5344
5345 Sema &SemaRef;
5346 /// Sequenced regions within the expression.
5347 SequenceTree Tree;
5348 /// Declaration modifications and references which we have seen.
5349 UsageInfoMap UsageMap;
5350 /// The region we are currently within.
5351 SequenceTree::Seq Region;
5352 /// Filled in with declarations which were modified as a side-effect
5353 /// (that is, post-increment operations).
5354 llvm::SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smith1a2dcd52013-01-17 23:18:09 +00005355 /// Expressions to check later. We defer checking these to reduce
5356 /// stack usage.
5357 llvm::SmallVectorImpl<Expr*> &WorkList;
Richard Smith6c3af3d2013-01-17 01:17:56 +00005358
5359 /// RAII object wrapping the visitation of a sequenced subexpression of an
5360 /// expression. At the end of this process, the side-effects of the evaluation
5361 /// become sequenced with respect to the value computation of the result, so
5362 /// we downgrade any UK_ModAsSideEffect within the evaluation to
5363 /// UK_ModAsValue.
5364 struct SequencedSubexpression {
5365 SequencedSubexpression(SequenceChecker &Self)
5366 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
5367 Self.ModAsSideEffect = &ModAsSideEffect;
5368 }
5369 ~SequencedSubexpression() {
5370 for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) {
5371 UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first];
5372 U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second;
5373 Self.addUsage(U, ModAsSideEffect[I].first,
5374 ModAsSideEffect[I].second.Use, UK_ModAsValue);
5375 }
5376 Self.ModAsSideEffect = OldModAsSideEffect;
5377 }
5378
5379 SequenceChecker &Self;
5380 llvm::SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
5381 llvm::SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
5382 };
5383
5384 /// \brief Find the object which is produced by the specified expression,
5385 /// if any.
5386 Object getObject(Expr *E, bool Mod) const {
5387 E = E->IgnoreParenCasts();
5388 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5389 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
5390 return getObject(UO->getSubExpr(), Mod);
5391 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5392 if (BO->getOpcode() == BO_Comma)
5393 return getObject(BO->getRHS(), Mod);
5394 if (Mod && BO->isAssignmentOp())
5395 return getObject(BO->getLHS(), Mod);
5396 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
5397 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
5398 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
5399 return ME->getMemberDecl();
5400 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5401 // FIXME: If this is a reference, map through to its value.
5402 return DRE->getDecl();
5403 return 0;
5404 }
5405
5406 /// \brief Note that an object was modified or used by an expression.
5407 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
5408 Usage &U = UI.Uses[UK];
5409 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
5410 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
5411 ModAsSideEffect->push_back(std::make_pair(O, U));
5412 U.Use = Ref;
5413 U.Seq = Region;
5414 }
5415 }
5416 /// \brief Check whether a modification or use conflicts with a prior usage.
5417 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
5418 bool IsModMod) {
5419 if (UI.Diagnosed)
5420 return;
5421
5422 const Usage &U = UI.Uses[OtherKind];
5423 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
5424 return;
5425
5426 Expr *Mod = U.Use;
5427 Expr *ModOrUse = Ref;
5428 if (OtherKind == UK_Use)
5429 std::swap(Mod, ModOrUse);
5430
5431 SemaRef.Diag(Mod->getExprLoc(),
5432 IsModMod ? diag::warn_unsequenced_mod_mod
5433 : diag::warn_unsequenced_mod_use)
5434 << O << SourceRange(ModOrUse->getExprLoc());
5435 UI.Diagnosed = true;
5436 }
5437
5438 void notePreUse(Object O, Expr *Use) {
5439 UsageInfo &U = UsageMap[O];
5440 // Uses conflict with other modifications.
5441 checkUsage(O, U, Use, UK_ModAsValue, false);
5442 }
5443 void notePostUse(Object O, Expr *Use) {
5444 UsageInfo &U = UsageMap[O];
5445 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
5446 addUsage(U, O, Use, UK_Use);
5447 }
5448
5449 void notePreMod(Object O, Expr *Mod) {
5450 UsageInfo &U = UsageMap[O];
5451 // Modifications conflict with other modifications and with uses.
5452 checkUsage(O, U, Mod, UK_ModAsValue, true);
5453 checkUsage(O, U, Mod, UK_Use, false);
5454 }
5455 void notePostMod(Object O, Expr *Use, UsageKind UK) {
5456 UsageInfo &U = UsageMap[O];
5457 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
5458 addUsage(U, O, Use, UK);
5459 }
5460
5461public:
Richard Smith1a2dcd52013-01-17 23:18:09 +00005462 SequenceChecker(Sema &S, Expr *E,
5463 llvm::SmallVectorImpl<Expr*> &WorkList)
Richard Smithe5096c82013-01-17 01:40:50 +00005464 : EvaluatedExprVisitor<SequenceChecker>(S.Context), SemaRef(S),
Richard Smith1a2dcd52013-01-17 23:18:09 +00005465 Region(Tree.root()), ModAsSideEffect(0), WorkList(WorkList) {
Richard Smith6c3af3d2013-01-17 01:17:56 +00005466 Visit(E);
5467 }
5468
5469 void VisitStmt(Stmt *S) {
5470 // Skip all statements which aren't expressions for now.
5471 }
5472
5473 void VisitExpr(Expr *E) {
5474 // By default, just recurse to evaluated subexpressions.
Richard Smithe5096c82013-01-17 01:40:50 +00005475 EvaluatedExprVisitor<SequenceChecker>::VisitStmt(E);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005476 }
5477
5478 void VisitCastExpr(CastExpr *E) {
5479 Object O = Object();
5480 if (E->getCastKind() == CK_LValueToRValue)
5481 O = getObject(E->getSubExpr(), false);
5482
5483 if (O)
5484 notePreUse(O, E);
5485 VisitExpr(E);
5486 if (O)
5487 notePostUse(O, E);
5488 }
5489
5490 void VisitBinComma(BinaryOperator *BO) {
5491 // C++11 [expr.comma]p1:
5492 // Every value computation and side effect associated with the left
5493 // expression is sequenced before every value computation and side
5494 // effect associated with the right expression.
5495 SequenceTree::Seq LHS = Tree.allocate(Region);
5496 SequenceTree::Seq RHS = Tree.allocate(Region);
5497 SequenceTree::Seq OldRegion = Region;
5498
5499 {
5500 SequencedSubexpression SeqLHS(*this);
5501 Region = LHS;
5502 Visit(BO->getLHS());
5503 }
5504
5505 Region = RHS;
5506 Visit(BO->getRHS());
5507
5508 Region = OldRegion;
5509
5510 // Forget that LHS and RHS are sequenced. They are both unsequenced
5511 // with respect to other stuff.
5512 Tree.merge(LHS);
5513 Tree.merge(RHS);
5514 }
5515
5516 void VisitBinAssign(BinaryOperator *BO) {
5517 // The modification is sequenced after the value computation of the LHS
5518 // and RHS, so check it before inspecting the operands and update the
5519 // map afterwards.
5520 Object O = getObject(BO->getLHS(), true);
5521 if (!O)
5522 return VisitExpr(BO);
5523
5524 notePreMod(O, BO);
5525
5526 // C++11 [expr.ass]p7:
5527 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
5528 // only once.
5529 //
5530 // Therefore, for a compound assignment operator, O is considered used
5531 // everywhere except within the evaluation of E1 itself.
5532 if (isa<CompoundAssignOperator>(BO))
5533 notePreUse(O, BO);
5534
5535 Visit(BO->getLHS());
5536
5537 if (isa<CompoundAssignOperator>(BO))
5538 notePostUse(O, BO);
5539
5540 Visit(BO->getRHS());
5541
5542 notePostMod(O, BO, UK_ModAsValue);
5543 }
5544 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
5545 VisitBinAssign(CAO);
5546 }
5547
5548 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
5549 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
5550 void VisitUnaryPreIncDec(UnaryOperator *UO) {
5551 Object O = getObject(UO->getSubExpr(), true);
5552 if (!O)
5553 return VisitExpr(UO);
5554
5555 notePreMod(O, UO);
5556 Visit(UO->getSubExpr());
5557 notePostMod(O, UO, UK_ModAsValue);
5558 }
5559
5560 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
5561 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
5562 void VisitUnaryPostIncDec(UnaryOperator *UO) {
5563 Object O = getObject(UO->getSubExpr(), true);
5564 if (!O)
5565 return VisitExpr(UO);
5566
5567 notePreMod(O, UO);
5568 Visit(UO->getSubExpr());
5569 notePostMod(O, UO, UK_ModAsSideEffect);
5570 }
5571
5572 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
5573 void VisitBinLOr(BinaryOperator *BO) {
5574 // The side-effects of the LHS of an '&&' are sequenced before the
5575 // value computation of the RHS, and hence before the value computation
5576 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
5577 // as if they were unconditionally sequenced.
5578 {
5579 SequencedSubexpression Sequenced(*this);
5580 Visit(BO->getLHS());
5581 }
5582
5583 bool Result;
5584 if (!BO->getLHS()->isValueDependent() &&
Richard Smith995e4a72013-01-17 22:06:26 +00005585 BO->getLHS()->EvaluateAsBooleanCondition(Result, SemaRef.Context)) {
5586 if (!Result)
5587 Visit(BO->getRHS());
5588 } else {
5589 // Check for unsequenced operations in the RHS, treating it as an
5590 // entirely separate evaluation.
5591 //
5592 // FIXME: If there are operations in the RHS which are unsequenced
5593 // with respect to operations outside the RHS, and those operations
5594 // are unconditionally evaluated, diagnose them.
Richard Smith1a2dcd52013-01-17 23:18:09 +00005595 WorkList.push_back(BO->getRHS());
Richard Smith995e4a72013-01-17 22:06:26 +00005596 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00005597 }
5598 void VisitBinLAnd(BinaryOperator *BO) {
5599 {
5600 SequencedSubexpression Sequenced(*this);
5601 Visit(BO->getLHS());
5602 }
5603
5604 bool Result;
5605 if (!BO->getLHS()->isValueDependent() &&
Richard Smith995e4a72013-01-17 22:06:26 +00005606 BO->getLHS()->EvaluateAsBooleanCondition(Result, SemaRef.Context)) {
5607 if (Result)
5608 Visit(BO->getRHS());
5609 } else {
Richard Smith1a2dcd52013-01-17 23:18:09 +00005610 WorkList.push_back(BO->getRHS());
Richard Smith995e4a72013-01-17 22:06:26 +00005611 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00005612 }
5613
5614 // Only visit the condition, unless we can be sure which subexpression will
5615 // be chosen.
5616 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
5617 SequencedSubexpression Sequenced(*this);
5618 Visit(CO->getCond());
5619
5620 bool Result;
5621 if (!CO->getCond()->isValueDependent() &&
5622 CO->getCond()->EvaluateAsBooleanCondition(Result, SemaRef.Context))
5623 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith995e4a72013-01-17 22:06:26 +00005624 else {
Richard Smith1a2dcd52013-01-17 23:18:09 +00005625 WorkList.push_back(CO->getTrueExpr());
5626 WorkList.push_back(CO->getFalseExpr());
Richard Smith995e4a72013-01-17 22:06:26 +00005627 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00005628 }
5629
5630 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
5631 if (!CCE->isListInitialization())
5632 return VisitExpr(CCE);
5633
5634 // In C++11, list initializations are sequenced.
5635 llvm::SmallVector<SequenceTree::Seq, 32> Elts;
5636 SequenceTree::Seq Parent = Region;
5637 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
5638 E = CCE->arg_end();
5639 I != E; ++I) {
5640 Region = Tree.allocate(Parent);
5641 Elts.push_back(Region);
5642 Visit(*I);
5643 }
5644
5645 // Forget that the initializers are sequenced.
5646 Region = Parent;
5647 for (unsigned I = 0; I < Elts.size(); ++I)
5648 Tree.merge(Elts[I]);
5649 }
5650
5651 void VisitInitListExpr(InitListExpr *ILE) {
5652 if (!SemaRef.getLangOpts().CPlusPlus11)
5653 return VisitExpr(ILE);
5654
5655 // In C++11, list initializations are sequenced.
5656 llvm::SmallVector<SequenceTree::Seq, 32> Elts;
5657 SequenceTree::Seq Parent = Region;
5658 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
5659 Expr *E = ILE->getInit(I);
5660 if (!E) continue;
5661 Region = Tree.allocate(Parent);
5662 Elts.push_back(Region);
5663 Visit(E);
5664 }
5665
5666 // Forget that the initializers are sequenced.
5667 Region = Parent;
5668 for (unsigned I = 0; I < Elts.size(); ++I)
5669 Tree.merge(Elts[I]);
5670 }
5671};
5672}
5673
5674void Sema::CheckUnsequencedOperations(Expr *E) {
Richard Smith1a2dcd52013-01-17 23:18:09 +00005675 llvm::SmallVector<Expr*, 8> WorkList;
5676 WorkList.push_back(E);
5677 while (!WorkList.empty()) {
5678 Expr *Item = WorkList.back();
5679 WorkList.pop_back();
5680 SequenceChecker(*this, Item, WorkList);
5681 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00005682}
5683
Fariborz Jahanianad48a502013-01-24 22:11:45 +00005684void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
5685 bool IsConstexpr) {
Richard Smith6c3af3d2013-01-17 01:17:56 +00005686 CheckImplicitConversions(E, CheckLoc);
5687 CheckUnsequencedOperations(E);
Fariborz Jahanianad48a502013-01-24 22:11:45 +00005688 if (!IsConstexpr && !E->isValueDependent())
5689 CheckForIntOverflow(E);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005690}
5691
John McCall15d7d122010-11-11 03:21:53 +00005692void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
5693 FieldDecl *BitField,
5694 Expr *Init) {
5695 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
5696}
5697
Mike Stumpf8c49212010-01-21 03:59:47 +00005698/// CheckParmsForFunctionDef - Check that the parameters of the given
5699/// function are appropriate for the definition of a function. This
5700/// takes care of any checks that cannot be performed on the
5701/// declaration itself, e.g., that the types of each of the function
5702/// parameters are complete.
Douglas Gregor82aa7132010-11-01 18:37:59 +00005703bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
5704 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00005705 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00005706 for (; P != PEnd; ++P) {
5707 ParmVarDecl *Param = *P;
5708
Mike Stumpf8c49212010-01-21 03:59:47 +00005709 // C99 6.7.5.3p4: the parameters in a parameter type list in a
5710 // function declarator that is part of a function definition of
5711 // that function shall not have incomplete type.
5712 //
5713 // This is also C++ [dcl.fct]p6.
5714 if (!Param->isInvalidDecl() &&
5715 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00005716 diag::err_typecheck_decl_incomplete_type)) {
Mike Stumpf8c49212010-01-21 03:59:47 +00005717 Param->setInvalidDecl();
5718 HasInvalidParm = true;
5719 }
5720
5721 // C99 6.9.1p5: If the declarator includes a parameter type list, the
5722 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00005723 if (CheckParameterNames &&
5724 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00005725 !Param->isImplicit() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00005726 !getLangOpts().CPlusPlus)
Mike Stumpf8c49212010-01-21 03:59:47 +00005727 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00005728
5729 // C99 6.7.5.3p12:
5730 // If the function declarator is not part of a definition of that
5731 // function, parameters may have incomplete type and may use the [*]
5732 // notation in their sequences of declarator specifiers to specify
5733 // variable length array types.
5734 QualType PType = Param->getOriginalType();
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00005735 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigd17e3402010-02-01 05:02:49 +00005736 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitfc093362013-03-01 21:41:22 +00005737 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigd17e3402010-02-01 05:02:49 +00005738 // information is added for it.
5739 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00005740 break;
Sam Weinigd17e3402010-02-01 05:02:49 +00005741 }
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00005742 PType= AT->getElementType();
Sam Weinigd17e3402010-02-01 05:02:49 +00005743 }
Mike Stumpf8c49212010-01-21 03:59:47 +00005744 }
5745
5746 return HasInvalidParm;
5747}
John McCallb7f4ffe2010-08-12 21:44:57 +00005748
5749/// CheckCastAlign - Implements -Wcast-align, which warns when a
5750/// pointer cast increases the alignment requirements.
5751void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
5752 // This is actually a lot of work to potentially be doing on every
5753 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00005754 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
5755 TRange.getBegin())
David Blaikied6471f72011-09-25 23:23:43 +00005756 == DiagnosticsEngine::Ignored)
John McCallb7f4ffe2010-08-12 21:44:57 +00005757 return;
5758
5759 // Ignore dependent types.
5760 if (T->isDependentType() || Op->getType()->isDependentType())
5761 return;
5762
5763 // Require that the destination be a pointer type.
5764 const PointerType *DestPtr = T->getAs<PointerType>();
5765 if (!DestPtr) return;
5766
5767 // If the destination has alignment 1, we're done.
5768 QualType DestPointee = DestPtr->getPointeeType();
5769 if (DestPointee->isIncompleteType()) return;
5770 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
5771 if (DestAlign.isOne()) return;
5772
5773 // Require that the source be a pointer type.
5774 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
5775 if (!SrcPtr) return;
5776 QualType SrcPointee = SrcPtr->getPointeeType();
5777
5778 // Whitelist casts from cv void*. We already implicitly
5779 // whitelisted casts to cv void*, since they have alignment 1.
5780 // Also whitelist casts involving incomplete types, which implicitly
5781 // includes 'void'.
5782 if (SrcPointee->isIncompleteType()) return;
5783
5784 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
5785 if (SrcAlign >= DestAlign) return;
5786
5787 Diag(TRange.getBegin(), diag::warn_cast_align)
5788 << Op->getType() << T
5789 << static_cast<unsigned>(SrcAlign.getQuantity())
5790 << static_cast<unsigned>(DestAlign.getQuantity())
5791 << TRange << Op->getSourceRange();
5792}
5793
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005794static const Type* getElementType(const Expr *BaseExpr) {
5795 const Type* EltType = BaseExpr->getType().getTypePtr();
5796 if (EltType->isAnyPointerType())
5797 return EltType->getPointeeType().getTypePtr();
5798 else if (EltType->isArrayType())
5799 return EltType->getBaseElementTypeUnsafe();
5800 return EltType;
5801}
5802
Chandler Carruthc2684342011-08-05 09:10:50 +00005803/// \brief Check whether this array fits the idiom of a size-one tail padded
5804/// array member of a struct.
5805///
5806/// We avoid emitting out-of-bounds access warnings for such arrays as they are
5807/// commonly used to emulate flexible arrays in C89 code.
5808static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
5809 const NamedDecl *ND) {
5810 if (Size != 1 || !ND) return false;
5811
5812 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
5813 if (!FD) return false;
5814
5815 // Don't consider sizes resulting from macro expansions or template argument
5816 // substitution to form C89 tail-padded arrays.
Sean Callanand2cf3482012-05-04 18:22:53 +00005817
5818 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00005819 while (TInfo) {
5820 TypeLoc TL = TInfo->getTypeLoc();
5821 // Look through typedefs.
David Blaikie39e6ab42013-02-18 22:06:02 +00005822 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
5823 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00005824 TInfo = TDL->getTypeSourceInfo();
5825 continue;
5826 }
David Blaikie39e6ab42013-02-18 22:06:02 +00005827 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
5828 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier5e253012013-02-06 00:58:34 +00005829 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
5830 return false;
5831 }
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00005832 break;
Sean Callanand2cf3482012-05-04 18:22:53 +00005833 }
Chandler Carruthc2684342011-08-05 09:10:50 +00005834
5835 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gay381711c2011-11-29 22:43:53 +00005836 if (!RD) return false;
5837 if (RD->isUnion()) return false;
5838 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
5839 if (!CRD->isStandardLayout()) return false;
5840 }
Chandler Carruthc2684342011-08-05 09:10:50 +00005841
Benjamin Kramer22d4fed2011-08-06 03:04:42 +00005842 // See if this is the last field decl in the record.
5843 const Decl *D = FD;
5844 while ((D = D->getNextDeclInContext()))
5845 if (isa<FieldDecl>(D))
5846 return false;
5847 return true;
Chandler Carruthc2684342011-08-05 09:10:50 +00005848}
5849
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005850void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005851 const ArraySubscriptExpr *ASE,
Richard Smith25b009a2011-12-16 19:31:14 +00005852 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman92b670e2012-02-27 21:21:40 +00005853 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005854 if (IndexExpr->isValueDependent())
5855 return;
5856
Matt Beaumont-Gay8ef8f432011-12-12 22:35:02 +00005857 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005858 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00005859 const ConstantArrayType *ArrayTy =
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005860 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00005861 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00005862 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00005863
Chandler Carruth34064582011-02-17 20:55:08 +00005864 llvm::APSInt index;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005865 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00005866 return;
Richard Smith25b009a2011-12-16 19:31:14 +00005867 if (IndexNegated)
5868 index = -index;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00005869
Chandler Carruthba447122011-08-05 08:07:29 +00005870 const NamedDecl *ND = NULL;
Chandler Carruthba447122011-08-05 08:07:29 +00005871 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
5872 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruthc2684342011-08-05 09:10:50 +00005873 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruthba447122011-08-05 08:07:29 +00005874 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruthba447122011-08-05 08:07:29 +00005875
Ted Kremenek9e060ca2011-02-23 23:06:04 +00005876 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00005877 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00005878 if (!size.isStrictlyPositive())
5879 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005880
5881 const Type* BaseType = getElementType(BaseExpr);
Nico Weberde5998f2011-09-17 22:59:41 +00005882 if (BaseType != EffectiveType) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005883 // Make sure we're comparing apples to apples when comparing index to size
5884 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
5885 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhraind10f4bc2011-08-10 19:47:25 +00005886 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhrain18f16972011-08-10 18:49:28 +00005887 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005888 if (ptrarith_typesize != array_typesize) {
5889 // There's a cast to a different size type involved
5890 uint64_t ratio = array_typesize / ptrarith_typesize;
5891 // TODO: Be smarter about handling cases where array_typesize is not a
5892 // multiple of ptrarith_typesize
5893 if (ptrarith_typesize * ratio == array_typesize)
5894 size *= llvm::APInt(size.getBitWidth(), ratio);
5895 }
5896 }
5897
Chandler Carruth34064582011-02-17 20:55:08 +00005898 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00005899 index = index.zext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00005900 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00005901 size = size.zext(index.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00005902
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005903 // For array subscripting the index must be less than size, but for pointer
5904 // arithmetic also allow the index (offset) to be equal to size since
5905 // computing the next address after the end of the array is legal and
5906 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman92b670e2012-02-27 21:21:40 +00005907 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruthba447122011-08-05 08:07:29 +00005908 return;
5909
5910 // Also don't warn for arrays of size 1 which are members of some
5911 // structure. These are often used to approximate flexible arrays in C89
5912 // code.
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005913 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00005914 return;
Chandler Carruth34064582011-02-17 20:55:08 +00005915
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005916 // Suppress the warning if the subscript expression (as identified by the
5917 // ']' location) and the index expression are both from macro expansions
5918 // within a system header.
5919 if (ASE) {
5920 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
5921 ASE->getRBracketLoc());
5922 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
5923 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
5924 IndexExpr->getLocStart());
5925 if (SourceMgr.isFromSameFile(RBracketLoc, IndexLoc))
5926 return;
5927 }
5928 }
5929
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005930 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005931 if (ASE)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005932 DiagID = diag::warn_array_index_exceeds_bounds;
5933
5934 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
5935 PDiag(DiagID) << index.toString(10, true)
5936 << size.toString(10, true)
5937 << (unsigned)size.getLimitedValue(~0U)
5938 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00005939 } else {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005940 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005941 if (!ASE) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005942 DiagID = diag::warn_ptr_arith_precedes_bounds;
5943 if (index.isNegative()) index = -index;
5944 }
5945
5946 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
5947 PDiag(DiagID) << index.toString(10, true)
5948 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00005949 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00005950
Matt Beaumont-Gaycfbc5b52011-11-29 19:27:11 +00005951 if (!ND) {
5952 // Try harder to find a NamedDecl to point at in the note.
5953 while (const ArraySubscriptExpr *ASE =
5954 dyn_cast<ArraySubscriptExpr>(BaseExpr))
5955 BaseExpr = ASE->getBase()->IgnoreParenCasts();
5956 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
5957 ND = dyn_cast<NamedDecl>(DRE->getDecl());
5958 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
5959 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
5960 }
5961
Chandler Carruth35001ca2011-02-17 21:10:52 +00005962 if (ND)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005963 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
5964 PDiag(diag::note_array_index_out_of_bounds)
5965 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00005966}
5967
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005968void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005969 int AllowOnePastEnd = 0;
5970 while (expr) {
5971 expr = expr->IgnoreParenImpCasts();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005972 switch (expr->getStmtClass()) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005973 case Stmt::ArraySubscriptExprClass: {
5974 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005975 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005976 AllowOnePastEnd > 0);
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005977 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005978 }
5979 case Stmt::UnaryOperatorClass: {
5980 // Only unwrap the * and & unary operators
5981 const UnaryOperator *UO = cast<UnaryOperator>(expr);
5982 expr = UO->getSubExpr();
5983 switch (UO->getOpcode()) {
5984 case UO_AddrOf:
5985 AllowOnePastEnd++;
5986 break;
5987 case UO_Deref:
5988 AllowOnePastEnd--;
5989 break;
5990 default:
5991 return;
5992 }
5993 break;
5994 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005995 case Stmt::ConditionalOperatorClass: {
5996 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
5997 if (const Expr *lhs = cond->getLHS())
5998 CheckArrayAccess(lhs);
5999 if (const Expr *rhs = cond->getRHS())
6000 CheckArrayAccess(rhs);
6001 return;
6002 }
6003 default:
6004 return;
6005 }
Peter Collingbournef111d932011-04-15 00:35:48 +00006006 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006007}
John McCallf85e1932011-06-15 23:02:42 +00006008
6009//===--- CHECK: Objective-C retain cycles ----------------------------------//
6010
6011namespace {
6012 struct RetainCycleOwner {
6013 RetainCycleOwner() : Variable(0), Indirect(false) {}
6014 VarDecl *Variable;
6015 SourceRange Range;
6016 SourceLocation Loc;
6017 bool Indirect;
6018
6019 void setLocsFrom(Expr *e) {
6020 Loc = e->getExprLoc();
6021 Range = e->getSourceRange();
6022 }
6023 };
6024}
6025
6026/// Consider whether capturing the given variable can possibly lead to
6027/// a retain cycle.
6028static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledruf3477c12012-09-27 10:16:10 +00006029 // In ARC, it's captured strongly iff the variable has __strong
John McCallf85e1932011-06-15 23:02:42 +00006030 // lifetime. In MRR, it's captured strongly if the variable is
6031 // __block and has an appropriate type.
6032 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
6033 return false;
6034
6035 owner.Variable = var;
Jordan Rosee10f4d32012-09-15 02:48:31 +00006036 if (ref)
6037 owner.setLocsFrom(ref);
John McCallf85e1932011-06-15 23:02:42 +00006038 return true;
6039}
6040
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006041static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCallf85e1932011-06-15 23:02:42 +00006042 while (true) {
6043 e = e->IgnoreParens();
6044 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
6045 switch (cast->getCastKind()) {
6046 case CK_BitCast:
6047 case CK_LValueBitCast:
6048 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00006049 case CK_ARCReclaimReturnedObject:
John McCallf85e1932011-06-15 23:02:42 +00006050 e = cast->getSubExpr();
6051 continue;
6052
John McCallf85e1932011-06-15 23:02:42 +00006053 default:
6054 return false;
6055 }
6056 }
6057
6058 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
6059 ObjCIvarDecl *ivar = ref->getDecl();
6060 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
6061 return false;
6062
6063 // Try to find a retain cycle in the base.
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006064 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCallf85e1932011-06-15 23:02:42 +00006065 return false;
6066
6067 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
6068 owner.Indirect = true;
6069 return true;
6070 }
6071
6072 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
6073 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
6074 if (!var) return false;
6075 return considerVariable(var, ref, owner);
6076 }
6077
John McCallf85e1932011-06-15 23:02:42 +00006078 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
6079 if (member->isArrow()) return false;
6080
6081 // Don't count this as an indirect ownership.
6082 e = member->getBase();
6083 continue;
6084 }
6085
John McCall4b9c2d22011-11-06 09:01:30 +00006086 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
6087 // Only pay attention to pseudo-objects on property references.
6088 ObjCPropertyRefExpr *pre
6089 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
6090 ->IgnoreParens());
6091 if (!pre) return false;
6092 if (pre->isImplicitProperty()) return false;
6093 ObjCPropertyDecl *property = pre->getExplicitProperty();
6094 if (!property->isRetaining() &&
6095 !(property->getPropertyIvarDecl() &&
6096 property->getPropertyIvarDecl()->getType()
6097 .getObjCLifetime() == Qualifiers::OCL_Strong))
6098 return false;
6099
6100 owner.Indirect = true;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006101 if (pre->isSuperReceiver()) {
6102 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
6103 if (!owner.Variable)
6104 return false;
6105 owner.Loc = pre->getLocation();
6106 owner.Range = pre->getSourceRange();
6107 return true;
6108 }
John McCall4b9c2d22011-11-06 09:01:30 +00006109 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
6110 ->getSourceExpr());
6111 continue;
6112 }
6113
John McCallf85e1932011-06-15 23:02:42 +00006114 // Array ivars?
6115
6116 return false;
6117 }
6118}
6119
6120namespace {
6121 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
6122 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
6123 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
6124 Variable(variable), Capturer(0) {}
6125
6126 VarDecl *Variable;
6127 Expr *Capturer;
6128
6129 void VisitDeclRefExpr(DeclRefExpr *ref) {
6130 if (ref->getDecl() == Variable && !Capturer)
6131 Capturer = ref;
6132 }
6133
John McCallf85e1932011-06-15 23:02:42 +00006134 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
6135 if (Capturer) return;
6136 Visit(ref->getBase());
6137 if (Capturer && ref->isFreeIvar())
6138 Capturer = ref;
6139 }
6140
6141 void VisitBlockExpr(BlockExpr *block) {
6142 // Look inside nested blocks
6143 if (block->getBlockDecl()->capturesVariable(Variable))
6144 Visit(block->getBlockDecl()->getBody());
6145 }
Fariborz Jahanian7e2e4c32012-08-31 20:04:47 +00006146
6147 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
6148 if (Capturer) return;
6149 if (OVE->getSourceExpr())
6150 Visit(OVE->getSourceExpr());
6151 }
John McCallf85e1932011-06-15 23:02:42 +00006152 };
6153}
6154
6155/// Check whether the given argument is a block which captures a
6156/// variable.
6157static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
6158 assert(owner.Variable && owner.Loc.isValid());
6159
6160 e = e->IgnoreParenCasts();
Jordan Rose1fac58a2012-09-17 17:54:30 +00006161
6162 // Look through [^{...} copy] and Block_copy(^{...}).
6163 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
6164 Selector Cmd = ME->getSelector();
6165 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
6166 e = ME->getInstanceReceiver();
6167 if (!e)
6168 return 0;
6169 e = e->IgnoreParenCasts();
6170 }
6171 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
6172 if (CE->getNumArgs() == 1) {
6173 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekd13eff62012-10-02 04:36:54 +00006174 if (Fn) {
6175 const IdentifierInfo *FnI = Fn->getIdentifier();
6176 if (FnI && FnI->isStr("_Block_copy")) {
6177 e = CE->getArg(0)->IgnoreParenCasts();
6178 }
6179 }
Jordan Rose1fac58a2012-09-17 17:54:30 +00006180 }
6181 }
6182
John McCallf85e1932011-06-15 23:02:42 +00006183 BlockExpr *block = dyn_cast<BlockExpr>(e);
6184 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
6185 return 0;
6186
6187 FindCaptureVisitor visitor(S.Context, owner.Variable);
6188 visitor.Visit(block->getBlockDecl()->getBody());
6189 return visitor.Capturer;
6190}
6191
6192static void diagnoseRetainCycle(Sema &S, Expr *capturer,
6193 RetainCycleOwner &owner) {
6194 assert(capturer);
6195 assert(owner.Variable && owner.Loc.isValid());
6196
6197 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
6198 << owner.Variable << capturer->getSourceRange();
6199 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
6200 << owner.Indirect << owner.Range;
6201}
6202
6203/// Check for a keyword selector that starts with the word 'add' or
6204/// 'set'.
6205static bool isSetterLikeSelector(Selector sel) {
6206 if (sel.isUnarySelector()) return false;
6207
Chris Lattner5f9e2722011-07-23 10:55:15 +00006208 StringRef str = sel.getNameForSlot(0);
John McCallf85e1932011-06-15 23:02:42 +00006209 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00006210 if (str.startswith("set"))
John McCallf85e1932011-06-15 23:02:42 +00006211 str = str.substr(3);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00006212 else if (str.startswith("add")) {
6213 // Specially whitelist 'addOperationWithBlock:'.
6214 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
6215 return false;
6216 str = str.substr(3);
6217 }
John McCallf85e1932011-06-15 23:02:42 +00006218 else
6219 return false;
6220
6221 if (str.empty()) return true;
Jordan Rose3f6f51e2013-02-08 22:30:41 +00006222 return !isLowercase(str.front());
John McCallf85e1932011-06-15 23:02:42 +00006223}
6224
6225/// Check a message send to see if it's likely to cause a retain cycle.
6226void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
6227 // Only check instance methods whose selector looks like a setter.
6228 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
6229 return;
6230
6231 // Try to find a variable that the receiver is strongly owned by.
6232 RetainCycleOwner owner;
6233 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006234 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCallf85e1932011-06-15 23:02:42 +00006235 return;
6236 } else {
6237 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
6238 owner.Variable = getCurMethodDecl()->getSelfDecl();
6239 owner.Loc = msg->getSuperLoc();
6240 owner.Range = msg->getSuperLoc();
6241 }
6242
6243 // Check whether the receiver is captured by any of the arguments.
6244 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
6245 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
6246 return diagnoseRetainCycle(*this, capturer, owner);
6247}
6248
6249/// Check a property assign to see if it's likely to cause a retain cycle.
6250void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
6251 RetainCycleOwner owner;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006252 if (!findRetainCycleOwner(*this, receiver, owner))
John McCallf85e1932011-06-15 23:02:42 +00006253 return;
6254
6255 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
6256 diagnoseRetainCycle(*this, capturer, owner);
6257}
6258
Jordan Rosee10f4d32012-09-15 02:48:31 +00006259void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
6260 RetainCycleOwner Owner;
6261 if (!considerVariable(Var, /*DeclRefExpr=*/0, Owner))
6262 return;
6263
6264 // Because we don't have an expression for the variable, we have to set the
6265 // location explicitly here.
6266 Owner.Loc = Var->getLocation();
6267 Owner.Range = Var->getSourceRange();
6268
6269 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
6270 diagnoseRetainCycle(*this, Capturer, Owner);
6271}
6272
Ted Kremenek9d084012012-12-21 08:04:28 +00006273static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
6274 Expr *RHS, bool isProperty) {
6275 // Check if RHS is an Objective-C object literal, which also can get
6276 // immediately zapped in a weak reference. Note that we explicitly
6277 // allow ObjCStringLiterals, since those are designed to never really die.
6278 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenekf530ff72012-12-21 21:59:39 +00006279
Ted Kremenekd3292c82012-12-21 22:46:35 +00006280 // This enum needs to match with the 'select' in
6281 // warn_objc_arc_literal_assign (off-by-1).
6282 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
6283 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
6284 return false;
Ted Kremenekf530ff72012-12-21 21:59:39 +00006285
6286 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenekd3292c82012-12-21 22:46:35 +00006287 << (unsigned) Kind
Ted Kremenek9d084012012-12-21 08:04:28 +00006288 << (isProperty ? 0 : 1)
6289 << RHS->getSourceRange();
Ted Kremenekf530ff72012-12-21 21:59:39 +00006290
6291 return true;
Ted Kremenek9d084012012-12-21 08:04:28 +00006292}
6293
Ted Kremenekb29b30f2012-12-21 19:45:30 +00006294static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
6295 Qualifiers::ObjCLifetime LT,
6296 Expr *RHS, bool isProperty) {
6297 // Strip off any implicit cast added to get to the one ARC-specific.
6298 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
6299 if (cast->getCastKind() == CK_ARCConsumeObject) {
6300 S.Diag(Loc, diag::warn_arc_retained_assign)
6301 << (LT == Qualifiers::OCL_ExplicitNone)
6302 << (isProperty ? 0 : 1)
6303 << RHS->getSourceRange();
6304 return true;
6305 }
6306 RHS = cast->getSubExpr();
6307 }
6308
6309 if (LT == Qualifiers::OCL_Weak &&
6310 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
6311 return true;
6312
6313 return false;
6314}
6315
Ted Kremenekb1ea5102012-12-21 08:04:20 +00006316bool Sema::checkUnsafeAssigns(SourceLocation Loc,
6317 QualType LHS, Expr *RHS) {
6318 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
6319
6320 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
6321 return false;
6322
6323 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
6324 return true;
6325
6326 return false;
6327}
6328
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006329void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
6330 Expr *LHS, Expr *RHS) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006331 QualType LHSType;
6332 // PropertyRef on LHS type need be directly obtained from
6333 // its declaration as it has a PsuedoType.
6334 ObjCPropertyRefExpr *PRE
6335 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
6336 if (PRE && !PRE->isImplicitProperty()) {
6337 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
6338 if (PD)
6339 LHSType = PD->getType();
6340 }
6341
6342 if (LHSType.isNull())
6343 LHSType = LHS->getType();
Jordan Rose7a270482012-09-28 22:21:35 +00006344
6345 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
6346
6347 if (LT == Qualifiers::OCL_Weak) {
6348 DiagnosticsEngine::Level Level =
6349 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
6350 if (Level != DiagnosticsEngine::Ignored)
6351 getCurFunction()->markSafeWeakUse(LHS);
6352 }
6353
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006354 if (checkUnsafeAssigns(Loc, LHSType, RHS))
6355 return;
Jordan Rose7a270482012-09-28 22:21:35 +00006356
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006357 // FIXME. Check for other life times.
6358 if (LT != Qualifiers::OCL_None)
6359 return;
6360
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006361 if (PRE) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006362 if (PRE->isImplicitProperty())
6363 return;
6364 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
6365 if (!PD)
6366 return;
6367
Bill Wendlingad017fa2012-12-20 19:22:21 +00006368 unsigned Attributes = PD->getPropertyAttributes();
6369 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006370 // when 'assign' attribute was not explicitly specified
6371 // by user, ignore it and rely on property type itself
6372 // for lifetime info.
6373 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
6374 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
6375 LHSType->isObjCRetainableType())
6376 return;
6377
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006378 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00006379 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006380 Diag(Loc, diag::warn_arc_retained_property_assign)
6381 << RHS->getSourceRange();
6382 return;
6383 }
6384 RHS = cast->getSubExpr();
6385 }
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006386 }
Bill Wendlingad017fa2012-12-20 19:22:21 +00006387 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb1ea5102012-12-21 08:04:20 +00006388 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
6389 return;
Fariborz Jahanianbd2e27e2012-07-06 21:09:27 +00006390 }
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006391 }
6392}
Dmitri Gribenko625bb562012-02-14 22:14:32 +00006393
6394//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
6395
6396namespace {
6397bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
6398 SourceLocation StmtLoc,
6399 const NullStmt *Body) {
6400 // Do not warn if the body is a macro that expands to nothing, e.g:
6401 //
6402 // #define CALL(x)
6403 // if (condition)
6404 // CALL(0);
6405 //
6406 if (Body->hasLeadingEmptyMacro())
6407 return false;
6408
6409 // Get line numbers of statement and body.
6410 bool StmtLineInvalid;
6411 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
6412 &StmtLineInvalid);
6413 if (StmtLineInvalid)
6414 return false;
6415
6416 bool BodyLineInvalid;
6417 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
6418 &BodyLineInvalid);
6419 if (BodyLineInvalid)
6420 return false;
6421
6422 // Warn if null statement and body are on the same line.
6423 if (StmtLine != BodyLine)
6424 return false;
6425
6426 return true;
6427}
6428} // Unnamed namespace
6429
6430void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
6431 const Stmt *Body,
6432 unsigned DiagID) {
6433 // Since this is a syntactic check, don't emit diagnostic for template
6434 // instantiations, this just adds noise.
6435 if (CurrentInstantiationScope)
6436 return;
6437
6438 // The body should be a null statement.
6439 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
6440 if (!NBody)
6441 return;
6442
6443 // Do the usual checks.
6444 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
6445 return;
6446
6447 Diag(NBody->getSemiLoc(), DiagID);
6448 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
6449}
6450
6451void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
6452 const Stmt *PossibleBody) {
6453 assert(!CurrentInstantiationScope); // Ensured by caller
6454
6455 SourceLocation StmtLoc;
6456 const Stmt *Body;
6457 unsigned DiagID;
6458 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
6459 StmtLoc = FS->getRParenLoc();
6460 Body = FS->getBody();
6461 DiagID = diag::warn_empty_for_body;
6462 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
6463 StmtLoc = WS->getCond()->getSourceRange().getEnd();
6464 Body = WS->getBody();
6465 DiagID = diag::warn_empty_while_body;
6466 } else
6467 return; // Neither `for' nor `while'.
6468
6469 // The body should be a null statement.
6470 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
6471 if (!NBody)
6472 return;
6473
6474 // Skip expensive checks if diagnostic is disabled.
6475 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
6476 DiagnosticsEngine::Ignored)
6477 return;
6478
6479 // Do the usual checks.
6480 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
6481 return;
6482
6483 // `for(...);' and `while(...);' are popular idioms, so in order to keep
6484 // noise level low, emit diagnostics only if for/while is followed by a
6485 // CompoundStmt, e.g.:
6486 // for (int i = 0; i < n; i++);
6487 // {
6488 // a(i);
6489 // }
6490 // or if for/while is followed by a statement with more indentation
6491 // than for/while itself:
6492 // for (int i = 0; i < n; i++);
6493 // a(i);
6494 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
6495 if (!ProbableTypo) {
6496 bool BodyColInvalid;
6497 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
6498 PossibleBody->getLocStart(),
6499 &BodyColInvalid);
6500 if (BodyColInvalid)
6501 return;
6502
6503 bool StmtColInvalid;
6504 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
6505 S->getLocStart(),
6506 &StmtColInvalid);
6507 if (StmtColInvalid)
6508 return;
6509
6510 if (BodyCol > StmtCol)
6511 ProbableTypo = true;
6512 }
6513
6514 if (ProbableTypo) {
6515 Diag(NBody->getSemiLoc(), DiagID);
6516 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
6517 }
6518}
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00006519
6520//===--- Layout compatibility ----------------------------------------------//
6521
6522namespace {
6523
6524bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
6525
6526/// \brief Check if two enumeration types are layout-compatible.
6527bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
6528 // C++11 [dcl.enum] p8:
6529 // Two enumeration types are layout-compatible if they have the same
6530 // underlying type.
6531 return ED1->isComplete() && ED2->isComplete() &&
6532 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
6533}
6534
6535/// \brief Check if two fields are layout-compatible.
6536bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
6537 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
6538 return false;
6539
6540 if (Field1->isBitField() != Field2->isBitField())
6541 return false;
6542
6543 if (Field1->isBitField()) {
6544 // Make sure that the bit-fields are the same length.
6545 unsigned Bits1 = Field1->getBitWidthValue(C);
6546 unsigned Bits2 = Field2->getBitWidthValue(C);
6547
6548 if (Bits1 != Bits2)
6549 return false;
6550 }
6551
6552 return true;
6553}
6554
6555/// \brief Check if two standard-layout structs are layout-compatible.
6556/// (C++11 [class.mem] p17)
6557bool isLayoutCompatibleStruct(ASTContext &C,
6558 RecordDecl *RD1,
6559 RecordDecl *RD2) {
6560 // If both records are C++ classes, check that base classes match.
6561 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
6562 // If one of records is a CXXRecordDecl we are in C++ mode,
6563 // thus the other one is a CXXRecordDecl, too.
6564 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
6565 // Check number of base classes.
6566 if (D1CXX->getNumBases() != D2CXX->getNumBases())
6567 return false;
6568
6569 // Check the base classes.
6570 for (CXXRecordDecl::base_class_const_iterator
6571 Base1 = D1CXX->bases_begin(),
6572 BaseEnd1 = D1CXX->bases_end(),
6573 Base2 = D2CXX->bases_begin();
6574 Base1 != BaseEnd1;
6575 ++Base1, ++Base2) {
6576 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
6577 return false;
6578 }
6579 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
6580 // If only RD2 is a C++ class, it should have zero base classes.
6581 if (D2CXX->getNumBases() > 0)
6582 return false;
6583 }
6584
6585 // Check the fields.
6586 RecordDecl::field_iterator Field2 = RD2->field_begin(),
6587 Field2End = RD2->field_end(),
6588 Field1 = RD1->field_begin(),
6589 Field1End = RD1->field_end();
6590 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
6591 if (!isLayoutCompatible(C, *Field1, *Field2))
6592 return false;
6593 }
6594 if (Field1 != Field1End || Field2 != Field2End)
6595 return false;
6596
6597 return true;
6598}
6599
6600/// \brief Check if two standard-layout unions are layout-compatible.
6601/// (C++11 [class.mem] p18)
6602bool isLayoutCompatibleUnion(ASTContext &C,
6603 RecordDecl *RD1,
6604 RecordDecl *RD2) {
6605 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
6606 for (RecordDecl::field_iterator Field2 = RD2->field_begin(),
6607 Field2End = RD2->field_end();
6608 Field2 != Field2End; ++Field2) {
6609 UnmatchedFields.insert(*Field2);
6610 }
6611
6612 for (RecordDecl::field_iterator Field1 = RD1->field_begin(),
6613 Field1End = RD1->field_end();
6614 Field1 != Field1End; ++Field1) {
6615 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
6616 I = UnmatchedFields.begin(),
6617 E = UnmatchedFields.end();
6618
6619 for ( ; I != E; ++I) {
6620 if (isLayoutCompatible(C, *Field1, *I)) {
6621 bool Result = UnmatchedFields.erase(*I);
6622 (void) Result;
6623 assert(Result);
6624 break;
6625 }
6626 }
6627 if (I == E)
6628 return false;
6629 }
6630
6631 return UnmatchedFields.empty();
6632}
6633
6634bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
6635 if (RD1->isUnion() != RD2->isUnion())
6636 return false;
6637
6638 if (RD1->isUnion())
6639 return isLayoutCompatibleUnion(C, RD1, RD2);
6640 else
6641 return isLayoutCompatibleStruct(C, RD1, RD2);
6642}
6643
6644/// \brief Check if two types are layout-compatible in C++11 sense.
6645bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
6646 if (T1.isNull() || T2.isNull())
6647 return false;
6648
6649 // C++11 [basic.types] p11:
6650 // If two types T1 and T2 are the same type, then T1 and T2 are
6651 // layout-compatible types.
6652 if (C.hasSameType(T1, T2))
6653 return true;
6654
6655 T1 = T1.getCanonicalType().getUnqualifiedType();
6656 T2 = T2.getCanonicalType().getUnqualifiedType();
6657
6658 const Type::TypeClass TC1 = T1->getTypeClass();
6659 const Type::TypeClass TC2 = T2->getTypeClass();
6660
6661 if (TC1 != TC2)
6662 return false;
6663
6664 if (TC1 == Type::Enum) {
6665 return isLayoutCompatible(C,
6666 cast<EnumType>(T1)->getDecl(),
6667 cast<EnumType>(T2)->getDecl());
6668 } else if (TC1 == Type::Record) {
6669 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
6670 return false;
6671
6672 return isLayoutCompatible(C,
6673 cast<RecordType>(T1)->getDecl(),
6674 cast<RecordType>(T2)->getDecl());
6675 }
6676
6677 return false;
6678}
6679}
6680
6681//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
6682
6683namespace {
6684/// \brief Given a type tag expression find the type tag itself.
6685///
6686/// \param TypeExpr Type tag expression, as it appears in user's code.
6687///
6688/// \param VD Declaration of an identifier that appears in a type tag.
6689///
6690/// \param MagicValue Type tag magic value.
6691bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
6692 const ValueDecl **VD, uint64_t *MagicValue) {
6693 while(true) {
6694 if (!TypeExpr)
6695 return false;
6696
6697 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
6698
6699 switch (TypeExpr->getStmtClass()) {
6700 case Stmt::UnaryOperatorClass: {
6701 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
6702 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
6703 TypeExpr = UO->getSubExpr();
6704 continue;
6705 }
6706 return false;
6707 }
6708
6709 case Stmt::DeclRefExprClass: {
6710 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
6711 *VD = DRE->getDecl();
6712 return true;
6713 }
6714
6715 case Stmt::IntegerLiteralClass: {
6716 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
6717 llvm::APInt MagicValueAPInt = IL->getValue();
6718 if (MagicValueAPInt.getActiveBits() <= 64) {
6719 *MagicValue = MagicValueAPInt.getZExtValue();
6720 return true;
6721 } else
6722 return false;
6723 }
6724
6725 case Stmt::BinaryConditionalOperatorClass:
6726 case Stmt::ConditionalOperatorClass: {
6727 const AbstractConditionalOperator *ACO =
6728 cast<AbstractConditionalOperator>(TypeExpr);
6729 bool Result;
6730 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
6731 if (Result)
6732 TypeExpr = ACO->getTrueExpr();
6733 else
6734 TypeExpr = ACO->getFalseExpr();
6735 continue;
6736 }
6737 return false;
6738 }
6739
6740 case Stmt::BinaryOperatorClass: {
6741 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
6742 if (BO->getOpcode() == BO_Comma) {
6743 TypeExpr = BO->getRHS();
6744 continue;
6745 }
6746 return false;
6747 }
6748
6749 default:
6750 return false;
6751 }
6752 }
6753}
6754
6755/// \brief Retrieve the C type corresponding to type tag TypeExpr.
6756///
6757/// \param TypeExpr Expression that specifies a type tag.
6758///
6759/// \param MagicValues Registered magic values.
6760///
6761/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
6762/// kind.
6763///
6764/// \param TypeInfo Information about the corresponding C type.
6765///
6766/// \returns true if the corresponding C type was found.
6767bool GetMatchingCType(
6768 const IdentifierInfo *ArgumentKind,
6769 const Expr *TypeExpr, const ASTContext &Ctx,
6770 const llvm::DenseMap<Sema::TypeTagMagicValue,
6771 Sema::TypeTagData> *MagicValues,
6772 bool &FoundWrongKind,
6773 Sema::TypeTagData &TypeInfo) {
6774 FoundWrongKind = false;
6775
6776 // Variable declaration that has type_tag_for_datatype attribute.
6777 const ValueDecl *VD = NULL;
6778
6779 uint64_t MagicValue;
6780
6781 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
6782 return false;
6783
6784 if (VD) {
6785 for (specific_attr_iterator<TypeTagForDatatypeAttr>
6786 I = VD->specific_attr_begin<TypeTagForDatatypeAttr>(),
6787 E = VD->specific_attr_end<TypeTagForDatatypeAttr>();
6788 I != E; ++I) {
6789 if (I->getArgumentKind() != ArgumentKind) {
6790 FoundWrongKind = true;
6791 return false;
6792 }
6793 TypeInfo.Type = I->getMatchingCType();
6794 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
6795 TypeInfo.MustBeNull = I->getMustBeNull();
6796 return true;
6797 }
6798 return false;
6799 }
6800
6801 if (!MagicValues)
6802 return false;
6803
6804 llvm::DenseMap<Sema::TypeTagMagicValue,
6805 Sema::TypeTagData>::const_iterator I =
6806 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
6807 if (I == MagicValues->end())
6808 return false;
6809
6810 TypeInfo = I->second;
6811 return true;
6812}
6813} // unnamed namespace
6814
6815void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
6816 uint64_t MagicValue, QualType Type,
6817 bool LayoutCompatible,
6818 bool MustBeNull) {
6819 if (!TypeTagForDatatypeMagicValues)
6820 TypeTagForDatatypeMagicValues.reset(
6821 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
6822
6823 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
6824 (*TypeTagForDatatypeMagicValues)[Magic] =
6825 TypeTagData(Type, LayoutCompatible, MustBeNull);
6826}
6827
6828namespace {
6829bool IsSameCharType(QualType T1, QualType T2) {
6830 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
6831 if (!BT1)
6832 return false;
6833
6834 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
6835 if (!BT2)
6836 return false;
6837
6838 BuiltinType::Kind T1Kind = BT1->getKind();
6839 BuiltinType::Kind T2Kind = BT2->getKind();
6840
6841 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
6842 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
6843 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
6844 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
6845}
6846} // unnamed namespace
6847
6848void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
6849 const Expr * const *ExprArgs) {
6850 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
6851 bool IsPointerAttr = Attr->getIsPointer();
6852
6853 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
6854 bool FoundWrongKind;
6855 TypeTagData TypeInfo;
6856 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
6857 TypeTagForDatatypeMagicValues.get(),
6858 FoundWrongKind, TypeInfo)) {
6859 if (FoundWrongKind)
6860 Diag(TypeTagExpr->getExprLoc(),
6861 diag::warn_type_tag_for_datatype_wrong_kind)
6862 << TypeTagExpr->getSourceRange();
6863 return;
6864 }
6865
6866 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
6867 if (IsPointerAttr) {
6868 // Skip implicit cast of pointer to `void *' (as a function argument).
6869 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5a249802012-11-03 16:07:49 +00006870 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkob57ce4e2012-11-03 22:10:18 +00006871 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00006872 ArgumentExpr = ICE->getSubExpr();
6873 }
6874 QualType ArgumentType = ArgumentExpr->getType();
6875
6876 // Passing a `void*' pointer shouldn't trigger a warning.
6877 if (IsPointerAttr && ArgumentType->isVoidPointerType())
6878 return;
6879
6880 if (TypeInfo.MustBeNull) {
6881 // Type tag with matching void type requires a null pointer.
6882 if (!ArgumentExpr->isNullPointerConstant(Context,
6883 Expr::NPC_ValueDependentIsNotNull)) {
6884 Diag(ArgumentExpr->getExprLoc(),
6885 diag::warn_type_safety_null_pointer_required)
6886 << ArgumentKind->getName()
6887 << ArgumentExpr->getSourceRange()
6888 << TypeTagExpr->getSourceRange();
6889 }
6890 return;
6891 }
6892
6893 QualType RequiredType = TypeInfo.Type;
6894 if (IsPointerAttr)
6895 RequiredType = Context.getPointerType(RequiredType);
6896
6897 bool mismatch = false;
6898 if (!TypeInfo.LayoutCompatible) {
6899 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
6900
6901 // C++11 [basic.fundamental] p1:
6902 // Plain char, signed char, and unsigned char are three distinct types.
6903 //
6904 // But we treat plain `char' as equivalent to `signed char' or `unsigned
6905 // char' depending on the current char signedness mode.
6906 if (mismatch)
6907 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
6908 RequiredType->getPointeeType())) ||
6909 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
6910 mismatch = false;
6911 } else
6912 if (IsPointerAttr)
6913 mismatch = !isLayoutCompatible(Context,
6914 ArgumentType->getPointeeType(),
6915 RequiredType->getPointeeType());
6916 else
6917 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
6918
6919 if (mismatch)
6920 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
6921 << ArgumentType << ArgumentKind->getName()
6922 << TypeInfo.LayoutCompatible << RequiredType
6923 << ArgumentExpr->getSourceRange()
6924 << TypeTagExpr->getSourceRange();
6925}