blob: a6294e5764e8b68b0c6d99db5a95d0a6901adc2f [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,
589 Expr **Args, unsigned NumArgs) {
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 Gribenko1c030e92013-01-13 20:46:02 +0000593 checkCall(Method, llvm::makeArrayRef<const Expr *>(Args, NumArgs),
594 Method->param_size(),
Richard Smith831421f2012-06-25 20:30:08 +0000595 /*IsMemberFunction=*/false,
596 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000597
598 return false;
599}
600
Richard Smith831421f2012-06-25 20:30:08 +0000601bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall,
602 const FunctionProtoType *Proto) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000603 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
604 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000605 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000606
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000607 QualType Ty = V->getType();
608 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000609 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000610
Richard Smith831421f2012-06-25 20:30:08 +0000611 VariadicCallType CallType =
612 Proto && Proto->isVariadic() ? VariadicBlock : VariadicDoesNotApply ;
613 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
Anders Carlssond406bf02009-08-16 01:56:34 +0000614
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000615 checkCall(NDecl,
616 llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
617 TheCall->getNumArgs()),
Richard Smith831421f2012-06-25 20:30:08 +0000618 NumProtoArgs, /*IsMemberFunction=*/false,
619 TheCall->getRParenLoc(),
620 TheCall->getCallee()->getSourceRange(), CallType);
621
Anders Carlssond406bf02009-08-16 01:56:34 +0000622 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000623}
624
Richard Smithff34d402012-04-12 05:08:17 +0000625ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
626 AtomicExpr::AtomicOp Op) {
Eli Friedman276b0612011-10-11 02:20:01 +0000627 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
628 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedman276b0612011-10-11 02:20:01 +0000629
Richard Smithff34d402012-04-12 05:08:17 +0000630 // All these operations take one of the following forms:
631 enum {
632 // C __c11_atomic_init(A *, C)
633 Init,
634 // C __c11_atomic_load(A *, int)
635 Load,
636 // void __atomic_load(A *, CP, int)
637 Copy,
638 // C __c11_atomic_add(A *, M, int)
639 Arithmetic,
640 // C __atomic_exchange_n(A *, CP, int)
641 Xchg,
642 // void __atomic_exchange(A *, C *, CP, int)
643 GNUXchg,
644 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
645 C11CmpXchg,
646 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
647 GNUCmpXchg
648 } Form = Init;
649 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
650 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
651 // where:
652 // C is an appropriate type,
653 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
654 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
655 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
656 // the int parameters are for orderings.
Eli Friedman276b0612011-10-11 02:20:01 +0000657
Richard Smithff34d402012-04-12 05:08:17 +0000658 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
659 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
660 && "need to update code for modified C11 atomics");
661 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
662 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
663 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
664 Op == AtomicExpr::AO__atomic_store_n ||
665 Op == AtomicExpr::AO__atomic_exchange_n ||
666 Op == AtomicExpr::AO__atomic_compare_exchange_n;
667 bool IsAddSub = false;
668
669 switch (Op) {
670 case AtomicExpr::AO__c11_atomic_init:
671 Form = Init;
672 break;
673
674 case AtomicExpr::AO__c11_atomic_load:
675 case AtomicExpr::AO__atomic_load_n:
676 Form = Load;
677 break;
678
679 case AtomicExpr::AO__c11_atomic_store:
680 case AtomicExpr::AO__atomic_load:
681 case AtomicExpr::AO__atomic_store:
682 case AtomicExpr::AO__atomic_store_n:
683 Form = Copy;
684 break;
685
686 case AtomicExpr::AO__c11_atomic_fetch_add:
687 case AtomicExpr::AO__c11_atomic_fetch_sub:
688 case AtomicExpr::AO__atomic_fetch_add:
689 case AtomicExpr::AO__atomic_fetch_sub:
690 case AtomicExpr::AO__atomic_add_fetch:
691 case AtomicExpr::AO__atomic_sub_fetch:
692 IsAddSub = true;
693 // Fall through.
694 case AtomicExpr::AO__c11_atomic_fetch_and:
695 case AtomicExpr::AO__c11_atomic_fetch_or:
696 case AtomicExpr::AO__c11_atomic_fetch_xor:
697 case AtomicExpr::AO__atomic_fetch_and:
698 case AtomicExpr::AO__atomic_fetch_or:
699 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smith51b92402012-04-13 06:31:38 +0000700 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithff34d402012-04-12 05:08:17 +0000701 case AtomicExpr::AO__atomic_and_fetch:
702 case AtomicExpr::AO__atomic_or_fetch:
703 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smith51b92402012-04-13 06:31:38 +0000704 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithff34d402012-04-12 05:08:17 +0000705 Form = Arithmetic;
706 break;
707
708 case AtomicExpr::AO__c11_atomic_exchange:
709 case AtomicExpr::AO__atomic_exchange_n:
710 Form = Xchg;
711 break;
712
713 case AtomicExpr::AO__atomic_exchange:
714 Form = GNUXchg;
715 break;
716
717 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
718 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
719 Form = C11CmpXchg;
720 break;
721
722 case AtomicExpr::AO__atomic_compare_exchange:
723 case AtomicExpr::AO__atomic_compare_exchange_n:
724 Form = GNUCmpXchg;
725 break;
726 }
727
728 // Check we have the right number of arguments.
729 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedman276b0612011-10-11 02:20:01 +0000730 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithff34d402012-04-12 05:08:17 +0000731 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +0000732 << TheCall->getCallee()->getSourceRange();
733 return ExprError();
Richard Smithff34d402012-04-12 05:08:17 +0000734 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
735 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedman276b0612011-10-11 02:20:01 +0000736 diag::err_typecheck_call_too_many_args)
Richard Smithff34d402012-04-12 05:08:17 +0000737 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +0000738 << TheCall->getCallee()->getSourceRange();
739 return ExprError();
740 }
741
Richard Smithff34d402012-04-12 05:08:17 +0000742 // Inspect the first argument of the atomic operation.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000743 Expr *Ptr = TheCall->getArg(0);
Eli Friedman276b0612011-10-11 02:20:01 +0000744 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
745 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
746 if (!pointerType) {
Richard Smithff34d402012-04-12 05:08:17 +0000747 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedman276b0612011-10-11 02:20:01 +0000748 << Ptr->getType() << Ptr->getSourceRange();
749 return ExprError();
750 }
751
Richard Smithff34d402012-04-12 05:08:17 +0000752 // For a __c11 builtin, this should be a pointer to an _Atomic type.
753 QualType AtomTy = pointerType->getPointeeType(); // 'A'
754 QualType ValType = AtomTy; // 'C'
755 if (IsC11) {
756 if (!AtomTy->isAtomicType()) {
757 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
758 << Ptr->getType() << Ptr->getSourceRange();
759 return ExprError();
760 }
Richard Smithbc57b102012-09-15 06:09:58 +0000761 if (AtomTy.isConstQualified()) {
762 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
763 << Ptr->getType() << Ptr->getSourceRange();
764 return ExprError();
765 }
Richard Smithff34d402012-04-12 05:08:17 +0000766 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedman276b0612011-10-11 02:20:01 +0000767 }
Eli Friedman276b0612011-10-11 02:20:01 +0000768
Richard Smithff34d402012-04-12 05:08:17 +0000769 // For an arithmetic operation, the implied arithmetic must be well-formed.
770 if (Form == Arithmetic) {
771 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
772 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
773 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
774 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
775 return ExprError();
776 }
777 if (!IsAddSub && !ValType->isIntegerType()) {
778 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
779 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
780 return ExprError();
781 }
782 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
783 // For __atomic_*_n operations, the value type must be a scalar integral or
784 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedman276b0612011-10-11 02:20:01 +0000785 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithff34d402012-04-12 05:08:17 +0000786 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
787 return ExprError();
788 }
789
790 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context)) {
791 // For GNU atomics, require a trivially-copyable type. This is not part of
792 // the GNU atomics specification, but we enforce it for sanity.
793 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedman276b0612011-10-11 02:20:01 +0000794 << Ptr->getType() << Ptr->getSourceRange();
795 return ExprError();
796 }
797
Richard Smithff34d402012-04-12 05:08:17 +0000798 // FIXME: For any builtin other than a load, the ValType must not be
799 // const-qualified.
Eli Friedman276b0612011-10-11 02:20:01 +0000800
801 switch (ValType.getObjCLifetime()) {
802 case Qualifiers::OCL_None:
803 case Qualifiers::OCL_ExplicitNone:
804 // okay
805 break;
806
807 case Qualifiers::OCL_Weak:
808 case Qualifiers::OCL_Strong:
809 case Qualifiers::OCL_Autoreleasing:
Richard Smithff34d402012-04-12 05:08:17 +0000810 // FIXME: Can this happen? By this point, ValType should be known
811 // to be trivially copyable.
Eli Friedman276b0612011-10-11 02:20:01 +0000812 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
813 << ValType << Ptr->getSourceRange();
814 return ExprError();
815 }
816
817 QualType ResultType = ValType;
Richard Smithff34d402012-04-12 05:08:17 +0000818 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedman276b0612011-10-11 02:20:01 +0000819 ResultType = Context.VoidTy;
Richard Smithff34d402012-04-12 05:08:17 +0000820 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedman276b0612011-10-11 02:20:01 +0000821 ResultType = Context.BoolTy;
822
Richard Smithff34d402012-04-12 05:08:17 +0000823 // The type of a parameter passed 'by value'. In the GNU atomics, such
824 // arguments are actually passed as pointers.
825 QualType ByValType = ValType; // 'CP'
826 if (!IsC11 && !IsN)
827 ByValType = Ptr->getType();
828
Eli Friedman276b0612011-10-11 02:20:01 +0000829 // The first argument --- the pointer --- has a fixed type; we
830 // deduce the types of the rest of the arguments accordingly. Walk
831 // the remaining arguments, converting them to the deduced value type.
Richard Smithff34d402012-04-12 05:08:17 +0000832 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedman276b0612011-10-11 02:20:01 +0000833 QualType Ty;
Richard Smithff34d402012-04-12 05:08:17 +0000834 if (i < NumVals[Form] + 1) {
835 switch (i) {
836 case 1:
837 // The second argument is the non-atomic operand. For arithmetic, this
838 // is always passed by value, and for a compare_exchange it is always
839 // passed by address. For the rest, GNU uses by-address and C11 uses
840 // by-value.
841 assert(Form != Load);
842 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
843 Ty = ValType;
844 else if (Form == Copy || Form == Xchg)
845 Ty = ByValType;
846 else if (Form == Arithmetic)
847 Ty = Context.getPointerDiffType();
848 else
849 Ty = Context.getPointerType(ValType.getUnqualifiedType());
850 break;
851 case 2:
852 // The third argument to compare_exchange / GNU exchange is a
853 // (pointer to a) desired value.
854 Ty = ByValType;
855 break;
856 case 3:
857 // The fourth argument to GNU compare_exchange is a 'weak' flag.
858 Ty = Context.BoolTy;
859 break;
860 }
Eli Friedman276b0612011-10-11 02:20:01 +0000861 } else {
862 // The order(s) are always converted to int.
863 Ty = Context.IntTy;
864 }
Richard Smithff34d402012-04-12 05:08:17 +0000865
Eli Friedman276b0612011-10-11 02:20:01 +0000866 InitializedEntity Entity =
867 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithff34d402012-04-12 05:08:17 +0000868 ExprResult Arg = TheCall->getArg(i);
Eli Friedman276b0612011-10-11 02:20:01 +0000869 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
870 if (Arg.isInvalid())
871 return true;
872 TheCall->setArg(i, Arg.get());
873 }
874
Richard Smithff34d402012-04-12 05:08:17 +0000875 // Permute the arguments into a 'consistent' order.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000876 SmallVector<Expr*, 5> SubExprs;
877 SubExprs.push_back(Ptr);
Richard Smithff34d402012-04-12 05:08:17 +0000878 switch (Form) {
879 case Init:
880 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnall7a7ee302012-01-16 17:27:18 +0000881 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +0000882 break;
883 case Load:
884 SubExprs.push_back(TheCall->getArg(1)); // Order
885 break;
886 case Copy:
887 case Arithmetic:
888 case Xchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000889 SubExprs.push_back(TheCall->getArg(2)); // Order
890 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +0000891 break;
892 case GNUXchg:
893 // Note, AtomicExpr::getVal2() has a special case for this atomic.
894 SubExprs.push_back(TheCall->getArg(3)); // Order
895 SubExprs.push_back(TheCall->getArg(1)); // Val1
896 SubExprs.push_back(TheCall->getArg(2)); // Val2
897 break;
898 case C11CmpXchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000899 SubExprs.push_back(TheCall->getArg(3)); // Order
900 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000901 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall2ebb98a2012-03-29 17:58:59 +0000902 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithff34d402012-04-12 05:08:17 +0000903 break;
904 case GNUCmpXchg:
905 SubExprs.push_back(TheCall->getArg(4)); // Order
906 SubExprs.push_back(TheCall->getArg(1)); // Val1
907 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
908 SubExprs.push_back(TheCall->getArg(2)); // Val2
909 SubExprs.push_back(TheCall->getArg(3)); // Weak
910 break;
Eli Friedman276b0612011-10-11 02:20:01 +0000911 }
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000912
913 return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +0000914 SubExprs, ResultType, Op,
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000915 TheCall->getRParenLoc()));
Eli Friedman276b0612011-10-11 02:20:01 +0000916}
917
918
John McCall5f8d6042011-08-27 01:09:30 +0000919/// checkBuiltinArgument - Given a call to a builtin function, perform
920/// normal type-checking on the given argument, updating the call in
921/// place. This is useful when a builtin function requires custom
922/// type-checking for some of its arguments but not necessarily all of
923/// them.
924///
925/// Returns true on error.
926static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
927 FunctionDecl *Fn = E->getDirectCallee();
928 assert(Fn && "builtin call without direct callee!");
929
930 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
931 InitializedEntity Entity =
932 InitializedEntity::InitializeParameter(S.Context, Param);
933
934 ExprResult Arg = E->getArg(0);
935 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
936 if (Arg.isInvalid())
937 return true;
938
939 E->setArg(ArgIndex, Arg.take());
940 return false;
941}
942
Chris Lattner5caa3702009-05-08 06:58:22 +0000943/// SemaBuiltinAtomicOverloaded - We have a call to a function like
944/// __sync_fetch_and_add, which is an overloaded function based on the pointer
945/// type of its first argument. The main ActOnCallExpr routines have already
946/// promoted the types of arguments because all of these calls are prototyped as
947/// void(...).
948///
949/// This function goes through and does final semantic checking for these
950/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +0000951ExprResult
952Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000953 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +0000954 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
955 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
956
957 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +0000958 if (TheCall->getNumArgs() < 1) {
959 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
960 << 0 << 1 << TheCall->getNumArgs()
961 << TheCall->getCallee()->getSourceRange();
962 return ExprError();
963 }
Mike Stump1eb44332009-09-09 15:08:12 +0000964
Chris Lattner5caa3702009-05-08 06:58:22 +0000965 // Inspect the first argument of the atomic builtin. This should always be
966 // a pointer type, whose element is an integral scalar or pointer type.
967 // Because it is a pointer type, we don't have to worry about any implicit
968 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +0000969 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +0000970 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman8c382062012-01-23 02:35:22 +0000971 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
972 if (FirstArgResult.isInvalid())
973 return ExprError();
974 FirstArg = FirstArgResult.take();
975 TheCall->setArg(0, FirstArg);
976
John McCallf85e1932011-06-15 23:02:42 +0000977 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
978 if (!pointerType) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000979 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
980 << FirstArg->getType() << FirstArg->getSourceRange();
981 return ExprError();
982 }
Mike Stump1eb44332009-09-09 15:08:12 +0000983
John McCallf85e1932011-06-15 23:02:42 +0000984 QualType ValType = pointerType->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +0000985 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +0000986 !ValType->isBlockPointerType()) {
987 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
988 << FirstArg->getType() << FirstArg->getSourceRange();
989 return ExprError();
990 }
Chris Lattner5caa3702009-05-08 06:58:22 +0000991
John McCallf85e1932011-06-15 23:02:42 +0000992 switch (ValType.getObjCLifetime()) {
993 case Qualifiers::OCL_None:
994 case Qualifiers::OCL_ExplicitNone:
995 // okay
996 break;
997
998 case Qualifiers::OCL_Weak:
999 case Qualifiers::OCL_Strong:
1000 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00001001 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCallf85e1932011-06-15 23:02:42 +00001002 << ValType << FirstArg->getSourceRange();
1003 return ExprError();
1004 }
1005
John McCallb45ae252011-10-05 07:41:44 +00001006 // Strip any qualifiers off ValType.
1007 ValType = ValType.getUnqualifiedType();
1008
Chandler Carruth8d13d222010-07-18 20:54:12 +00001009 // The majority of builtins return a value, but a few have special return
1010 // types, so allow them to override appropriately below.
1011 QualType ResultType = ValType;
1012
Chris Lattner5caa3702009-05-08 06:58:22 +00001013 // We need to figure out which concrete builtin this maps onto. For example,
1014 // __sync_fetch_and_add with a 2 byte object turns into
1015 // __sync_fetch_and_add_2.
1016#define BUILTIN_ROW(x) \
1017 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1018 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +00001019
Chris Lattner5caa3702009-05-08 06:58:22 +00001020 static const unsigned BuiltinIndices[][5] = {
1021 BUILTIN_ROW(__sync_fetch_and_add),
1022 BUILTIN_ROW(__sync_fetch_and_sub),
1023 BUILTIN_ROW(__sync_fetch_and_or),
1024 BUILTIN_ROW(__sync_fetch_and_and),
1025 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +00001026
Chris Lattner5caa3702009-05-08 06:58:22 +00001027 BUILTIN_ROW(__sync_add_and_fetch),
1028 BUILTIN_ROW(__sync_sub_and_fetch),
1029 BUILTIN_ROW(__sync_and_and_fetch),
1030 BUILTIN_ROW(__sync_or_and_fetch),
1031 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +00001032
Chris Lattner5caa3702009-05-08 06:58:22 +00001033 BUILTIN_ROW(__sync_val_compare_and_swap),
1034 BUILTIN_ROW(__sync_bool_compare_and_swap),
1035 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +00001036 BUILTIN_ROW(__sync_lock_release),
1037 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +00001038 };
Mike Stump1eb44332009-09-09 15:08:12 +00001039#undef BUILTIN_ROW
1040
Chris Lattner5caa3702009-05-08 06:58:22 +00001041 // Determine the index of the size.
1042 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +00001043 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +00001044 case 1: SizeIndex = 0; break;
1045 case 2: SizeIndex = 1; break;
1046 case 4: SizeIndex = 2; break;
1047 case 8: SizeIndex = 3; break;
1048 case 16: SizeIndex = 4; break;
1049 default:
Chandler Carruthd2014572010-07-09 18:59:35 +00001050 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1051 << FirstArg->getType() << FirstArg->getSourceRange();
1052 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +00001053 }
Mike Stump1eb44332009-09-09 15:08:12 +00001054
Chris Lattner5caa3702009-05-08 06:58:22 +00001055 // Each of these builtins has one pointer argument, followed by some number of
1056 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1057 // that we ignore. Find out which row of BuiltinIndices to read from as well
1058 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00001059 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +00001060 unsigned BuiltinIndex, NumFixed = 1;
1061 switch (BuiltinID) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001062 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregora9766412011-11-28 16:30:08 +00001063 case Builtin::BI__sync_fetch_and_add:
1064 case Builtin::BI__sync_fetch_and_add_1:
1065 case Builtin::BI__sync_fetch_and_add_2:
1066 case Builtin::BI__sync_fetch_and_add_4:
1067 case Builtin::BI__sync_fetch_and_add_8:
1068 case Builtin::BI__sync_fetch_and_add_16:
1069 BuiltinIndex = 0;
1070 break;
1071
1072 case Builtin::BI__sync_fetch_and_sub:
1073 case Builtin::BI__sync_fetch_and_sub_1:
1074 case Builtin::BI__sync_fetch_and_sub_2:
1075 case Builtin::BI__sync_fetch_and_sub_4:
1076 case Builtin::BI__sync_fetch_and_sub_8:
1077 case Builtin::BI__sync_fetch_and_sub_16:
1078 BuiltinIndex = 1;
1079 break;
1080
1081 case Builtin::BI__sync_fetch_and_or:
1082 case Builtin::BI__sync_fetch_and_or_1:
1083 case Builtin::BI__sync_fetch_and_or_2:
1084 case Builtin::BI__sync_fetch_and_or_4:
1085 case Builtin::BI__sync_fetch_and_or_8:
1086 case Builtin::BI__sync_fetch_and_or_16:
1087 BuiltinIndex = 2;
1088 break;
1089
1090 case Builtin::BI__sync_fetch_and_and:
1091 case Builtin::BI__sync_fetch_and_and_1:
1092 case Builtin::BI__sync_fetch_and_and_2:
1093 case Builtin::BI__sync_fetch_and_and_4:
1094 case Builtin::BI__sync_fetch_and_and_8:
1095 case Builtin::BI__sync_fetch_and_and_16:
1096 BuiltinIndex = 3;
1097 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001098
Douglas Gregora9766412011-11-28 16:30:08 +00001099 case Builtin::BI__sync_fetch_and_xor:
1100 case Builtin::BI__sync_fetch_and_xor_1:
1101 case Builtin::BI__sync_fetch_and_xor_2:
1102 case Builtin::BI__sync_fetch_and_xor_4:
1103 case Builtin::BI__sync_fetch_and_xor_8:
1104 case Builtin::BI__sync_fetch_and_xor_16:
1105 BuiltinIndex = 4;
1106 break;
1107
1108 case Builtin::BI__sync_add_and_fetch:
1109 case Builtin::BI__sync_add_and_fetch_1:
1110 case Builtin::BI__sync_add_and_fetch_2:
1111 case Builtin::BI__sync_add_and_fetch_4:
1112 case Builtin::BI__sync_add_and_fetch_8:
1113 case Builtin::BI__sync_add_and_fetch_16:
1114 BuiltinIndex = 5;
1115 break;
1116
1117 case Builtin::BI__sync_sub_and_fetch:
1118 case Builtin::BI__sync_sub_and_fetch_1:
1119 case Builtin::BI__sync_sub_and_fetch_2:
1120 case Builtin::BI__sync_sub_and_fetch_4:
1121 case Builtin::BI__sync_sub_and_fetch_8:
1122 case Builtin::BI__sync_sub_and_fetch_16:
1123 BuiltinIndex = 6;
1124 break;
1125
1126 case Builtin::BI__sync_and_and_fetch:
1127 case Builtin::BI__sync_and_and_fetch_1:
1128 case Builtin::BI__sync_and_and_fetch_2:
1129 case Builtin::BI__sync_and_and_fetch_4:
1130 case Builtin::BI__sync_and_and_fetch_8:
1131 case Builtin::BI__sync_and_and_fetch_16:
1132 BuiltinIndex = 7;
1133 break;
1134
1135 case Builtin::BI__sync_or_and_fetch:
1136 case Builtin::BI__sync_or_and_fetch_1:
1137 case Builtin::BI__sync_or_and_fetch_2:
1138 case Builtin::BI__sync_or_and_fetch_4:
1139 case Builtin::BI__sync_or_and_fetch_8:
1140 case Builtin::BI__sync_or_and_fetch_16:
1141 BuiltinIndex = 8;
1142 break;
1143
1144 case Builtin::BI__sync_xor_and_fetch:
1145 case Builtin::BI__sync_xor_and_fetch_1:
1146 case Builtin::BI__sync_xor_and_fetch_2:
1147 case Builtin::BI__sync_xor_and_fetch_4:
1148 case Builtin::BI__sync_xor_and_fetch_8:
1149 case Builtin::BI__sync_xor_and_fetch_16:
1150 BuiltinIndex = 9;
1151 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001152
Chris Lattner5caa3702009-05-08 06:58:22 +00001153 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001154 case Builtin::BI__sync_val_compare_and_swap_1:
1155 case Builtin::BI__sync_val_compare_and_swap_2:
1156 case Builtin::BI__sync_val_compare_and_swap_4:
1157 case Builtin::BI__sync_val_compare_and_swap_8:
1158 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001159 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +00001160 NumFixed = 2;
1161 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001162
Chris Lattner5caa3702009-05-08 06:58:22 +00001163 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001164 case Builtin::BI__sync_bool_compare_and_swap_1:
1165 case Builtin::BI__sync_bool_compare_and_swap_2:
1166 case Builtin::BI__sync_bool_compare_and_swap_4:
1167 case Builtin::BI__sync_bool_compare_and_swap_8:
1168 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001169 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +00001170 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001171 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001172 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001173
1174 case Builtin::BI__sync_lock_test_and_set:
1175 case Builtin::BI__sync_lock_test_and_set_1:
1176 case Builtin::BI__sync_lock_test_and_set_2:
1177 case Builtin::BI__sync_lock_test_and_set_4:
1178 case Builtin::BI__sync_lock_test_and_set_8:
1179 case Builtin::BI__sync_lock_test_and_set_16:
1180 BuiltinIndex = 12;
1181 break;
1182
Chris Lattner5caa3702009-05-08 06:58:22 +00001183 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +00001184 case Builtin::BI__sync_lock_release_1:
1185 case Builtin::BI__sync_lock_release_2:
1186 case Builtin::BI__sync_lock_release_4:
1187 case Builtin::BI__sync_lock_release_8:
1188 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001189 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +00001190 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001191 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001192 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001193
1194 case Builtin::BI__sync_swap:
1195 case Builtin::BI__sync_swap_1:
1196 case Builtin::BI__sync_swap_2:
1197 case Builtin::BI__sync_swap_4:
1198 case Builtin::BI__sync_swap_8:
1199 case Builtin::BI__sync_swap_16:
1200 BuiltinIndex = 14;
1201 break;
Chris Lattner5caa3702009-05-08 06:58:22 +00001202 }
Mike Stump1eb44332009-09-09 15:08:12 +00001203
Chris Lattner5caa3702009-05-08 06:58:22 +00001204 // Now that we know how many fixed arguments we expect, first check that we
1205 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +00001206 if (TheCall->getNumArgs() < 1+NumFixed) {
1207 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1208 << 0 << 1+NumFixed << TheCall->getNumArgs()
1209 << TheCall->getCallee()->getSourceRange();
1210 return ExprError();
1211 }
Mike Stump1eb44332009-09-09 15:08:12 +00001212
Chris Lattnere7ac0a92009-05-08 15:36:58 +00001213 // Get the decl for the concrete builtin from this, we can tell what the
1214 // concrete integer type we should convert to is.
1215 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1216 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara2ad11cd2012-09-22 09:05:22 +00001217 FunctionDecl *NewBuiltinDecl;
1218 if (NewBuiltinID == BuiltinID)
1219 NewBuiltinDecl = FDecl;
1220 else {
1221 // Perform builtin lookup to avoid redeclaring it.
1222 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1223 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1224 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1225 assert(Res.getFoundDecl());
1226 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
1227 if (NewBuiltinDecl == 0)
1228 return ExprError();
1229 }
Chandler Carruthd2014572010-07-09 18:59:35 +00001230
John McCallf871d0c2010-08-07 06:22:56 +00001231 // The first argument --- the pointer --- has a fixed type; we
1232 // deduce the types of the rest of the arguments accordingly. Walk
1233 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +00001234 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +00001235 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +00001236
Chris Lattner5caa3702009-05-08 06:58:22 +00001237 // GCC does an implicit conversion to the pointer or integer ValType. This
1238 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb45ae252011-10-05 07:41:44 +00001239 // Initialize the argument.
1240 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1241 ValType, /*consume*/ false);
1242 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley429bb272011-04-08 18:41:53 +00001243 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +00001244 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001245
Chris Lattner5caa3702009-05-08 06:58:22 +00001246 // Okay, we have something that *can* be converted to the right type. Check
1247 // to see if there is a potentially weird extension going on here. This can
1248 // happen when you do an atomic operation on something like an char* and
1249 // pass in 42. The 42 gets converted to char. This is even more strange
1250 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +00001251 // FIXME: Do this check.
John McCallb45ae252011-10-05 07:41:44 +00001252 TheCall->setArg(i+1, Arg.take());
Chris Lattner5caa3702009-05-08 06:58:22 +00001253 }
Mike Stump1eb44332009-09-09 15:08:12 +00001254
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001255 ASTContext& Context = this->getASTContext();
1256
1257 // Create a new DeclRefExpr to refer to the new decl.
1258 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1259 Context,
1260 DRE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001261 SourceLocation(),
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001262 NewBuiltinDecl,
John McCallf4b88a42012-03-10 09:33:50 +00001263 /*enclosing*/ false,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001264 DRE->getLocation(),
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001265 Context.BuiltinFnTy,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001266 DRE->getValueKind());
Mike Stump1eb44332009-09-09 15:08:12 +00001267
Chris Lattner5caa3702009-05-08 06:58:22 +00001268 // Set the callee in the CallExpr.
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001269 // FIXME: This loses syntactic information.
1270 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1271 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1272 CK_BuiltinFnToFnPtr);
John Wiegley429bb272011-04-08 18:41:53 +00001273 TheCall->setCallee(PromotedCall.take());
Mike Stump1eb44332009-09-09 15:08:12 +00001274
Chandler Carruthdb4325b2010-07-18 07:23:17 +00001275 // Change the result type of the call to match the original value type. This
1276 // is arbitrary, but the codegen for these builtins ins design to handle it
1277 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +00001278 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +00001279
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001280 return TheCallResult;
Chris Lattner5caa3702009-05-08 06:58:22 +00001281}
1282
Chris Lattner69039812009-02-18 06:01:06 +00001283/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +00001284/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +00001285/// Note: It might also make sense to do the UTF-16 conversion here (would
1286/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +00001287bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +00001288 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +00001289 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1290
Douglas Gregor5cee1192011-07-27 05:40:30 +00001291 if (!Literal || !Literal->isAscii()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001292 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1293 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001294 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +00001295 }
Mike Stump1eb44332009-09-09 15:08:12 +00001296
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001297 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001298 StringRef String = Literal->getString();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001299 unsigned NumBytes = String.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001300 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divacky31ba6132012-09-06 15:59:27 +00001301 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001302 UTF16 *ToPtr = &ToBuf[0];
1303
1304 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1305 &ToPtr, ToPtr + NumBytes,
1306 strictConversion);
1307 // Check for conversion failure.
1308 if (Result != conversionOK)
1309 Diag(Arg->getLocStart(),
1310 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1311 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001312 return false;
Chris Lattner59907c42007-08-10 20:18:51 +00001313}
1314
Chris Lattnerc27c6652007-12-20 00:05:45 +00001315/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1316/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +00001317bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1318 Expr *Fn = TheCall->getCallee();
1319 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +00001320 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001321 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001322 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1323 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +00001324 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001325 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +00001326 return true;
1327 }
Eli Friedman56f20ae2008-12-15 22:05:35 +00001328
1329 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +00001330 return Diag(TheCall->getLocEnd(),
1331 diag::err_typecheck_call_too_few_args_at_least)
1332 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +00001333 }
1334
John McCall5f8d6042011-08-27 01:09:30 +00001335 // Type-check the first argument normally.
1336 if (checkBuiltinArgument(*this, TheCall, 0))
1337 return true;
1338
Chris Lattnerc27c6652007-12-20 00:05:45 +00001339 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001340 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +00001341 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001342 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +00001343 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +00001344 else if (FunctionDecl *FD = getCurFunctionDecl())
1345 isVariadic = FD->isVariadic();
1346 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001347 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +00001348
Chris Lattnerc27c6652007-12-20 00:05:45 +00001349 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001350 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1351 return true;
1352 }
Mike Stump1eb44332009-09-09 15:08:12 +00001353
Chris Lattner30ce3442007-12-19 23:59:04 +00001354 // Verify that the second argument to the builtin is the last argument of the
1355 // current function or method.
1356 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +00001357 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001358
Anders Carlsson88cf2262008-02-11 04:20:54 +00001359 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1360 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001361 // FIXME: This isn't correct for methods (results in bogus warning).
1362 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +00001363 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001364 if (CurBlock)
1365 LastArg = *(CurBlock->TheDecl->param_end()-1);
1366 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +00001367 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001368 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001369 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001370 SecondArgIsLastNamedArgument = PV == LastArg;
1371 }
1372 }
Mike Stump1eb44332009-09-09 15:08:12 +00001373
Chris Lattner30ce3442007-12-19 23:59:04 +00001374 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001375 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +00001376 diag::warn_second_parameter_of_va_start_not_last_named_argument);
1377 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +00001378}
Chris Lattner30ce3442007-12-19 23:59:04 +00001379
Chris Lattner1b9a0792007-12-20 00:26:33 +00001380/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1381/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +00001382bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1383 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +00001384 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001385 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +00001386 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +00001387 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001388 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001389 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001390 << SourceRange(TheCall->getArg(2)->getLocStart(),
1391 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001392
John Wiegley429bb272011-04-08 18:41:53 +00001393 ExprResult OrigArg0 = TheCall->getArg(0);
1394 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +00001395
Chris Lattner1b9a0792007-12-20 00:26:33 +00001396 // Do standard promotions between the two arguments, returning their common
1397 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +00001398 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +00001399 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1400 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +00001401
1402 // Make sure any conversions are pushed back into the call; this is
1403 // type safe since unordered compare builtins are declared as "_Bool
1404 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +00001405 TheCall->setArg(0, OrigArg0.get());
1406 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001407
John Wiegley429bb272011-04-08 18:41:53 +00001408 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +00001409 return false;
1410
Chris Lattner1b9a0792007-12-20 00:26:33 +00001411 // If the common type isn't a real floating type, then the arguments were
1412 // invalid for this operation.
Eli Friedman860a3192012-06-16 02:19:17 +00001413 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +00001414 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001415 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +00001416 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1417 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001418
Chris Lattner1b9a0792007-12-20 00:26:33 +00001419 return false;
1420}
1421
Benjamin Kramere771a7a2010-02-15 22:42:31 +00001422/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1423/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001424/// to check everything. We expect the last argument to be a floating point
1425/// value.
1426bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1427 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +00001428 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001429 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001430 if (TheCall->getNumArgs() > NumArgs)
1431 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001432 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001433 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001434 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001435 (*(TheCall->arg_end()-1))->getLocEnd());
1436
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001437 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001438
Eli Friedman9ac6f622009-08-31 20:06:00 +00001439 if (OrigArg->isTypeDependent())
1440 return false;
1441
Chris Lattner81368fb2010-05-06 05:50:07 +00001442 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +00001443 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +00001444 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001445 diag::err_typecheck_call_invalid_unary_fp)
1446 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001447
Chris Lattner81368fb2010-05-06 05:50:07 +00001448 // If this is an implicit conversion from float -> double, remove it.
1449 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1450 Expr *CastArg = Cast->getSubExpr();
1451 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1452 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1453 "promotion from float to double is the only expected cast here");
1454 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +00001455 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner81368fb2010-05-06 05:50:07 +00001456 }
1457 }
1458
Eli Friedman9ac6f622009-08-31 20:06:00 +00001459 return false;
1460}
1461
Eli Friedmand38617c2008-05-14 19:38:39 +00001462/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1463// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +00001464ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001465 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001466 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +00001467 diag::err_typecheck_call_too_few_args_at_least)
Nate Begeman37b6a572010-06-08 00:16:34 +00001468 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherd77b9a22010-04-16 04:48:22 +00001469 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001470
Nate Begeman37b6a572010-06-08 00:16:34 +00001471 // Determine which of the following types of shufflevector we're checking:
1472 // 1) unary, vector mask: (lhs, mask)
1473 // 2) binary, vector mask: (lhs, rhs, mask)
1474 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1475 QualType resType = TheCall->getArg(0)->getType();
1476 unsigned numElements = 0;
1477
Douglas Gregorcde01732009-05-19 22:10:17 +00001478 if (!TheCall->getArg(0)->isTypeDependent() &&
1479 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001480 QualType LHSType = TheCall->getArg(0)->getType();
1481 QualType RHSType = TheCall->getArg(1)->getType();
1482
1483 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001484 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001485 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001486 TheCall->getArg(1)->getLocEnd());
1487 return ExprError();
1488 }
Nate Begeman37b6a572010-06-08 00:16:34 +00001489
1490 numElements = LHSType->getAs<VectorType>()->getNumElements();
1491 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +00001492
Nate Begeman37b6a572010-06-08 00:16:34 +00001493 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1494 // with mask. If so, verify that RHS is an integer vector type with the
1495 // same number of elts as lhs.
1496 if (TheCall->getNumArgs() == 2) {
Douglas Gregorf6094622010-07-23 15:58:24 +00001497 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +00001498 RHSType->getAs<VectorType>()->getNumElements() != numElements)
1499 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1500 << SourceRange(TheCall->getArg(1)->getLocStart(),
1501 TheCall->getArg(1)->getLocEnd());
1502 numResElements = numElements;
1503 }
1504 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001505 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_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();
Nate Begeman37b6a572010-06-08 00:16:34 +00001509 } else if (numElements != numResElements) {
1510 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +00001511 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001512 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +00001513 }
Eli Friedmand38617c2008-05-14 19:38:39 +00001514 }
1515
1516 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001517 if (TheCall->getArg(i)->isTypeDependent() ||
1518 TheCall->getArg(i)->isValueDependent())
1519 continue;
1520
Nate Begeman37b6a572010-06-08 00:16:34 +00001521 llvm::APSInt Result(32);
1522 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1523 return ExprError(Diag(TheCall->getLocStart(),
1524 diag::err_shufflevector_nonconstant_argument)
1525 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001526
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001527 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001528 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001529 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001530 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001531 }
1532
Chris Lattner5f9e2722011-07-23 10:55:15 +00001533 SmallVector<Expr*, 32> exprs;
Eli Friedmand38617c2008-05-14 19:38:39 +00001534
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001535 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +00001536 exprs.push_back(TheCall->getArg(i));
1537 TheCall->setArg(i, 0);
1538 }
1539
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001540 return Owned(new (Context) ShuffleVectorExpr(Context, exprs, resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001541 TheCall->getCallee()->getLocStart(),
1542 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +00001543}
Chris Lattner30ce3442007-12-19 23:59:04 +00001544
Daniel Dunbar4493f792008-07-21 22:59:13 +00001545/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1546// This is declared to take (const void*, ...) and can take two
1547// optional constant int args.
1548bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001549 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001550
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001551 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +00001552 return Diag(TheCall->getLocEnd(),
1553 diag::err_typecheck_call_too_many_args_at_most)
1554 << 0 /*function call*/ << 3 << NumArgs
1555 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001556
1557 // Argument 0 is checked for us and the remaining arguments must be
1558 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001559 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +00001560 Expr *Arg = TheCall->getArg(i);
Douglas Gregor592a4232012-06-29 01:05:22 +00001561
1562 // We can't check the value of a dependent argument.
1563 if (Arg->isTypeDependent() || Arg->isValueDependent())
1564 continue;
1565
Eli Friedman9aef7262009-12-04 00:30:06 +00001566 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +00001567 if (SemaBuiltinConstantArg(TheCall, i, Result))
1568 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001569
Daniel Dunbar4493f792008-07-21 22:59:13 +00001570 // FIXME: gcc issues a warning and rewrites these to 0. These
1571 // seems especially odd for the third argument since the default
1572 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001573 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +00001574 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001575 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001576 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001577 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +00001578 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001579 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001580 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001581 }
1582 }
1583
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001584 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +00001585}
1586
Eric Christopher691ebc32010-04-17 02:26:23 +00001587/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1588/// TheCall is a constant expression.
1589bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1590 llvm::APSInt &Result) {
1591 Expr *Arg = TheCall->getArg(ArgNum);
1592 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1593 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1594
1595 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1596
1597 if (!Arg->isIntegerConstantExpr(Result, Context))
1598 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +00001599 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +00001600
Chris Lattner21fb98e2009-09-23 06:06:36 +00001601 return false;
1602}
1603
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001604/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1605/// int type). This simply type checks that type is one of the defined
1606/// constants (0-3).
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001607// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001608bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +00001609 llvm::APSInt Result;
Douglas Gregor592a4232012-06-29 01:05:22 +00001610
1611 // We can't check the value of a dependent argument.
1612 if (TheCall->getArg(1)->isTypeDependent() ||
1613 TheCall->getArg(1)->isValueDependent())
1614 return false;
1615
Eric Christopher691ebc32010-04-17 02:26:23 +00001616 // Check constant-ness first.
1617 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1618 return true;
1619
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001620 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001621 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001622 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1623 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001624 }
1625
1626 return false;
1627}
1628
Eli Friedman586d6a82009-05-03 06:04:26 +00001629/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +00001630/// This checks that val is a constant 1.
1631bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1632 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +00001633 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +00001634
Eric Christopher691ebc32010-04-17 02:26:23 +00001635 // TODO: This is less than ideal. Overload this to take a value.
1636 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1637 return true;
1638
1639 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +00001640 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1641 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1642
1643 return false;
1644}
1645
Richard Smith831421f2012-06-25 20:30:08 +00001646// Determine if an expression is a string literal or constant string.
1647// If this function returns false on the arguments to a function expecting a
1648// format string, we will usually need to emit a warning.
1649// True string literals are then checked by CheckFormatString.
1650Sema::StringLiteralCheckType
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001651Sema::checkFormatStringExpr(const Expr *E, ArrayRef<const Expr *> Args,
1652 bool HasVAListArg,
Richard Smith831421f2012-06-25 20:30:08 +00001653 unsigned format_idx, unsigned firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001654 FormatStringType Type, VariadicCallType CallType,
1655 bool inFunctionCall) {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001656 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +00001657 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith831421f2012-06-25 20:30:08 +00001658 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001659
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001660 E = E->IgnoreParenCasts();
Peter Collingbournef111d932011-04-15 00:35:48 +00001661
David Blaikiea73cdcb2012-02-10 21:07:25 +00001662 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
1663 // Technically -Wformat-nonliteral does not warn about this case.
1664 // The behavior of printf and friends in this case is implementation
1665 // dependent. Ideally if the format string cannot be null then
1666 // it should have a 'nonnull' attribute in the function prototype.
Richard Smith831421f2012-06-25 20:30:08 +00001667 return SLCT_CheckedLiteral;
David Blaikiea73cdcb2012-02-10 21:07:25 +00001668
Ted Kremenekd30ef872009-01-12 23:09:09 +00001669 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +00001670 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +00001671 case Stmt::ConditionalOperatorClass: {
Richard Smith831421f2012-06-25 20:30:08 +00001672 // The expression is a literal if both sub-expressions were, and it was
1673 // completely checked only if both sub-expressions were checked.
1674 const AbstractConditionalOperator *C =
1675 cast<AbstractConditionalOperator>(E);
1676 StringLiteralCheckType Left =
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001677 checkFormatStringExpr(C->getTrueExpr(), Args,
Richard Smith831421f2012-06-25 20:30:08 +00001678 HasVAListArg, format_idx, firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001679 Type, CallType, inFunctionCall);
Richard Smith831421f2012-06-25 20:30:08 +00001680 if (Left == SLCT_NotALiteral)
1681 return SLCT_NotALiteral;
1682 StringLiteralCheckType Right =
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001683 checkFormatStringExpr(C->getFalseExpr(), Args,
Richard Smith831421f2012-06-25 20:30:08 +00001684 HasVAListArg, format_idx, firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001685 Type, CallType, inFunctionCall);
Richard Smith831421f2012-06-25 20:30:08 +00001686 return Left < Right ? Left : Right;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001687 }
1688
1689 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001690 E = cast<ImplicitCastExpr>(E)->getSubExpr();
1691 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001692 }
1693
John McCall56ca35d2011-02-17 10:25:35 +00001694 case Stmt::OpaqueValueExprClass:
1695 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
1696 E = src;
1697 goto tryAgain;
1698 }
Richard Smith831421f2012-06-25 20:30:08 +00001699 return SLCT_NotALiteral;
John McCall56ca35d2011-02-17 10:25:35 +00001700
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001701 case Stmt::PredefinedExprClass:
1702 // While __func__, etc., are technically not string literals, they
1703 // cannot contain format specifiers and thus are not a security
1704 // liability.
Richard Smith831421f2012-06-25 20:30:08 +00001705 return SLCT_UncheckedLiteral;
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001706
Ted Kremenek082d9362009-03-20 21:35:28 +00001707 case Stmt::DeclRefExprClass: {
1708 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001709
Ted Kremenek082d9362009-03-20 21:35:28 +00001710 // As an exception, do not flag errors for variables binding to
1711 // const string literals.
1712 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1713 bool isConstant = false;
1714 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001715
Ted Kremenek082d9362009-03-20 21:35:28 +00001716 if (const ArrayType *AT = Context.getAsArrayType(T)) {
1717 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001718 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001719 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +00001720 PT->getPointeeType().isConstant(Context);
Jean-Daniel Dupase98e5b52012-01-25 10:35:33 +00001721 } else if (T->isObjCObjectPointerType()) {
1722 // In ObjC, there is usually no "const ObjectPointer" type,
1723 // so don't check if the pointee type is constant.
1724 isConstant = T.isConstant(Context);
Ted Kremenek082d9362009-03-20 21:35:28 +00001725 }
Mike Stump1eb44332009-09-09 15:08:12 +00001726
Ted Kremenek082d9362009-03-20 21:35:28 +00001727 if (isConstant) {
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00001728 if (const Expr *Init = VD->getAnyInitializer()) {
1729 // Look through initializers like const char c[] = { "foo" }
1730 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
1731 if (InitList->isStringLiteralInit())
1732 Init = InitList->getInit(0)->IgnoreParenImpCasts();
1733 }
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001734 return checkFormatStringExpr(Init, Args,
Richard Smith831421f2012-06-25 20:30:08 +00001735 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001736 firstDataArg, Type, CallType,
Richard Smith831421f2012-06-25 20:30:08 +00001737 /*inFunctionCall*/false);
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00001738 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001739 }
Mike Stump1eb44332009-09-09 15:08:12 +00001740
Anders Carlssond966a552009-06-28 19:55:58 +00001741 // For vprintf* functions (i.e., HasVAListArg==true), we add a
1742 // special check to see if the format string is a function parameter
1743 // of the function calling the printf function. If the function
1744 // has an attribute indicating it is a printf-like function, then we
1745 // should suppress warnings concerning non-literals being used in a call
1746 // to a vprintf function. For example:
1747 //
1748 // void
1749 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1750 // va_list ap;
1751 // va_start(ap, fmt);
1752 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
1753 // ...
1754 //
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00001755 if (HasVAListArg) {
1756 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
1757 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
1758 int PVIndex = PV->getFunctionScopeIndex() + 1;
1759 for (specific_attr_iterator<FormatAttr>
1760 i = ND->specific_attr_begin<FormatAttr>(),
1761 e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) {
1762 FormatAttr *PVFormat = *i;
1763 // adjust for implicit parameter
1764 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1765 if (MD->isInstance())
1766 ++PVIndex;
1767 // We also check if the formats are compatible.
1768 // We can't pass a 'scanf' string to a 'printf' function.
1769 if (PVIndex == PVFormat->getFormatIdx() &&
1770 Type == GetFormatStringType(PVFormat))
Richard Smith831421f2012-06-25 20:30:08 +00001771 return SLCT_UncheckedLiteral;
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00001772 }
1773 }
1774 }
1775 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001776 }
Mike Stump1eb44332009-09-09 15:08:12 +00001777
Richard Smith831421f2012-06-25 20:30:08 +00001778 return SLCT_NotALiteral;
Ted Kremenek082d9362009-03-20 21:35:28 +00001779 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00001780
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001781 case Stmt::CallExprClass:
1782 case Stmt::CXXMemberCallExprClass: {
Anders Carlsson8f031b32009-06-27 04:05:33 +00001783 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001784 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
1785 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
1786 unsigned ArgIndex = FA->getFormatIdx();
1787 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1788 if (MD->isInstance())
1789 --ArgIndex;
1790 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001791
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001792 return checkFormatStringExpr(Arg, Args,
Richard Smith831421f2012-06-25 20:30:08 +00001793 HasVAListArg, format_idx, firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001794 Type, CallType, inFunctionCall);
Jordan Rose50687312012-06-04 23:52:23 +00001795 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
1796 unsigned BuiltinID = FD->getBuiltinID();
1797 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
1798 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
1799 const Expr *Arg = CE->getArg(0);
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001800 return checkFormatStringExpr(Arg, Args,
Richard Smith831421f2012-06-25 20:30:08 +00001801 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001802 firstDataArg, Type, CallType,
1803 inFunctionCall);
Jordan Rose50687312012-06-04 23:52:23 +00001804 }
Anders Carlsson8f031b32009-06-27 04:05:33 +00001805 }
1806 }
Mike Stump1eb44332009-09-09 15:08:12 +00001807
Richard Smith831421f2012-06-25 20:30:08 +00001808 return SLCT_NotALiteral;
Anders Carlsson8f031b32009-06-27 04:05:33 +00001809 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001810 case Stmt::ObjCStringLiteralClass:
1811 case Stmt::StringLiteralClass: {
1812 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001813
Ted Kremenek082d9362009-03-20 21:35:28 +00001814 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00001815 StrE = ObjCFExpr->getString();
1816 else
Ted Kremenek082d9362009-03-20 21:35:28 +00001817 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001818
Ted Kremenekd30ef872009-01-12 23:09:09 +00001819 if (StrE) {
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001820 CheckFormatString(StrE, E, Args, HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001821 firstDataArg, Type, inFunctionCall, CallType);
Richard Smith831421f2012-06-25 20:30:08 +00001822 return SLCT_CheckedLiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001823 }
Mike Stump1eb44332009-09-09 15:08:12 +00001824
Richard Smith831421f2012-06-25 20:30:08 +00001825 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001826 }
Mike Stump1eb44332009-09-09 15:08:12 +00001827
Ted Kremenek082d9362009-03-20 21:35:28 +00001828 default:
Richard Smith831421f2012-06-25 20:30:08 +00001829 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001830 }
1831}
1832
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001833void
Mike Stump1eb44332009-09-09 15:08:12 +00001834Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewycky909a70d2011-03-25 01:44:32 +00001835 const Expr * const *ExprArgs,
1836 SourceLocation CallSiteLoc) {
Sean Huntcf807c42010-08-18 23:23:40 +00001837 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1838 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001839 i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +00001840 const Expr *ArgExpr = ExprArgs[*i];
Nick Lewycky3edf3872013-01-23 05:08:29 +00001841
1842 // As a special case, transparent unions initialized with zero are
1843 // considered null for the purposes of the nonnull attribute.
1844 if (const RecordType *UT = ArgExpr->getType()->getAsUnionType()) {
1845 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
1846 if (const CompoundLiteralExpr *CLE =
1847 dyn_cast<CompoundLiteralExpr>(ArgExpr))
1848 if (const InitListExpr *ILE =
1849 dyn_cast<InitListExpr>(CLE->getInitializer()))
1850 ArgExpr = ILE->getInit(0);
1851 }
1852
1853 bool Result;
1854 if (ArgExpr->EvaluateAsBooleanCondition(Result, Context) && !Result)
Nick Lewycky909a70d2011-03-25 01:44:32 +00001855 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001856 }
1857}
Ted Kremenekd30ef872009-01-12 23:09:09 +00001858
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001859Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
1860 return llvm::StringSwitch<FormatStringType>(Format->getType())
1861 .Case("scanf", FST_Scanf)
1862 .Cases("printf", "printf0", FST_Printf)
1863 .Cases("NSString", "CFString", FST_NSString)
1864 .Case("strftime", FST_Strftime)
1865 .Case("strfmon", FST_Strfmon)
1866 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
1867 .Default(FST_Unknown);
1868}
1869
Jordan Roseddcfbc92012-07-19 18:10:23 +00001870/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek826a3452010-07-16 02:11:22 +00001871/// functions) for correct use of format strings.
Richard Smith831421f2012-06-25 20:30:08 +00001872/// Returns true if a format string has been fully checked.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001873bool Sema::CheckFormatArguments(const FormatAttr *Format,
1874 ArrayRef<const Expr *> Args,
1875 bool IsCXXMember,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001876 VariadicCallType CallType,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001877 SourceLocation Loc, SourceRange Range) {
Richard Smith831421f2012-06-25 20:30:08 +00001878 FormatStringInfo FSI;
1879 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001880 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith831421f2012-06-25 20:30:08 +00001881 FSI.FirstDataArg, GetFormatStringType(Format),
Jordan Roseddcfbc92012-07-19 18:10:23 +00001882 CallType, Loc, Range);
Richard Smith831421f2012-06-25 20:30:08 +00001883 return false;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001884}
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001885
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001886bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001887 bool HasVAListArg, unsigned format_idx,
1888 unsigned firstDataArg, FormatStringType Type,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001889 VariadicCallType CallType,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001890 SourceLocation Loc, SourceRange Range) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001891 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001892 if (format_idx >= Args.size()) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001893 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith831421f2012-06-25 20:30:08 +00001894 return false;
Ted Kremenek71895b92007-08-14 17:39:48 +00001895 }
Mike Stump1eb44332009-09-09 15:08:12 +00001896
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001897 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001898
Chris Lattner59907c42007-08-10 20:18:51 +00001899 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001900 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001901 // Dynamically generated format strings are difficult to
1902 // automatically vet at compile time. Requiring that format strings
1903 // are string literals: (1) permits the checking of format strings by
1904 // the compiler and thereby (2) can practically remove the source of
1905 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001906
Mike Stump1eb44332009-09-09 15:08:12 +00001907 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001908 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001909 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001910 // the same format string checking logic for both ObjC and C strings.
Richard Smith831421f2012-06-25 20:30:08 +00001911 StringLiteralCheckType CT =
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001912 checkFormatStringExpr(OrigFormatExpr, Args, HasVAListArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001913 format_idx, firstDataArg, Type, CallType);
Richard Smith831421f2012-06-25 20:30:08 +00001914 if (CT != SLCT_NotALiteral)
1915 // Literal format string found, check done!
1916 return CT == SLCT_CheckedLiteral;
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001917
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00001918 // Strftime is particular as it always uses a single 'time' argument,
1919 // so it is safe to pass a non-literal string.
1920 if (Type == FST_Strftime)
Richard Smith831421f2012-06-25 20:30:08 +00001921 return false;
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00001922
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00001923 // Do not emit diag when the string param is a macro expansion and the
1924 // format is either NSString or CFString. This is a hack to prevent
1925 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
1926 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupasdc170202012-05-04 21:08:08 +00001927 if (Type == FST_NSString &&
1928 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith831421f2012-06-25 20:30:08 +00001929 return false;
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00001930
Chris Lattner655f1412009-04-29 04:59:47 +00001931 // If there are no arguments specified, warn with -Wformat-security, otherwise
1932 // warn only with -Wformat-nonliteral.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001933 if (Args.size() == format_idx+1)
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001934 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001935 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00001936 << OrigFormatExpr->getSourceRange();
1937 else
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001938 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001939 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00001940 << OrigFormatExpr->getSourceRange();
Richard Smith831421f2012-06-25 20:30:08 +00001941 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001942}
Ted Kremenek71895b92007-08-14 17:39:48 +00001943
Ted Kremeneke0e53132010-01-28 23:39:18 +00001944namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00001945class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1946protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001947 Sema &S;
1948 const StringLiteral *FExpr;
1949 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001950 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001951 const unsigned NumDataArgs;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001952 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001953 const bool HasVAListArg;
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001954 ArrayRef<const Expr *> Args;
Ted Kremenek0d277352010-01-29 01:06:55 +00001955 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001956 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00001957 bool usesPositionalArgs;
1958 bool atFirstArg;
Richard Trieu55733de2011-10-28 00:41:25 +00001959 bool inFunctionCall;
Jordan Roseddcfbc92012-07-19 18:10:23 +00001960 Sema::VariadicCallType CallType;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001961public:
Ted Kremenek826a3452010-07-16 02:11:22 +00001962 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00001963 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00001964 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001965 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001966 unsigned formatIdx, bool inFunctionCall,
1967 Sema::VariadicCallType callType)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001968 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose50687312012-06-04 23:52:23 +00001969 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
1970 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001971 Args(Args), FormatIdx(formatIdx),
Richard Trieu55733de2011-10-28 00:41:25 +00001972 usesPositionalArgs(false), atFirstArg(true),
Jordan Roseddcfbc92012-07-19 18:10:23 +00001973 inFunctionCall(inFunctionCall), CallType(callType) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001974 CoveredArgs.resize(numDataArgs);
1975 CoveredArgs.reset();
1976 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001977
Ted Kremenek07d161f2010-01-29 01:50:07 +00001978 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001979
Ted Kremenek826a3452010-07-16 02:11:22 +00001980 void HandleIncompleteSpecifier(const char *startSpecifier,
1981 unsigned specifierLen);
Hans Wennborg76517422012-02-22 10:17:01 +00001982
Jordan Rosebbb6bb42012-09-08 04:00:03 +00001983 void HandleInvalidLengthModifier(
1984 const analyze_format_string::FormatSpecifier &FS,
1985 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose8be066e2012-09-08 04:00:12 +00001986 const char *startSpecifier, unsigned specifierLen, unsigned DiagID);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00001987
Hans Wennborg76517422012-02-22 10:17:01 +00001988 void HandleNonStandardLengthModifier(
Jordan Rose8be066e2012-09-08 04:00:12 +00001989 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborg76517422012-02-22 10:17:01 +00001990 const char *startSpecifier, unsigned specifierLen);
1991
1992 void HandleNonStandardConversionSpecifier(
1993 const analyze_format_string::ConversionSpecifier &CS,
1994 const char *startSpecifier, unsigned specifierLen);
1995
Hans Wennborgf8562642012-03-09 10:10:54 +00001996 virtual void HandlePosition(const char *startPos, unsigned posLen);
1997
Ted Kremenekefaff192010-02-27 01:41:03 +00001998 virtual void HandleInvalidPosition(const char *startSpecifier,
1999 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00002000 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00002001
2002 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
2003
Ted Kremeneke0e53132010-01-28 23:39:18 +00002004 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002005
Richard Trieu55733de2011-10-28 00:41:25 +00002006 template <typename Range>
2007 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2008 const Expr *ArgumentExpr,
2009 PartialDiagnostic PDiag,
2010 SourceLocation StringLoc,
2011 bool IsStringLocation, Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002012 ArrayRef<FixItHint> Fixit = ArrayRef<FixItHint>());
Richard Trieu55733de2011-10-28 00:41:25 +00002013
Ted Kremenek826a3452010-07-16 02:11:22 +00002014protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002015 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2016 const char *startSpec,
2017 unsigned specifierLen,
2018 const char *csStart, unsigned csLen);
Richard Trieu55733de2011-10-28 00:41:25 +00002019
2020 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2021 const char *startSpec,
2022 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002023
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002024 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00002025 CharSourceRange getSpecifierRange(const char *startSpecifier,
2026 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002027 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002028
Ted Kremenek0d277352010-01-29 01:06:55 +00002029 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00002030
2031 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2032 const analyze_format_string::ConversionSpecifier &CS,
2033 const char *startSpecifier, unsigned specifierLen,
2034 unsigned argIndex);
Richard Trieu55733de2011-10-28 00:41:25 +00002035
2036 template <typename Range>
2037 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2038 bool IsStringLocation, Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002039 ArrayRef<FixItHint> Fixit = ArrayRef<FixItHint>());
Richard Trieu55733de2011-10-28 00:41:25 +00002040
2041 void CheckPositionalAndNonpositionalArgs(
2042 const analyze_format_string::FormatSpecifier *FS);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002043};
2044}
2045
Ted Kremenek826a3452010-07-16 02:11:22 +00002046SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00002047 return OrigFormatExpr->getSourceRange();
2048}
2049
Ted Kremenek826a3452010-07-16 02:11:22 +00002050CharSourceRange CheckFormatHandler::
2051getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002052 SourceLocation Start = getLocationOfByte(startSpecifier);
2053 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2054
2055 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002056 End = End.getLocWithOffset(1);
Tom Care45f9b7e2010-06-21 21:21:01 +00002057
2058 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002059}
2060
Ted Kremenek826a3452010-07-16 02:11:22 +00002061SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002062 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002063}
2064
Ted Kremenek826a3452010-07-16 02:11:22 +00002065void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2066 unsigned specifierLen){
Richard Trieu55733de2011-10-28 00:41:25 +00002067 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2068 getLocationOfByte(startSpecifier),
2069 /*IsStringLocation*/true,
2070 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek808015a2010-01-29 03:16:21 +00002071}
2072
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002073void CheckFormatHandler::HandleInvalidLengthModifier(
2074 const analyze_format_string::FormatSpecifier &FS,
2075 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose8be066e2012-09-08 04:00:12 +00002076 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002077 using namespace analyze_format_string;
2078
2079 const LengthModifier &LM = FS.getLengthModifier();
2080 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2081
2082 // See if we know how to fix this length modifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002083 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002084 if (FixedLM) {
Jordan Rose8be066e2012-09-08 04:00:12 +00002085 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002086 getLocationOfByte(LM.getStart()),
2087 /*IsStringLocation*/true,
2088 getSpecifierRange(startSpecifier, specifierLen));
2089
2090 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2091 << FixedLM->toString()
2092 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2093
2094 } else {
Jordan Rose8be066e2012-09-08 04:00:12 +00002095 FixItHint Hint;
2096 if (DiagID == diag::warn_format_nonsensical_length)
2097 Hint = FixItHint::CreateRemoval(LMRange);
2098
2099 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002100 getLocationOfByte(LM.getStart()),
2101 /*IsStringLocation*/true,
2102 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose8be066e2012-09-08 04:00:12 +00002103 Hint);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002104 }
2105}
2106
Hans Wennborg76517422012-02-22 10:17:01 +00002107void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose8be066e2012-09-08 04:00:12 +00002108 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborg76517422012-02-22 10:17:01 +00002109 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose8be066e2012-09-08 04:00:12 +00002110 using namespace analyze_format_string;
2111
2112 const LengthModifier &LM = FS.getLengthModifier();
2113 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2114
2115 // See if we know how to fix this length modifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002116 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose8be066e2012-09-08 04:00:12 +00002117 if (FixedLM) {
2118 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2119 << LM.toString() << 0,
2120 getLocationOfByte(LM.getStart()),
2121 /*IsStringLocation*/true,
2122 getSpecifierRange(startSpecifier, specifierLen));
2123
2124 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2125 << FixedLM->toString()
2126 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2127
2128 } else {
2129 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2130 << LM.toString() << 0,
2131 getLocationOfByte(LM.getStart()),
2132 /*IsStringLocation*/true,
2133 getSpecifierRange(startSpecifier, specifierLen));
2134 }
Hans Wennborg76517422012-02-22 10:17:01 +00002135}
2136
2137void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2138 const analyze_format_string::ConversionSpecifier &CS,
2139 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose670941c2012-09-13 02:11:15 +00002140 using namespace analyze_format_string;
2141
2142 // See if we know how to fix this conversion specifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002143 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose670941c2012-09-13 02:11:15 +00002144 if (FixedCS) {
2145 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2146 << CS.toString() << /*conversion specifier*/1,
2147 getLocationOfByte(CS.getStart()),
2148 /*IsStringLocation*/true,
2149 getSpecifierRange(startSpecifier, specifierLen));
2150
2151 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2152 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2153 << FixedCS->toString()
2154 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2155 } else {
2156 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2157 << CS.toString() << /*conversion specifier*/1,
2158 getLocationOfByte(CS.getStart()),
2159 /*IsStringLocation*/true,
2160 getSpecifierRange(startSpecifier, specifierLen));
2161 }
Hans Wennborg76517422012-02-22 10:17:01 +00002162}
2163
Hans Wennborgf8562642012-03-09 10:10:54 +00002164void CheckFormatHandler::HandlePosition(const char *startPos,
2165 unsigned posLen) {
2166 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2167 getLocationOfByte(startPos),
2168 /*IsStringLocation*/true,
2169 getSpecifierRange(startPos, posLen));
2170}
2171
Ted Kremenekefaff192010-02-27 01:41:03 +00002172void
Ted Kremenek826a3452010-07-16 02:11:22 +00002173CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2174 analyze_format_string::PositionContext p) {
Richard Trieu55733de2011-10-28 00:41:25 +00002175 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2176 << (unsigned) p,
2177 getLocationOfByte(startPos), /*IsStringLocation*/true,
2178 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002179}
2180
Ted Kremenek826a3452010-07-16 02:11:22 +00002181void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00002182 unsigned posLen) {
Richard Trieu55733de2011-10-28 00:41:25 +00002183 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2184 getLocationOfByte(startPos),
2185 /*IsStringLocation*/true,
2186 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002187}
2188
Ted Kremenek826a3452010-07-16 02:11:22 +00002189void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose50687312012-06-04 23:52:23 +00002190 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0c069442011-03-15 21:18:48 +00002191 // The presence of a null character is likely an error.
Richard Trieu55733de2011-10-28 00:41:25 +00002192 EmitFormatDiagnostic(
2193 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2194 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2195 getFormatStringRange());
Ted Kremenek0c069442011-03-15 21:18:48 +00002196 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002197}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002198
Jordan Rose48716662012-07-19 18:10:08 +00002199// Note that this may return NULL if there was an error parsing or building
2200// one of the argument expressions.
Ted Kremenek826a3452010-07-16 02:11:22 +00002201const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002202 return Args[FirstDataArg + i];
Ted Kremenek826a3452010-07-16 02:11:22 +00002203}
2204
2205void CheckFormatHandler::DoneProcessing() {
2206 // Does the number of data arguments exceed the number of
2207 // format conversions in the format string?
2208 if (!HasVAListArg) {
2209 // Find any arguments that weren't covered.
2210 CoveredArgs.flip();
2211 signed notCoveredArg = CoveredArgs.find_first();
2212 if (notCoveredArg >= 0) {
2213 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose48716662012-07-19 18:10:08 +00002214 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2215 SourceLocation Loc = E->getLocStart();
2216 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2217 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2218 Loc, /*IsStringLocation*/false,
2219 getFormatStringRange());
2220 }
Bob Wilsonc03f2df2012-05-03 19:47:19 +00002221 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002222 }
2223 }
2224}
2225
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002226bool
2227CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2228 SourceLocation Loc,
2229 const char *startSpec,
2230 unsigned specifierLen,
2231 const char *csStart,
2232 unsigned csLen) {
2233
2234 bool keepGoing = true;
2235 if (argIndex < NumDataArgs) {
2236 // Consider the argument coverered, even though the specifier doesn't
2237 // make sense.
2238 CoveredArgs.set(argIndex);
2239 }
2240 else {
2241 // If argIndex exceeds the number of data arguments we
2242 // don't issue a warning because that is just a cascade of warnings (and
2243 // they may have intended '%%' anyway). We don't want to continue processing
2244 // the format string after this point, however, as we will like just get
2245 // gibberish when trying to match arguments.
2246 keepGoing = false;
2247 }
2248
Richard Trieu55733de2011-10-28 00:41:25 +00002249 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2250 << StringRef(csStart, csLen),
2251 Loc, /*IsStringLocation*/true,
2252 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002253
2254 return keepGoing;
2255}
2256
Richard Trieu55733de2011-10-28 00:41:25 +00002257void
2258CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2259 const char *startSpec,
2260 unsigned specifierLen) {
2261 EmitFormatDiagnostic(
2262 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2263 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2264}
2265
Ted Kremenek666a1972010-07-26 19:45:42 +00002266bool
2267CheckFormatHandler::CheckNumArgs(
2268 const analyze_format_string::FormatSpecifier &FS,
2269 const analyze_format_string::ConversionSpecifier &CS,
2270 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2271
2272 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002273 PartialDiagnostic PDiag = FS.usesPositionalArg()
2274 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2275 << (argIndex+1) << NumDataArgs)
2276 : S.PDiag(diag::warn_printf_insufficient_data_args);
2277 EmitFormatDiagnostic(
2278 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2279 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek666a1972010-07-26 19:45:42 +00002280 return false;
2281 }
2282 return true;
2283}
2284
Richard Trieu55733de2011-10-28 00:41:25 +00002285template<typename Range>
2286void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2287 SourceLocation Loc,
2288 bool IsStringLocation,
2289 Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002290 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002291 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu55733de2011-10-28 00:41:25 +00002292 Loc, IsStringLocation, StringRange, FixIt);
2293}
2294
2295/// \brief If the format string is not within the funcion call, emit a note
2296/// so that the function call and string are in diagnostic messages.
2297///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00002298/// \param InFunctionCall if true, the format string is within the function
Richard Trieu55733de2011-10-28 00:41:25 +00002299/// call and only one diagnostic message will be produced. Otherwise, an
2300/// extra note will be emitted pointing to location of the format string.
2301///
2302/// \param ArgumentExpr the expression that is passed as the format string
2303/// argument in the function call. Used for getting locations when two
2304/// diagnostics are emitted.
2305///
2306/// \param PDiag the callee should already have provided any strings for the
2307/// diagnostic message. This function only adds locations and fixits
2308/// to diagnostics.
2309///
2310/// \param Loc primary location for diagnostic. If two diagnostics are
2311/// required, one will be at Loc and a new SourceLocation will be created for
2312/// the other one.
2313///
2314/// \param IsStringLocation if true, Loc points to the format string should be
2315/// used for the note. Otherwise, Loc points to the argument list and will
2316/// be used with PDiag.
2317///
2318/// \param StringRange some or all of the string to highlight. This is
2319/// templated so it can accept either a CharSourceRange or a SourceRange.
2320///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00002321/// \param FixIt optional fix it hint for the format string.
Richard Trieu55733de2011-10-28 00:41:25 +00002322template<typename Range>
2323void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2324 const Expr *ArgumentExpr,
2325 PartialDiagnostic PDiag,
2326 SourceLocation Loc,
2327 bool IsStringLocation,
2328 Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002329 ArrayRef<FixItHint> FixIt) {
2330 if (InFunctionCall) {
2331 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2332 D << StringRange;
2333 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2334 I != E; ++I) {
2335 D << *I;
2336 }
2337 } else {
Richard Trieu55733de2011-10-28 00:41:25 +00002338 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2339 << ArgumentExpr->getSourceRange();
Jordan Roseec087352012-09-05 22:56:26 +00002340
2341 const Sema::SemaDiagnosticBuilder &Note =
2342 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2343 diag::note_format_string_defined);
2344
2345 Note << StringRange;
2346 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2347 I != E; ++I) {
2348 Note << *I;
2349 }
Richard Trieu55733de2011-10-28 00:41:25 +00002350 }
2351}
2352
Ted Kremenek826a3452010-07-16 02:11:22 +00002353//===--- CHECK: Printf format string checking ------------------------------===//
2354
2355namespace {
2356class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose50687312012-06-04 23:52:23 +00002357 bool ObjCContext;
Ted Kremenek826a3452010-07-16 02:11:22 +00002358public:
2359 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2360 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002361 unsigned numDataArgs, bool isObjC,
Ted Kremenek826a3452010-07-16 02:11:22 +00002362 const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002363 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002364 unsigned formatIdx, bool inFunctionCall,
2365 Sema::VariadicCallType CallType)
Ted Kremenek826a3452010-07-16 02:11:22 +00002366 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002367 numDataArgs, beg, hasVAListArg, Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002368 formatIdx, inFunctionCall, CallType), ObjCContext(isObjC)
2369 {}
2370
Ted Kremenek826a3452010-07-16 02:11:22 +00002371
2372 bool HandleInvalidPrintfConversionSpecifier(
2373 const analyze_printf::PrintfSpecifier &FS,
2374 const char *startSpecifier,
2375 unsigned specifierLen);
2376
2377 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2378 const char *startSpecifier,
2379 unsigned specifierLen);
Richard Smith831421f2012-06-25 20:30:08 +00002380 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2381 const char *StartSpecifier,
2382 unsigned SpecifierLen,
2383 const Expr *E);
2384
Ted Kremenek826a3452010-07-16 02:11:22 +00002385 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2386 const char *startSpecifier, unsigned specifierLen);
2387 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2388 const analyze_printf::OptionalAmount &Amt,
2389 unsigned type,
2390 const char *startSpecifier, unsigned specifierLen);
2391 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2392 const analyze_printf::OptionalFlag &flag,
2393 const char *startSpecifier, unsigned specifierLen);
2394 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2395 const analyze_printf::OptionalFlag &ignoredFlag,
2396 const analyze_printf::OptionalFlag &flag,
2397 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgf3749f42012-08-07 08:11:26 +00002398 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith831421f2012-06-25 20:30:08 +00002399 const Expr *E, const CharSourceRange &CSR);
2400
Ted Kremenek826a3452010-07-16 02:11:22 +00002401};
2402}
2403
2404bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2405 const analyze_printf::PrintfSpecifier &FS,
2406 const char *startSpecifier,
2407 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002408 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002409 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002410
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002411 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2412 getLocationOfByte(CS.getStart()),
2413 startSpecifier, specifierLen,
2414 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00002415}
2416
Ted Kremenek826a3452010-07-16 02:11:22 +00002417bool CheckPrintfHandler::HandleAmount(
2418 const analyze_format_string::OptionalAmount &Amt,
2419 unsigned k, const char *startSpecifier,
2420 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002421
2422 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002423 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002424 unsigned argIndex = Amt.getArgIndex();
2425 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002426 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2427 << k,
2428 getLocationOfByte(Amt.getStart()),
2429 /*IsStringLocation*/true,
2430 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002431 // Don't do any more checking. We will just emit
2432 // spurious errors.
2433 return false;
2434 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002435
Ted Kremenek0d277352010-01-29 01:06:55 +00002436 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00002437 // Although not in conformance with C99, we also allow the argument to be
2438 // an 'unsigned int' as that is a reasonably safe case. GCC also
2439 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002440 CoveredArgs.set(argIndex);
2441 const Expr *Arg = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00002442 if (!Arg)
2443 return false;
2444
Ted Kremenek0d277352010-01-29 01:06:55 +00002445 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002446
Hans Wennborgf3749f42012-08-07 08:11:26 +00002447 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
2448 assert(AT.isValid());
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002449
Hans Wennborgf3749f42012-08-07 08:11:26 +00002450 if (!AT.matchesType(S.Context, T)) {
Richard Trieu55733de2011-10-28 00:41:25 +00002451 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgf3749f42012-08-07 08:11:26 +00002452 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu55733de2011-10-28 00:41:25 +00002453 << T << Arg->getSourceRange(),
2454 getLocationOfByte(Amt.getStart()),
2455 /*IsStringLocation*/true,
2456 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002457 // Don't do any more checking. We will just emit
2458 // spurious errors.
2459 return false;
2460 }
2461 }
2462 }
2463 return true;
2464}
Ted Kremenek0d277352010-01-29 01:06:55 +00002465
Tom Caree4ee9662010-06-17 19:00:27 +00002466void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00002467 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002468 const analyze_printf::OptionalAmount &Amt,
2469 unsigned type,
2470 const char *startSpecifier,
2471 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002472 const analyze_printf::PrintfConversionSpecifier &CS =
2473 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00002474
Richard Trieu55733de2011-10-28 00:41:25 +00002475 FixItHint fixit =
2476 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2477 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2478 Amt.getConstantLength()))
2479 : FixItHint();
2480
2481 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2482 << type << CS.toString(),
2483 getLocationOfByte(Amt.getStart()),
2484 /*IsStringLocation*/true,
2485 getSpecifierRange(startSpecifier, specifierLen),
2486 fixit);
Tom Caree4ee9662010-06-17 19:00:27 +00002487}
2488
Ted Kremenek826a3452010-07-16 02:11:22 +00002489void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002490 const analyze_printf::OptionalFlag &flag,
2491 const char *startSpecifier,
2492 unsigned specifierLen) {
2493 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002494 const analyze_printf::PrintfConversionSpecifier &CS =
2495 FS.getConversionSpecifier();
Richard Trieu55733de2011-10-28 00:41:25 +00002496 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2497 << flag.toString() << CS.toString(),
2498 getLocationOfByte(flag.getPosition()),
2499 /*IsStringLocation*/true,
2500 getSpecifierRange(startSpecifier, specifierLen),
2501 FixItHint::CreateRemoval(
2502 getSpecifierRange(flag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002503}
2504
2505void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00002506 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002507 const analyze_printf::OptionalFlag &ignoredFlag,
2508 const analyze_printf::OptionalFlag &flag,
2509 const char *startSpecifier,
2510 unsigned specifierLen) {
2511 // Warn about ignored flag with a fixit removal.
Richard Trieu55733de2011-10-28 00:41:25 +00002512 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2513 << ignoredFlag.toString() << flag.toString(),
2514 getLocationOfByte(ignoredFlag.getPosition()),
2515 /*IsStringLocation*/true,
2516 getSpecifierRange(startSpecifier, specifierLen),
2517 FixItHint::CreateRemoval(
2518 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002519}
2520
Richard Smith831421f2012-06-25 20:30:08 +00002521// Determines if the specified is a C++ class or struct containing
2522// a member with the specified name and kind (e.g. a CXXMethodDecl named
2523// "c_str()").
2524template<typename MemberKind>
2525static llvm::SmallPtrSet<MemberKind*, 1>
2526CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2527 const RecordType *RT = Ty->getAs<RecordType>();
2528 llvm::SmallPtrSet<MemberKind*, 1> Results;
2529
2530 if (!RT)
2531 return Results;
2532 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
2533 if (!RD)
2534 return Results;
2535
2536 LookupResult R(S, &S.PP.getIdentifierTable().get(Name), SourceLocation(),
2537 Sema::LookupMemberName);
2538
2539 // We just need to include all members of the right kind turned up by the
2540 // filter, at this point.
2541 if (S.LookupQualifiedName(R, RT->getDecl()))
2542 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2543 NamedDecl *decl = (*I)->getUnderlyingDecl();
2544 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
2545 Results.insert(FK);
2546 }
2547 return Results;
2548}
2549
2550// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgf3749f42012-08-07 08:11:26 +00002551// better diagnostic if so. AT is assumed to be valid.
Richard Smith831421f2012-06-25 20:30:08 +00002552// Returns true when a c_str() conversion method is found.
2553bool CheckPrintfHandler::checkForCStrMembers(
Hans Wennborgf3749f42012-08-07 08:11:26 +00002554 const analyze_printf::ArgType &AT, const Expr *E,
Richard Smith831421f2012-06-25 20:30:08 +00002555 const CharSourceRange &CSR) {
2556 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2557
2558 MethodSet Results =
2559 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
2560
2561 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2562 MI != ME; ++MI) {
2563 const CXXMethodDecl *Method = *MI;
2564 if (Method->getNumParams() == 0 &&
Hans Wennborgf3749f42012-08-07 08:11:26 +00002565 AT.matchesType(S.Context, Method->getResultType())) {
Richard Smith831421f2012-06-25 20:30:08 +00002566 // FIXME: Suggest parens if the expression needs them.
2567 SourceLocation EndLoc =
2568 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd());
2569 S.Diag(E->getLocStart(), diag::note_printf_c_str)
2570 << "c_str()"
2571 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
2572 return true;
2573 }
2574 }
2575
2576 return false;
2577}
2578
Ted Kremeneke0e53132010-01-28 23:39:18 +00002579bool
Ted Kremenek826a3452010-07-16 02:11:22 +00002580CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002581 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00002582 const char *startSpecifier,
2583 unsigned specifierLen) {
2584
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002585 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00002586 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002587 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00002588
Ted Kremenekbaa40062010-07-19 22:01:06 +00002589 if (FS.consumesDataArgument()) {
2590 if (atFirstArg) {
2591 atFirstArg = false;
2592 usesPositionalArgs = FS.usesPositionalArg();
2593 }
2594 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002595 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2596 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002597 return false;
2598 }
Ted Kremenek0d277352010-01-29 01:06:55 +00002599 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002600
Ted Kremenekefaff192010-02-27 01:41:03 +00002601 // First check if the field width, precision, and conversion specifier
2602 // have matching data arguments.
2603 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2604 startSpecifier, specifierLen)) {
2605 return false;
2606 }
2607
2608 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2609 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002610 return false;
2611 }
2612
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002613 if (!CS.consumesDataArgument()) {
2614 // FIXME: Technically specifying a precision or field width here
2615 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002616 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002617 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002618
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002619 // Consume the argument.
2620 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00002621 if (argIndex < NumDataArgs) {
2622 // The check to see if the argIndex is valid will come later.
2623 // We set the bit here because we may exit early from this
2624 // function if we encounter some other error.
2625 CoveredArgs.set(argIndex);
2626 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002627
2628 // Check for using an Objective-C specific conversion specifier
2629 // in a non-ObjC literal.
Jordan Rose50687312012-06-04 23:52:23 +00002630 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002631 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2632 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002633 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002634
Tom Caree4ee9662010-06-17 19:00:27 +00002635 // Check for invalid use of field width
2636 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002637 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00002638 startSpecifier, specifierLen);
2639 }
2640
2641 // Check for invalid use of precision
2642 if (!FS.hasValidPrecision()) {
2643 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
2644 startSpecifier, specifierLen);
2645 }
2646
2647 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00002648 if (!FS.hasValidThousandsGroupingPrefix())
2649 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002650 if (!FS.hasValidLeadingZeros())
2651 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
2652 if (!FS.hasValidPlusPrefix())
2653 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00002654 if (!FS.hasValidSpacePrefix())
2655 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002656 if (!FS.hasValidAlternativeForm())
2657 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
2658 if (!FS.hasValidLeftJustified())
2659 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
2660
2661 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00002662 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
2663 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
2664 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002665 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
2666 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
2667 startSpecifier, specifierLen);
2668
2669 // Check the length modifier is valid with the given conversion specifier.
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002670 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose8be066e2012-09-08 04:00:12 +00002671 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
2672 diag::warn_format_nonsensical_length);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002673 else if (!FS.hasStandardLengthModifier())
Jordan Rose8be066e2012-09-08 04:00:12 +00002674 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002675 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose8be066e2012-09-08 04:00:12 +00002676 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
2677 diag::warn_format_non_standard_conversion_spec);
Tom Caree4ee9662010-06-17 19:00:27 +00002678
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002679 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
2680 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
2681
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002682 // The remaining checks depend on the data arguments.
2683 if (HasVAListArg)
2684 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002685
Ted Kremenek666a1972010-07-26 19:45:42 +00002686 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002687 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002688
Jordan Rose48716662012-07-19 18:10:08 +00002689 const Expr *Arg = getDataArg(argIndex);
2690 if (!Arg)
2691 return true;
2692
2693 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith831421f2012-06-25 20:30:08 +00002694}
2695
Jordan Roseec087352012-09-05 22:56:26 +00002696static bool requiresParensToAddCast(const Expr *E) {
2697 // FIXME: We should have a general way to reason about operator
2698 // precedence and whether parens are actually needed here.
2699 // Take care of a few common cases where they aren't.
2700 const Expr *Inside = E->IgnoreImpCasts();
2701 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
2702 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
2703
2704 switch (Inside->getStmtClass()) {
2705 case Stmt::ArraySubscriptExprClass:
2706 case Stmt::CallExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00002707 case Stmt::CharacterLiteralClass:
2708 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00002709 case Stmt::DeclRefExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00002710 case Stmt::FloatingLiteralClass:
2711 case Stmt::IntegerLiteralClass:
Jordan Roseec087352012-09-05 22:56:26 +00002712 case Stmt::MemberExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00002713 case Stmt::ObjCArrayLiteralClass:
2714 case Stmt::ObjCBoolLiteralExprClass:
2715 case Stmt::ObjCBoxedExprClass:
2716 case Stmt::ObjCDictionaryLiteralClass:
2717 case Stmt::ObjCEncodeExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00002718 case Stmt::ObjCIvarRefExprClass:
2719 case Stmt::ObjCMessageExprClass:
2720 case Stmt::ObjCPropertyRefExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00002721 case Stmt::ObjCStringLiteralClass:
2722 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00002723 case Stmt::ParenExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00002724 case Stmt::StringLiteralClass:
Jordan Roseec087352012-09-05 22:56:26 +00002725 case Stmt::UnaryOperatorClass:
2726 return false;
2727 default:
2728 return true;
2729 }
2730}
2731
Richard Smith831421f2012-06-25 20:30:08 +00002732bool
2733CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2734 const char *StartSpecifier,
2735 unsigned SpecifierLen,
2736 const Expr *E) {
2737 using namespace analyze_format_string;
2738 using namespace analyze_printf;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002739 // Now type check the data expression that matches the
2740 // format specifier.
Hans Wennborgf3749f42012-08-07 08:11:26 +00002741 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
2742 ObjCContext);
Jordan Rose614a8652012-09-05 22:56:19 +00002743 if (!AT.isValid())
2744 return true;
Jordan Roseec087352012-09-05 22:56:26 +00002745
Jordan Rose448ac3e2012-12-05 18:44:40 +00002746 QualType ExprTy = E->getType();
2747 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose614a8652012-09-05 22:56:19 +00002748 return true;
Jordan Roseee0259d2012-06-04 22:48:57 +00002749
Jordan Rose614a8652012-09-05 22:56:19 +00002750 // Look through argument promotions for our error message's reported type.
2751 // This includes the integral and floating promotions, but excludes array
2752 // and function pointer decay; seeing that an argument intended to be a
2753 // string has type 'char [6]' is probably more confusing than 'char *'.
2754 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2755 if (ICE->getCastKind() == CK_IntegralCast ||
2756 ICE->getCastKind() == CK_FloatingCast) {
2757 E = ICE->getSubExpr();
Jordan Rose448ac3e2012-12-05 18:44:40 +00002758 ExprTy = E->getType();
Jordan Rose614a8652012-09-05 22:56:19 +00002759
2760 // Check if we didn't match because of an implicit cast from a 'char'
2761 // or 'short' to an 'int'. This is done because printf is a varargs
2762 // function.
2763 if (ICE->getType() == S.Context.IntTy ||
2764 ICE->getType() == S.Context.UnsignedIntTy) {
2765 // All further checking is done on the subexpression.
Jordan Rose448ac3e2012-12-05 18:44:40 +00002766 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose614a8652012-09-05 22:56:19 +00002767 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00002768 }
Jordan Roseee0259d2012-06-04 22:48:57 +00002769 }
Jordan Rose448ac3e2012-12-05 18:44:40 +00002770 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
2771 // Special case for 'a', which has type 'int' in C.
2772 // Note, however, that we do /not/ want to treat multibyte constants like
2773 // 'MooV' as characters! This form is deprecated but still exists.
2774 if (ExprTy == S.Context.IntTy)
2775 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
2776 ExprTy = S.Context.CharTy;
Jordan Rose614a8652012-09-05 22:56:19 +00002777 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002778
Jordan Rose2cd34402012-12-05 18:44:49 +00002779 // %C in an Objective-C context prints a unichar, not a wchar_t.
2780 // If the argument is an integer of some kind, believe the %C and suggest
2781 // a cast instead of changing the conversion specifier.
Jordan Rose448ac3e2012-12-05 18:44:40 +00002782 QualType IntendedTy = ExprTy;
Jordan Rose2cd34402012-12-05 18:44:49 +00002783 if (ObjCContext &&
2784 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
2785 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
2786 !ExprTy->isCharType()) {
2787 // 'unichar' is defined as a typedef of unsigned short, but we should
2788 // prefer using the typedef if it is visible.
2789 IntendedTy = S.Context.UnsignedShortTy;
2790
2791 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
2792 Sema::LookupOrdinaryName);
2793 if (S.LookupName(Result, S.getCurScope())) {
2794 NamedDecl *ND = Result.getFoundDecl();
2795 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
2796 if (TD->getUnderlyingType() == IntendedTy)
2797 IntendedTy = S.Context.getTypedefType(TD);
2798 }
2799 }
2800 }
2801
2802 // Special-case some of Darwin's platform-independence types by suggesting
2803 // casts to primitive types that are known to be large enough.
2804 bool ShouldNotPrintDirectly = false;
Jordan Roseec087352012-09-05 22:56:26 +00002805 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Ted Kremenek6edb0292013-03-25 22:28:37 +00002806 // Use a 'while' to peel off layers of typedefs.
2807 QualType TyTy = IntendedTy;
2808 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
Jordan Roseec087352012-09-05 22:56:26 +00002809 StringRef Name = UserTy->getDecl()->getName();
Jordan Rose2cd34402012-12-05 18:44:49 +00002810 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Jordan Roseec087352012-09-05 22:56:26 +00002811 .Case("NSInteger", S.Context.LongTy)
2812 .Case("NSUInteger", S.Context.UnsignedLongTy)
2813 .Case("SInt32", S.Context.IntTy)
2814 .Case("UInt32", S.Context.UnsignedIntTy)
Jordan Rose2cd34402012-12-05 18:44:49 +00002815 .Default(QualType());
2816
2817 if (!CastTy.isNull()) {
2818 ShouldNotPrintDirectly = true;
2819 IntendedTy = CastTy;
Ted Kremenek6edb0292013-03-25 22:28:37 +00002820 break;
Jordan Rose2cd34402012-12-05 18:44:49 +00002821 }
Ted Kremenek6edb0292013-03-25 22:28:37 +00002822 TyTy = UserTy->desugar();
Jordan Roseec087352012-09-05 22:56:26 +00002823 }
2824 }
2825
Jordan Rose614a8652012-09-05 22:56:19 +00002826 // We may be able to offer a FixItHint if it is a supported type.
2827 PrintfSpecifier fixedFS = FS;
Jordan Roseec087352012-09-05 22:56:26 +00002828 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose614a8652012-09-05 22:56:19 +00002829 S.Context, ObjCContext);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002830
Jordan Rose614a8652012-09-05 22:56:19 +00002831 if (success) {
2832 // Get the fix string from the fixed format specifier
2833 SmallString<16> buf;
2834 llvm::raw_svector_ostream os(buf);
2835 fixedFS.toString(os);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002836
Jordan Roseec087352012-09-05 22:56:26 +00002837 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
2838
Jordan Rose2cd34402012-12-05 18:44:49 +00002839 if (IntendedTy == ExprTy) {
2840 // In this case, the specifier is wrong and should be changed to match
2841 // the argument.
2842 EmitFormatDiagnostic(
2843 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2844 << AT.getRepresentativeTypeName(S.Context) << IntendedTy
2845 << E->getSourceRange(),
2846 E->getLocStart(),
2847 /*IsStringLocation*/false,
2848 SpecRange,
2849 FixItHint::CreateReplacement(SpecRange, os.str()));
2850
2851 } else {
Jordan Roseec087352012-09-05 22:56:26 +00002852 // The canonical type for formatting this value is different from the
2853 // actual type of the expression. (This occurs, for example, with Darwin's
2854 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
2855 // should be printed as 'long' for 64-bit compatibility.)
2856 // Rather than emitting a normal format/argument mismatch, we want to
2857 // add a cast to the recommended type (and correct the format string
2858 // if necessary).
2859 SmallString<16> CastBuf;
2860 llvm::raw_svector_ostream CastFix(CastBuf);
2861 CastFix << "(";
2862 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
2863 CastFix << ")";
2864
2865 SmallVector<FixItHint,4> Hints;
2866 if (!AT.matchesType(S.Context, IntendedTy))
2867 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
2868
2869 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
2870 // If there's already a cast present, just replace it.
2871 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
2872 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
2873
2874 } else if (!requiresParensToAddCast(E)) {
2875 // If the expression has high enough precedence,
2876 // just write the C-style cast.
2877 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
2878 CastFix.str()));
2879 } else {
2880 // Otherwise, add parens around the expression as well as the cast.
2881 CastFix << "(";
2882 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
2883 CastFix.str()));
2884
2885 SourceLocation After = S.PP.getLocForEndOfToken(E->getLocEnd());
2886 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
2887 }
2888
Jordan Rose2cd34402012-12-05 18:44:49 +00002889 if (ShouldNotPrintDirectly) {
2890 // The expression has a type that should not be printed directly.
2891 // We extract the name from the typedef because we don't want to show
2892 // the underlying type in the diagnostic.
2893 StringRef Name = cast<TypedefType>(ExprTy)->getDecl()->getName();
Jordan Roseec087352012-09-05 22:56:26 +00002894
Jordan Rose2cd34402012-12-05 18:44:49 +00002895 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
2896 << Name << IntendedTy
2897 << E->getSourceRange(),
2898 E->getLocStart(), /*IsStringLocation=*/false,
2899 SpecRange, Hints);
2900 } else {
2901 // In this case, the expression could be printed using a different
2902 // specifier, but we've decided that the specifier is probably correct
2903 // and we should cast instead. Just use the normal warning message.
2904 EmitFormatDiagnostic(
2905 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2906 << AT.getRepresentativeTypeName(S.Context) << ExprTy
2907 << E->getSourceRange(),
2908 E->getLocStart(), /*IsStringLocation*/false,
2909 SpecRange, Hints);
2910 }
Jordan Roseec087352012-09-05 22:56:26 +00002911 }
Jordan Rose614a8652012-09-05 22:56:19 +00002912 } else {
2913 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
2914 SpecifierLen);
2915 // Since the warning for passing non-POD types to variadic functions
2916 // was deferred until now, we emit a warning for non-POD
2917 // arguments here.
Jordan Rose448ac3e2012-12-05 18:44:40 +00002918 if (S.isValidVarArgType(ExprTy) == Sema::VAK_Invalid) {
Jordan Rose614a8652012-09-05 22:56:19 +00002919 unsigned DiagKind;
Jordan Rose448ac3e2012-12-05 18:44:40 +00002920 if (ExprTy->isObjCObjectType())
Jordan Rose614a8652012-09-05 22:56:19 +00002921 DiagKind = diag::err_cannot_pass_objc_interface_to_vararg_format;
2922 else
2923 DiagKind = diag::warn_non_pod_vararg_with_format_string;
2924
2925 EmitFormatDiagnostic(
2926 S.PDiag(DiagKind)
Richard Smith80ad52f2013-01-02 11:42:31 +00002927 << S.getLangOpts().CPlusPlus11
Jordan Rose448ac3e2012-12-05 18:44:40 +00002928 << ExprTy
Jordan Rose614a8652012-09-05 22:56:19 +00002929 << CallType
2930 << AT.getRepresentativeTypeName(S.Context)
2931 << CSR
2932 << E->getSourceRange(),
2933 E->getLocStart(), /*IsStringLocation*/false, CSR);
2934
2935 checkForCStrMembers(AT, E, CSR);
2936 } else
Richard Trieu55733de2011-10-28 00:41:25 +00002937 EmitFormatDiagnostic(
2938 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Jordan Rose448ac3e2012-12-05 18:44:40 +00002939 << AT.getRepresentativeTypeName(S.Context) << ExprTy
Jordan Rose614a8652012-09-05 22:56:19 +00002940 << CSR
Richard Smith831421f2012-06-25 20:30:08 +00002941 << E->getSourceRange(),
Jordan Rose614a8652012-09-05 22:56:19 +00002942 E->getLocStart(), /*IsStringLocation*/false, CSR);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002943 }
2944
Ted Kremeneke0e53132010-01-28 23:39:18 +00002945 return true;
2946}
2947
Ted Kremenek826a3452010-07-16 02:11:22 +00002948//===--- CHECK: Scanf format string checking ------------------------------===//
2949
2950namespace {
2951class CheckScanfHandler : public CheckFormatHandler {
2952public:
2953 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
2954 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002955 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002956 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002957 unsigned formatIdx, bool inFunctionCall,
2958 Sema::VariadicCallType CallType)
Ted Kremenek826a3452010-07-16 02:11:22 +00002959 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002960 numDataArgs, beg, hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002961 Args, formatIdx, inFunctionCall, CallType)
Jordan Roseddcfbc92012-07-19 18:10:23 +00002962 {}
Ted Kremenek826a3452010-07-16 02:11:22 +00002963
2964 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
2965 const char *startSpecifier,
2966 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002967
2968 bool HandleInvalidScanfConversionSpecifier(
2969 const analyze_scanf::ScanfSpecifier &FS,
2970 const char *startSpecifier,
2971 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00002972
2973 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00002974};
Ted Kremenek07d161f2010-01-29 01:50:07 +00002975}
Ted Kremeneke0e53132010-01-28 23:39:18 +00002976
Ted Kremenekb7c21012010-07-16 18:28:03 +00002977void CheckScanfHandler::HandleIncompleteScanList(const char *start,
2978 const char *end) {
Richard Trieu55733de2011-10-28 00:41:25 +00002979 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
2980 getLocationOfByte(end), /*IsStringLocation*/true,
2981 getSpecifierRange(start, end - start));
Ted Kremenekb7c21012010-07-16 18:28:03 +00002982}
2983
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002984bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
2985 const analyze_scanf::ScanfSpecifier &FS,
2986 const char *startSpecifier,
2987 unsigned specifierLen) {
2988
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002989 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002990 FS.getConversionSpecifier();
2991
2992 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2993 getLocationOfByte(CS.getStart()),
2994 startSpecifier, specifierLen,
2995 CS.getStart(), CS.getLength());
2996}
2997
Ted Kremenek826a3452010-07-16 02:11:22 +00002998bool CheckScanfHandler::HandleScanfSpecifier(
2999 const analyze_scanf::ScanfSpecifier &FS,
3000 const char *startSpecifier,
3001 unsigned specifierLen) {
3002
3003 using namespace analyze_scanf;
3004 using namespace analyze_format_string;
3005
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003006 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00003007
Ted Kremenekbaa40062010-07-19 22:01:06 +00003008 // Handle case where '%' and '*' don't consume an argument. These shouldn't
3009 // be used to decide if we are using positional arguments consistently.
3010 if (FS.consumesDataArgument()) {
3011 if (atFirstArg) {
3012 atFirstArg = false;
3013 usesPositionalArgs = FS.usesPositionalArg();
3014 }
3015 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00003016 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3017 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00003018 return false;
3019 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003020 }
3021
3022 // Check if the field with is non-zero.
3023 const OptionalAmount &Amt = FS.getFieldWidth();
3024 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3025 if (Amt.getConstantAmount() == 0) {
3026 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3027 Amt.getConstantLength());
Richard Trieu55733de2011-10-28 00:41:25 +00003028 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3029 getLocationOfByte(Amt.getStart()),
3030 /*IsStringLocation*/true, R,
3031 FixItHint::CreateRemoval(R));
Ted Kremenek826a3452010-07-16 02:11:22 +00003032 }
3033 }
3034
3035 if (!FS.consumesDataArgument()) {
3036 // FIXME: Technically specifying a precision or field width here
3037 // makes no sense. Worth issuing a warning at some point.
3038 return true;
3039 }
3040
3041 // Consume the argument.
3042 unsigned argIndex = FS.getArgIndex();
3043 if (argIndex < NumDataArgs) {
3044 // The check to see if the argIndex is valid will come later.
3045 // We set the bit here because we may exit early from this
3046 // function if we encounter some other error.
3047 CoveredArgs.set(argIndex);
3048 }
3049
Ted Kremenek1e51c202010-07-20 20:04:47 +00003050 // Check the length modifier is valid with the given conversion specifier.
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003051 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose8be066e2012-09-08 04:00:12 +00003052 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3053 diag::warn_format_nonsensical_length);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003054 else if (!FS.hasStandardLengthModifier())
Jordan Rose8be066e2012-09-08 04:00:12 +00003055 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003056 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose8be066e2012-09-08 04:00:12 +00003057 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3058 diag::warn_format_non_standard_conversion_spec);
Hans Wennborg76517422012-02-22 10:17:01 +00003059
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003060 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3061 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3062
Ted Kremenek826a3452010-07-16 02:11:22 +00003063 // The remaining checks depend on the data arguments.
3064 if (HasVAListArg)
3065 return true;
3066
Ted Kremenek666a1972010-07-26 19:45:42 +00003067 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00003068 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00003069
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003070 // Check that the argument type matches the format specifier.
3071 const Expr *Ex = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00003072 if (!Ex)
3073 return true;
3074
Hans Wennborg58e1e542012-08-07 08:59:46 +00003075 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3076 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003077 ScanfSpecifier fixedFS = FS;
David Blaikie4e4d0842012-03-11 07:00:24 +00003078 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
Hans Wennborgbe6126a2012-02-15 09:59:46 +00003079 S.Context);
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003080
3081 if (success) {
3082 // Get the fix string from the fixed format specifier.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003083 SmallString<128> buf;
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003084 llvm::raw_svector_ostream os(buf);
3085 fixedFS.toString(os);
3086
3087 EmitFormatDiagnostic(
3088 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg58e1e542012-08-07 08:59:46 +00003089 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003090 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00003091 Ex->getLocStart(),
3092 /*IsStringLocation*/false,
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003093 getSpecifierRange(startSpecifier, specifierLen),
3094 FixItHint::CreateReplacement(
3095 getSpecifierRange(startSpecifier, specifierLen),
3096 os.str()));
3097 } else {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003098 EmitFormatDiagnostic(
3099 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg58e1e542012-08-07 08:59:46 +00003100 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003101 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00003102 Ex->getLocStart(),
3103 /*IsStringLocation*/false,
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003104 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003105 }
3106 }
3107
Ted Kremenek826a3452010-07-16 02:11:22 +00003108 return true;
3109}
3110
3111void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00003112 const Expr *OrigFormatExpr,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003113 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003114 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003115 unsigned firstDataArg, FormatStringType Type,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003116 bool inFunctionCall, VariadicCallType CallType) {
Ted Kremenek826a3452010-07-16 02:11:22 +00003117
Ted Kremeneke0e53132010-01-28 23:39:18 +00003118 // CHECK: is the format string a wide literal?
Richard Smithdf9ef1b2012-06-13 05:37:23 +00003119 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu55733de2011-10-28 00:41:25 +00003120 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003121 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00003122 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3123 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00003124 return;
3125 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003126
Ted Kremeneke0e53132010-01-28 23:39:18 +00003127 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner5f9e2722011-07-23 10:55:15 +00003128 StringRef StrRef = FExpr->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00003129 const char *Str = StrRef.data();
3130 unsigned StrLen = StrRef.size();
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003131 const unsigned numDataArgs = Args.size() - firstDataArg;
Ted Kremenek826a3452010-07-16 02:11:22 +00003132
Ted Kremeneke0e53132010-01-28 23:39:18 +00003133 // CHECK: empty format string?
Ted Kremenek4cd57912011-09-29 05:52:16 +00003134 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu55733de2011-10-28 00:41:25 +00003135 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003136 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00003137 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3138 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00003139 return;
3140 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003141
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003142 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek826a3452010-07-16 02:11:22 +00003143 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00003144 numDataArgs, (Type == FST_NSString),
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003145 Str, HasVAListArg, Args, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003146 inFunctionCall, CallType);
Ted Kremenek826a3452010-07-16 02:11:22 +00003147
Hans Wennborgd02deeb2011-12-15 10:25:47 +00003148 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose275b6f52012-09-13 02:11:03 +00003149 getLangOpts(),
3150 Context.getTargetInfo()))
Ted Kremenek826a3452010-07-16 02:11:22 +00003151 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003152 } else if (Type == FST_Scanf) {
Jordan Rose50687312012-06-04 23:52:23 +00003153 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003154 Str, HasVAListArg, Args, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003155 inFunctionCall, CallType);
Ted Kremenek826a3452010-07-16 02:11:22 +00003156
Hans Wennborgd02deeb2011-12-15 10:25:47 +00003157 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose275b6f52012-09-13 02:11:03 +00003158 getLangOpts(),
3159 Context.getTargetInfo()))
Ted Kremenek826a3452010-07-16 02:11:22 +00003160 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003161 } // TODO: handle other formats
Ted Kremenekce7024e2010-01-28 01:18:22 +00003162}
3163
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003164//===--- CHECK: Standard memory functions ---------------------------------===//
3165
Douglas Gregor2a053a32011-05-03 20:05:22 +00003166/// \brief Determine whether the given type is a dynamic class type (e.g.,
3167/// whether it has a vtable).
3168static bool isDynamicClassType(QualType T) {
3169 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3170 if (CXXRecordDecl *Definition = Record->getDefinition())
3171 if (Definition->isDynamicClass())
3172 return true;
3173
3174 return false;
3175}
3176
Chandler Carrutha72a12f2011-06-21 23:04:20 +00003177/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth000d4282011-06-16 09:09:40 +00003178/// otherwise returns NULL.
3179static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Webere4a1c642011-06-14 16:14:58 +00003180 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth000d4282011-06-16 09:09:40 +00003181 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3182 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
3183 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00003184
Chandler Carruth000d4282011-06-16 09:09:40 +00003185 return 0;
3186}
3187
Chandler Carrutha72a12f2011-06-21 23:04:20 +00003188/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth000d4282011-06-16 09:09:40 +00003189static QualType getSizeOfArgType(const Expr* E) {
3190 if (const UnaryExprOrTypeTraitExpr *SizeOf =
3191 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3192 if (SizeOf->getKind() == clang::UETT_SizeOf)
3193 return SizeOf->getTypeOfArgument();
3194
3195 return QualType();
Nico Webere4a1c642011-06-14 16:14:58 +00003196}
3197
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003198/// \brief Check for dangerous or invalid arguments to memset().
3199///
Chandler Carruth929f0132011-06-03 06:23:57 +00003200/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003201/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
3202/// function calls.
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003203///
3204/// \param Call The call expression to diagnose.
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003205void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks0a151a12012-01-17 00:37:07 +00003206 unsigned BId,
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003207 IdentifierInfo *FnName) {
Anna Zaks0a151a12012-01-17 00:37:07 +00003208 assert(BId != 0);
3209
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00003210 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor707a23e2011-06-16 17:56:04 +00003211 // we have enough arguments, and if not, abort further checking.
Anna Zaks0a151a12012-01-17 00:37:07 +00003212 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Webercda57822011-10-13 22:30:23 +00003213 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00003214 return;
3215
Anna Zaks0a151a12012-01-17 00:37:07 +00003216 unsigned LastArg = (BId == Builtin::BImemset ||
3217 BId == Builtin::BIstrndup ? 1 : 2);
3218 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Webercda57822011-10-13 22:30:23 +00003219 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth000d4282011-06-16 09:09:40 +00003220
3221 // We have special checking when the length is a sizeof expression.
3222 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
3223 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
3224 llvm::FoldingSetNodeID SizeOfArgID;
3225
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003226 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
3227 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00003228 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003229
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003230 QualType DestTy = Dest->getType();
3231 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
3232 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00003233
Chandler Carruth000d4282011-06-16 09:09:40 +00003234 // Never warn about void type pointers. This can be used to suppress
3235 // false positives.
3236 if (PointeeTy->isVoidType())
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003237 continue;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003238
Chandler Carruth000d4282011-06-16 09:09:40 +00003239 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
3240 // actually comparing the expressions for equality. Because computing the
3241 // expression IDs can be expensive, we only do this if the diagnostic is
3242 // enabled.
3243 if (SizeOfArg &&
3244 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
3245 SizeOfArg->getExprLoc())) {
3246 // We only compute IDs for expressions if the warning is enabled, and
3247 // cache the sizeof arg's ID.
3248 if (SizeOfArgID == llvm::FoldingSetNodeID())
3249 SizeOfArg->Profile(SizeOfArgID, Context, true);
3250 llvm::FoldingSetNodeID DestID;
3251 Dest->Profile(DestID, Context, true);
3252 if (DestID == SizeOfArgID) {
Nico Webercda57822011-10-13 22:30:23 +00003253 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
3254 // over sizeof(src) as well.
Chandler Carruth000d4282011-06-16 09:09:40 +00003255 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks6fcb3722012-05-30 00:34:21 +00003256 StringRef ReadableName = FnName->getName();
3257
Chandler Carruth000d4282011-06-16 09:09:40 +00003258 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaks90c78322012-05-30 23:14:52 +00003259 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth000d4282011-06-16 09:09:40 +00003260 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian7adf4172013-01-30 01:12:44 +00003261 if (!PointeeTy->isIncompleteType() &&
3262 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth000d4282011-06-16 09:09:40 +00003263 ActionIdx = 2; // If the pointee's size is sizeof(char),
3264 // suggest an explicit length.
Anna Zaks6fcb3722012-05-30 00:34:21 +00003265
3266 // If the function is defined as a builtin macro, do not show macro
3267 // expansion.
3268 SourceLocation SL = SizeOfArg->getExprLoc();
3269 SourceRange DSR = Dest->getSourceRange();
3270 SourceRange SSR = SizeOfArg->getSourceRange();
3271 SourceManager &SM = PP.getSourceManager();
3272
3273 if (SM.isMacroArgExpansion(SL)) {
3274 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
3275 SL = SM.getSpellingLoc(SL);
3276 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
3277 SM.getSpellingLoc(DSR.getEnd()));
3278 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
3279 SM.getSpellingLoc(SSR.getEnd()));
3280 }
3281
Anna Zaks90c78322012-05-30 23:14:52 +00003282 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth000d4282011-06-16 09:09:40 +00003283 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks6fcb3722012-05-30 00:34:21 +00003284 << ReadableName
Anna Zaks90c78322012-05-30 23:14:52 +00003285 << PointeeTy
3286 << DestTy
Anna Zaks6fcb3722012-05-30 00:34:21 +00003287 << DSR
Anna Zaks90c78322012-05-30 23:14:52 +00003288 << SSR);
3289 DiagRuntimeBehavior(SL, SizeOfArg,
3290 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
3291 << ActionIdx
3292 << SSR);
3293
Chandler Carruth000d4282011-06-16 09:09:40 +00003294 break;
3295 }
3296 }
3297
3298 // Also check for cases where the sizeof argument is the exact same
3299 // type as the memory argument, and where it points to a user-defined
3300 // record type.
3301 if (SizeOfArgTy != QualType()) {
3302 if (PointeeTy->isRecordType() &&
3303 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
3304 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
3305 PDiag(diag::warn_sizeof_pointer_type_memaccess)
3306 << FnName << SizeOfArgTy << ArgIdx
3307 << PointeeTy << Dest->getSourceRange()
3308 << LenExpr->getSourceRange());
3309 break;
3310 }
Nico Webere4a1c642011-06-14 16:14:58 +00003311 }
3312
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003313 // Always complain about dynamic classes.
Anna Zaks0a151a12012-01-17 00:37:07 +00003314 if (isDynamicClassType(PointeeTy)) {
3315
3316 unsigned OperationType = 0;
3317 // "overwritten" if we're warning about the destination for any call
3318 // but memcmp; otherwise a verb appropriate to the call.
3319 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
3320 if (BId == Builtin::BImemcpy)
3321 OperationType = 1;
3322 else if(BId == Builtin::BImemmove)
3323 OperationType = 2;
3324 else if (BId == Builtin::BImemcmp)
3325 OperationType = 3;
3326 }
3327
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003328 DiagRuntimeBehavior(
3329 Dest->getExprLoc(), Dest,
3330 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks0a151a12012-01-17 00:37:07 +00003331 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Anna Zaksd9b859a2012-01-13 21:52:01 +00003332 << FnName << PointeeTy
Anna Zaks0a151a12012-01-17 00:37:07 +00003333 << OperationType
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003334 << Call->getCallee()->getSourceRange());
Anna Zaks0a151a12012-01-17 00:37:07 +00003335 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
3336 BId != Builtin::BImemset)
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003337 DiagRuntimeBehavior(
3338 Dest->getExprLoc(), Dest,
3339 PDiag(diag::warn_arc_object_memaccess)
3340 << ArgIdx << FnName << PointeeTy
3341 << Call->getCallee()->getSourceRange());
John McCallf85e1932011-06-15 23:02:42 +00003342 else
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003343 continue;
John McCallf85e1932011-06-15 23:02:42 +00003344
3345 DiagRuntimeBehavior(
3346 Dest->getExprLoc(), Dest,
Chandler Carruth929f0132011-06-03 06:23:57 +00003347 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003348 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
3349 break;
3350 }
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003351 }
3352}
3353
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003354// A little helper routine: ignore addition and subtraction of integer literals.
3355// This intentionally does not ignore all integer constant expressions because
3356// we don't want to remove sizeof().
3357static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
3358 Ex = Ex->IgnoreParenCasts();
3359
3360 for (;;) {
3361 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
3362 if (!BO || !BO->isAdditiveOp())
3363 break;
3364
3365 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
3366 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
3367
3368 if (isa<IntegerLiteral>(RHS))
3369 Ex = LHS;
3370 else if (isa<IntegerLiteral>(LHS))
3371 Ex = RHS;
3372 else
3373 break;
3374 }
3375
3376 return Ex;
3377}
3378
Anna Zaks0f38ace2012-08-08 21:42:23 +00003379static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
3380 ASTContext &Context) {
3381 // Only handle constant-sized or VLAs, but not flexible members.
3382 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
3383 // Only issue the FIXIT for arrays of size > 1.
3384 if (CAT->getSize().getSExtValue() <= 1)
3385 return false;
3386 } else if (!Ty->isVariableArrayType()) {
3387 return false;
3388 }
3389 return true;
3390}
3391
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003392// Warn if the user has made the 'size' argument to strlcpy or strlcat
3393// be the size of the source, instead of the destination.
3394void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
3395 IdentifierInfo *FnName) {
3396
3397 // Don't crash if the user has the wrong number of arguments
3398 if (Call->getNumArgs() != 3)
3399 return;
3400
3401 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
3402 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
3403 const Expr *CompareWithSrc = NULL;
3404
3405 // Look for 'strlcpy(dst, x, sizeof(x))'
3406 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
3407 CompareWithSrc = Ex;
3408 else {
3409 // Look for 'strlcpy(dst, x, strlen(x))'
3410 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Richard Smith180f4792011-11-10 06:34:14 +00003411 if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003412 && SizeCall->getNumArgs() == 1)
3413 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
3414 }
3415 }
3416
3417 if (!CompareWithSrc)
3418 return;
3419
3420 // Determine if the argument to sizeof/strlen is equal to the source
3421 // argument. In principle there's all kinds of things you could do
3422 // here, for instance creating an == expression and evaluating it with
3423 // EvaluateAsBooleanCondition, but this uses a more direct technique:
3424 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
3425 if (!SrcArgDRE)
3426 return;
3427
3428 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
3429 if (!CompareWithSrcDRE ||
3430 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
3431 return;
3432
3433 const Expr *OriginalSizeArg = Call->getArg(2);
3434 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
3435 << OriginalSizeArg->getSourceRange() << FnName;
3436
3437 // Output a FIXIT hint if the destination is an array (rather than a
3438 // pointer to an array). This could be enhanced to handle some
3439 // pointers if we know the actual size, like if DstArg is 'array+2'
3440 // we could say 'sizeof(array)-2'.
3441 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks0f38ace2012-08-08 21:42:23 +00003442 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek8f746222011-08-18 22:48:41 +00003443 return;
Ted Kremenek8f746222011-08-18 22:48:41 +00003444
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003445 SmallString<128> sizeString;
Ted Kremenek8f746222011-08-18 22:48:41 +00003446 llvm::raw_svector_ostream OS(sizeString);
3447 OS << "sizeof(";
Richard Smithd1420c62012-08-16 03:56:14 +00003448 DstArg->printPretty(OS, 0, getPrintingPolicy());
Ted Kremenek8f746222011-08-18 22:48:41 +00003449 OS << ")";
3450
3451 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
3452 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
3453 OS.str());
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003454}
3455
Anna Zaksc36bedc2012-02-01 19:08:57 +00003456/// Check if two expressions refer to the same declaration.
3457static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
3458 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
3459 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
3460 return D1->getDecl() == D2->getDecl();
3461 return false;
3462}
3463
3464static const Expr *getStrlenExprArg(const Expr *E) {
3465 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
3466 const FunctionDecl *FD = CE->getDirectCallee();
3467 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
3468 return 0;
3469 return CE->getArg(0)->IgnoreParenCasts();
3470 }
3471 return 0;
3472}
3473
3474// Warn on anti-patterns as the 'size' argument to strncat.
3475// The correct size argument should look like following:
3476// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
3477void Sema::CheckStrncatArguments(const CallExpr *CE,
3478 IdentifierInfo *FnName) {
3479 // Don't crash if the user has the wrong number of arguments.
3480 if (CE->getNumArgs() < 3)
3481 return;
3482 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
3483 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
3484 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
3485
3486 // Identify common expressions, which are wrongly used as the size argument
3487 // to strncat and may lead to buffer overflows.
3488 unsigned PatternType = 0;
3489 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
3490 // - sizeof(dst)
3491 if (referToTheSameDecl(SizeOfArg, DstArg))
3492 PatternType = 1;
3493 // - sizeof(src)
3494 else if (referToTheSameDecl(SizeOfArg, SrcArg))
3495 PatternType = 2;
3496 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
3497 if (BE->getOpcode() == BO_Sub) {
3498 const Expr *L = BE->getLHS()->IgnoreParenCasts();
3499 const Expr *R = BE->getRHS()->IgnoreParenCasts();
3500 // - sizeof(dst) - strlen(dst)
3501 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
3502 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
3503 PatternType = 1;
3504 // - sizeof(src) - (anything)
3505 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
3506 PatternType = 2;
3507 }
3508 }
3509
3510 if (PatternType == 0)
3511 return;
3512
Anna Zaksafdb0412012-02-03 01:27:37 +00003513 // Generate the diagnostic.
3514 SourceLocation SL = LenArg->getLocStart();
3515 SourceRange SR = LenArg->getSourceRange();
3516 SourceManager &SM = PP.getSourceManager();
3517
3518 // If the function is defined as a builtin macro, do not show macro expansion.
3519 if (SM.isMacroArgExpansion(SL)) {
3520 SL = SM.getSpellingLoc(SL);
3521 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
3522 SM.getSpellingLoc(SR.getEnd()));
3523 }
3524
Anna Zaks0f38ace2012-08-08 21:42:23 +00003525 // Check if the destination is an array (rather than a pointer to an array).
3526 QualType DstTy = DstArg->getType();
3527 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
3528 Context);
3529 if (!isKnownSizeArray) {
3530 if (PatternType == 1)
3531 Diag(SL, diag::warn_strncat_wrong_size) << SR;
3532 else
3533 Diag(SL, diag::warn_strncat_src_size) << SR;
3534 return;
3535 }
3536
Anna Zaksc36bedc2012-02-01 19:08:57 +00003537 if (PatternType == 1)
Anna Zaksafdb0412012-02-03 01:27:37 +00003538 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003539 else
Anna Zaksafdb0412012-02-03 01:27:37 +00003540 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003541
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003542 SmallString<128> sizeString;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003543 llvm::raw_svector_ostream OS(sizeString);
3544 OS << "sizeof(";
Richard Smithd1420c62012-08-16 03:56:14 +00003545 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003546 OS << ") - ";
3547 OS << "strlen(";
Richard Smithd1420c62012-08-16 03:56:14 +00003548 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003549 OS << ") - 1";
3550
Anna Zaksafdb0412012-02-03 01:27:37 +00003551 Diag(SL, diag::note_strncat_wrong_size)
3552 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003553}
3554
Ted Kremenek06de2762007-08-17 16:46:58 +00003555//===--- CHECK: Return Address of Stack Variable --------------------------===//
3556
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003557static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3558 Decl *ParentDecl);
3559static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
3560 Decl *ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003561
3562/// CheckReturnStackAddr - Check if a return statement returns the address
3563/// of a stack variable.
3564void
3565Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
3566 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00003567
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003568 Expr *stackE = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003569 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003570
3571 // Perform checking for returned stack addresses, local blocks,
3572 // label addresses or references to temporaries.
John McCallf85e1932011-06-15 23:02:42 +00003573 if (lhsType->isPointerType() ||
David Blaikie4e4d0842012-03-11 07:00:24 +00003574 (!getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003575 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003576 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003577 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003578 }
3579
3580 if (stackE == 0)
3581 return; // Nothing suspicious was found.
3582
3583 SourceLocation diagLoc;
3584 SourceRange diagRange;
3585 if (refVars.empty()) {
3586 diagLoc = stackE->getLocStart();
3587 diagRange = stackE->getSourceRange();
3588 } else {
3589 // We followed through a reference variable. 'stackE' contains the
3590 // problematic expression but we will warn at the return statement pointing
3591 // at the reference variable. We will later display the "trail" of
3592 // reference variables using notes.
3593 diagLoc = refVars[0]->getLocStart();
3594 diagRange = refVars[0]->getSourceRange();
3595 }
3596
3597 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
3598 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
3599 : diag::warn_ret_stack_addr)
3600 << DR->getDecl()->getDeclName() << diagRange;
3601 } else if (isa<BlockExpr>(stackE)) { // local block.
3602 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
3603 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
3604 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
3605 } else { // local temporary.
3606 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
3607 : diag::warn_ret_local_temp_addr)
3608 << diagRange;
3609 }
3610
3611 // Display the "trail" of reference variables that we followed until we
3612 // found the problematic expression using notes.
3613 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
3614 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
3615 // If this var binds to another reference var, show the range of the next
3616 // var, otherwise the var binds to the problematic expression, in which case
3617 // show the range of the expression.
3618 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
3619 : stackE->getSourceRange();
3620 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
3621 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00003622 }
3623}
3624
3625/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
3626/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003627/// to a location on the stack, a local block, an address of a label, or a
3628/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00003629/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003630/// encounter a subexpression that (1) clearly does not lead to one of the
3631/// above problematic expressions (2) is something we cannot determine leads to
3632/// a problematic expression based on such local checking.
3633///
3634/// Both EvalAddr and EvalVal follow through reference variables to evaluate
3635/// the expression that they point to. Such variables are added to the
3636/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00003637///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00003638/// EvalAddr processes expressions that are pointers that are used as
3639/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003640/// At the base case of the recursion is a check for the above problematic
3641/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00003642///
3643/// This implementation handles:
3644///
3645/// * pointer-to-pointer casts
3646/// * implicit conversions from array references to pointers
3647/// * taking the address of fields
3648/// * arbitrary interplay between "&" and "*" operators
3649/// * pointer arithmetic from an address of a stack variable
3650/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003651static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3652 Decl *ParentDecl) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003653 if (E->isTypeDependent())
3654 return NULL;
3655
Ted Kremenek06de2762007-08-17 16:46:58 +00003656 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00003657 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00003658 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003659 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003660 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00003661
Peter Collingbournef111d932011-04-15 00:35:48 +00003662 E = E->IgnoreParens();
3663
Ted Kremenek06de2762007-08-17 16:46:58 +00003664 // Our "symbolic interpreter" is just a dispatch off the currently
3665 // viewed AST node. We then recursively traverse the AST by calling
3666 // EvalAddr and EvalVal appropriately.
3667 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003668 case Stmt::DeclRefExprClass: {
3669 DeclRefExpr *DR = cast<DeclRefExpr>(E);
3670
3671 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
3672 // If this is a reference variable, follow through to the expression that
3673 // it points to.
3674 if (V->hasLocalStorage() &&
3675 V->getType()->isReferenceType() && V->hasInit()) {
3676 // Add the reference variable to the "trail".
3677 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003678 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003679 }
3680
3681 return NULL;
3682 }
Ted Kremenek06de2762007-08-17 16:46:58 +00003683
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003684 case Stmt::UnaryOperatorClass: {
3685 // The only unary operator that make sense to handle here
3686 // is AddrOf. All others don't make sense as pointers.
3687 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003688
John McCall2de56d12010-08-25 11:45:40 +00003689 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003690 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003691 else
Ted Kremenek06de2762007-08-17 16:46:58 +00003692 return NULL;
3693 }
Mike Stump1eb44332009-09-09 15:08:12 +00003694
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003695 case Stmt::BinaryOperatorClass: {
3696 // Handle pointer arithmetic. All other binary operators are not valid
3697 // in this context.
3698 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00003699 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00003700
John McCall2de56d12010-08-25 11:45:40 +00003701 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003702 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00003703
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003704 Expr *Base = B->getLHS();
3705
3706 // Determine which argument is the real pointer base. It could be
3707 // the RHS argument instead of the LHS.
3708 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00003709
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003710 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003711 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003712 }
Steve Naroff61f40a22008-09-10 19:17:48 +00003713
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003714 // For conditional operators we need to see if either the LHS or RHS are
3715 // valid DeclRefExpr*s. If one of them is valid, we return it.
3716 case Stmt::ConditionalOperatorClass: {
3717 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003718
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003719 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003720 if (Expr *lhsExpr = C->getLHS()) {
3721 // In C++, we can have a throw-expression, which has 'void' type.
3722 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003723 if (Expr* LHS = EvalAddr(lhsExpr, refVars, ParentDecl))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003724 return LHS;
3725 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003726
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003727 // In C++, we can have a throw-expression, which has 'void' type.
3728 if (C->getRHS()->getType()->isVoidType())
3729 return NULL;
3730
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003731 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003732 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003733
3734 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00003735 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003736 return E; // local block.
3737 return NULL;
3738
3739 case Stmt::AddrLabelExprClass:
3740 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00003741
John McCall80ee6e82011-11-10 05:35:25 +00003742 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003743 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
3744 ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00003745
Ted Kremenek54b52742008-08-07 00:49:01 +00003746 // For casts, we need to handle conversions from arrays to
3747 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00003748 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00003749 case Stmt::CStyleCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00003750 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8b9414e2012-02-23 23:04:32 +00003751 case Stmt::ObjCBridgedCastExprClass:
Mike Stump1eb44332009-09-09 15:08:12 +00003752 case Stmt::CXXStaticCastExprClass:
3753 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00003754 case Stmt::CXXConstCastExprClass:
3755 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8b9414e2012-02-23 23:04:32 +00003756 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
3757 switch (cast<CastExpr>(E)->getCastKind()) {
3758 case CK_BitCast:
3759 case CK_LValueToRValue:
3760 case CK_NoOp:
3761 case CK_BaseToDerived:
3762 case CK_DerivedToBase:
3763 case CK_UncheckedDerivedToBase:
3764 case CK_Dynamic:
3765 case CK_CPointerToObjCPointerCast:
3766 case CK_BlockPointerToObjCPointerCast:
3767 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003768 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00003769
3770 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003771 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00003772
3773 default:
3774 return 0;
3775 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003776 }
Mike Stump1eb44332009-09-09 15:08:12 +00003777
Douglas Gregor03e80032011-06-21 17:03:29 +00003778 case Stmt::MaterializeTemporaryExprClass:
3779 if (Expr *Result = EvalAddr(
3780 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003781 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00003782 return Result;
3783
3784 return E;
3785
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003786 // Everything else: we simply don't reason about them.
3787 default:
3788 return NULL;
3789 }
Ted Kremenek06de2762007-08-17 16:46:58 +00003790}
Mike Stump1eb44332009-09-09 15:08:12 +00003791
Ted Kremenek06de2762007-08-17 16:46:58 +00003792
3793/// EvalVal - This function is complements EvalAddr in the mutual recursion.
3794/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003795static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3796 Decl *ParentDecl) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003797do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00003798 // We should only be called for evaluating non-pointer expressions, or
3799 // expressions with a pointer type that are not used as references but instead
3800 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00003801
Ted Kremenek06de2762007-08-17 16:46:58 +00003802 // Our "symbolic interpreter" is just a dispatch off the currently
3803 // viewed AST node. We then recursively traverse the AST by calling
3804 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00003805
3806 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00003807 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003808 case Stmt::ImplicitCastExprClass: {
3809 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00003810 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003811 E = IE->getSubExpr();
3812 continue;
3813 }
3814 return NULL;
3815 }
3816
John McCall80ee6e82011-11-10 05:35:25 +00003817 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003818 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00003819
Douglas Gregora2813ce2009-10-23 18:54:35 +00003820 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003821 // When we hit a DeclRefExpr we are looking at code that refers to a
3822 // variable's name. If it's not a reference variable we check if it has
3823 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00003824 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003825
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003826 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
3827 // Check if it refers to itself, e.g. "int& i = i;".
3828 if (V == ParentDecl)
3829 return DR;
3830
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003831 if (V->hasLocalStorage()) {
3832 if (!V->getType()->isReferenceType())
3833 return DR;
3834
3835 // Reference variable, follow through to the expression that
3836 // it points to.
3837 if (V->hasInit()) {
3838 // Add the reference variable to the "trail".
3839 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003840 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003841 }
3842 }
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003843 }
Mike Stump1eb44332009-09-09 15:08:12 +00003844
Ted Kremenek06de2762007-08-17 16:46:58 +00003845 return NULL;
3846 }
Mike Stump1eb44332009-09-09 15:08:12 +00003847
Ted Kremenek06de2762007-08-17 16:46:58 +00003848 case Stmt::UnaryOperatorClass: {
3849 // The only unary operator that make sense to handle here
3850 // is Deref. All others don't resolve to a "name." This includes
3851 // handling all sorts of rvalues passed to a unary operator.
3852 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003853
John McCall2de56d12010-08-25 11:45:40 +00003854 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003855 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003856
3857 return NULL;
3858 }
Mike Stump1eb44332009-09-09 15:08:12 +00003859
Ted Kremenek06de2762007-08-17 16:46:58 +00003860 case Stmt::ArraySubscriptExprClass: {
3861 // Array subscripts are potential references to data on the stack. We
3862 // retrieve the DeclRefExpr* for the array variable if it indeed
3863 // has local storage.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003864 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003865 }
Mike Stump1eb44332009-09-09 15:08:12 +00003866
Ted Kremenek06de2762007-08-17 16:46:58 +00003867 case Stmt::ConditionalOperatorClass: {
3868 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003869 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00003870 ConditionalOperator *C = cast<ConditionalOperator>(E);
3871
Anders Carlsson39073232007-11-30 19:04:31 +00003872 // Handle the GNU extension for missing LHS.
3873 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003874 if (Expr *LHS = EvalVal(lhsExpr, refVars, ParentDecl))
Anders Carlsson39073232007-11-30 19:04:31 +00003875 return LHS;
3876
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003877 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003878 }
Mike Stump1eb44332009-09-09 15:08:12 +00003879
Ted Kremenek06de2762007-08-17 16:46:58 +00003880 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00003881 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00003882 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003883
Ted Kremenek06de2762007-08-17 16:46:58 +00003884 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00003885 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00003886 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00003887
3888 // Check whether the member type is itself a reference, in which case
3889 // we're not going to refer to the member, but to what the member refers to.
3890 if (M->getMemberDecl()->getType()->isReferenceType())
3891 return NULL;
3892
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003893 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003894 }
Mike Stump1eb44332009-09-09 15:08:12 +00003895
Douglas Gregor03e80032011-06-21 17:03:29 +00003896 case Stmt::MaterializeTemporaryExprClass:
3897 if (Expr *Result = EvalVal(
3898 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003899 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00003900 return Result;
3901
3902 return E;
3903
Ted Kremenek06de2762007-08-17 16:46:58 +00003904 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003905 // Check that we don't return or take the address of a reference to a
3906 // temporary. This is only useful in C++.
3907 if (!E->isTypeDependent() && E->isRValue())
3908 return E;
3909
3910 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00003911 return NULL;
3912 }
Ted Kremenek68957a92010-08-04 20:01:07 +00003913} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00003914}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003915
3916//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
3917
3918/// Check for comparisons of floating point operands using != and ==.
3919/// Issue a warning if these are no self-comparisons, as they are not likely
3920/// to do what the programmer intended.
Richard Trieudd225092011-09-15 21:56:47 +00003921void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieudd225092011-09-15 21:56:47 +00003922 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
3923 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003924
3925 // Special case: check for x == x (which is OK).
3926 // Do not emit warnings for such cases.
3927 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
3928 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
3929 if (DRL->getDecl() == DRR->getDecl())
David Blaikie980343b2012-07-16 20:47:22 +00003930 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003931
3932
Ted Kremenek1b500bb2007-11-29 00:59:04 +00003933 // Special case: check for comparisons against literals that can be exactly
3934 // represented by APFloat. In such cases, do not emit a warning. This
3935 // is a heuristic: often comparison against such literals are used to
3936 // detect if a value in a variable has not changed. This clearly can
3937 // lead to false negatives.
David Blaikie980343b2012-07-16 20:47:22 +00003938 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
3939 if (FLL->isExact())
3940 return;
3941 } else
3942 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
3943 if (FLR->isExact())
3944 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003945
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003946 // Check for comparisons with builtin types.
David Blaikie980343b2012-07-16 20:47:22 +00003947 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
3948 if (CL->isBuiltinCall())
3949 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003950
David Blaikie980343b2012-07-16 20:47:22 +00003951 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
3952 if (CR->isBuiltinCall())
3953 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003954
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003955 // Emit the diagnostic.
David Blaikie980343b2012-07-16 20:47:22 +00003956 Diag(Loc, diag::warn_floatingpoint_eq)
3957 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003958}
John McCallba26e582010-01-04 23:21:16 +00003959
John McCallf2370c92010-01-06 05:24:50 +00003960//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
3961//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00003962
John McCallf2370c92010-01-06 05:24:50 +00003963namespace {
John McCallba26e582010-01-04 23:21:16 +00003964
John McCallf2370c92010-01-06 05:24:50 +00003965/// Structure recording the 'active' range of an integer-valued
3966/// expression.
3967struct IntRange {
3968 /// The number of bits active in the int.
3969 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00003970
John McCallf2370c92010-01-06 05:24:50 +00003971 /// True if the int is known not to have negative values.
3972 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00003973
John McCallf2370c92010-01-06 05:24:50 +00003974 IntRange(unsigned Width, bool NonNegative)
3975 : Width(Width), NonNegative(NonNegative)
3976 {}
John McCallba26e582010-01-04 23:21:16 +00003977
John McCall1844a6e2010-11-10 23:38:19 +00003978 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00003979 static IntRange forBoolType() {
3980 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00003981 }
3982
John McCall1844a6e2010-11-10 23:38:19 +00003983 /// Returns the range of an opaque value of the given integral type.
3984 static IntRange forValueOfType(ASTContext &C, QualType T) {
3985 return forValueOfCanonicalType(C,
3986 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00003987 }
3988
John McCall1844a6e2010-11-10 23:38:19 +00003989 /// Returns the range of an opaque value of a canonical integral type.
3990 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00003991 assert(T->isCanonicalUnqualified());
3992
3993 if (const VectorType *VT = dyn_cast<VectorType>(T))
3994 T = VT->getElementType().getTypePtr();
3995 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
3996 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00003997
John McCall091f23f2010-11-09 22:22:12 +00003998 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00003999 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
4000 EnumDecl *Enum = ET->getDecl();
John McCall5e1cdac2011-10-07 06:10:15 +00004001 if (!Enum->isCompleteDefinition())
John McCall091f23f2010-11-09 22:22:12 +00004002 return IntRange(C.getIntWidth(QualType(T, 0)), false);
4003
John McCall323ed742010-05-06 08:58:33 +00004004 unsigned NumPositive = Enum->getNumPositiveBits();
4005 unsigned NumNegative = Enum->getNumNegativeBits();
4006
Richard Trieu8f50b242012-11-16 01:32:40 +00004007 if (NumNegative == 0)
4008 return IntRange(NumPositive, true/*NonNegative*/);
4009 else
4010 return IntRange(std::max(NumPositive + 1, NumNegative),
4011 false/*NonNegative*/);
John McCall323ed742010-05-06 08:58:33 +00004012 }
John McCallf2370c92010-01-06 05:24:50 +00004013
4014 const BuiltinType *BT = cast<BuiltinType>(T);
4015 assert(BT->isInteger());
4016
4017 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4018 }
4019
John McCall1844a6e2010-11-10 23:38:19 +00004020 /// Returns the "target" range of a canonical integral type, i.e.
4021 /// the range of values expressible in the type.
4022 ///
4023 /// This matches forValueOfCanonicalType except that enums have the
4024 /// full range of their type, not the range of their enumerators.
4025 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
4026 assert(T->isCanonicalUnqualified());
4027
4028 if (const VectorType *VT = dyn_cast<VectorType>(T))
4029 T = VT->getElementType().getTypePtr();
4030 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4031 T = CT->getElementType().getTypePtr();
4032 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor69ff26b2011-09-08 23:29:05 +00004033 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall1844a6e2010-11-10 23:38:19 +00004034
4035 const BuiltinType *BT = cast<BuiltinType>(T);
4036 assert(BT->isInteger());
4037
4038 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4039 }
4040
4041 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00004042 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00004043 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00004044 L.NonNegative && R.NonNegative);
4045 }
4046
John McCall1844a6e2010-11-10 23:38:19 +00004047 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00004048 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00004049 return IntRange(std::min(L.Width, R.Width),
4050 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00004051 }
4052};
4053
Ted Kremenek0692a192012-01-31 05:37:37 +00004054static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
4055 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004056 if (value.isSigned() && value.isNegative())
4057 return IntRange(value.getMinSignedBits(), false);
4058
4059 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00004060 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00004061
4062 // isNonNegative() just checks the sign bit without considering
4063 // signedness.
4064 return IntRange(value.getActiveBits(), true);
4065}
4066
Ted Kremenek0692a192012-01-31 05:37:37 +00004067static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
4068 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004069 if (result.isInt())
4070 return GetValueRange(C, result.getInt(), MaxWidth);
4071
4072 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00004073 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
4074 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
4075 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
4076 R = IntRange::join(R, El);
4077 }
John McCallf2370c92010-01-06 05:24:50 +00004078 return R;
4079 }
4080
4081 if (result.isComplexInt()) {
4082 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
4083 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
4084 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00004085 }
4086
4087 // This can happen with lossless casts to intptr_t of "based" lvalues.
4088 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00004089 // FIXME: The only reason we need to pass the type in here is to get
4090 // the sign right on this one case. It would be nice if APValue
4091 // preserved this.
Eli Friedman65639282012-01-04 23:13:47 +00004092 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00004093 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall51313c32010-01-04 23:31:57 +00004094}
John McCallf2370c92010-01-06 05:24:50 +00004095
4096/// Pseudo-evaluate the given integer expression, estimating the
4097/// range of values it might take.
4098///
4099/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek0692a192012-01-31 05:37:37 +00004100static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004101 E = E->IgnoreParens();
4102
4103 // Try a full evaluation first.
4104 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00004105 if (E->EvaluateAsRValue(result, C))
John McCall0acc3112010-01-06 22:57:21 +00004106 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00004107
4108 // I think we only want to look through implicit casts here; if the
4109 // user has an explicit widening cast, we should treat the value as
4110 // being of the new, wider type.
4111 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedmanb17ee5b2011-12-15 02:41:52 +00004112 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCallf2370c92010-01-06 05:24:50 +00004113 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
4114
John McCall1844a6e2010-11-10 23:38:19 +00004115 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCallf2370c92010-01-06 05:24:50 +00004116
John McCall2de56d12010-08-25 11:45:40 +00004117 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00004118
John McCallf2370c92010-01-06 05:24:50 +00004119 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00004120 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00004121 return OutputTypeRange;
4122
4123 IntRange SubRange
4124 = GetExprRange(C, CE->getSubExpr(),
4125 std::min(MaxWidth, OutputTypeRange.Width));
4126
4127 // Bail out if the subexpr's range is as wide as the cast type.
4128 if (SubRange.Width >= OutputTypeRange.Width)
4129 return OutputTypeRange;
4130
4131 // Otherwise, we take the smaller width, and we're non-negative if
4132 // either the output type or the subexpr is.
4133 return IntRange(SubRange.Width,
4134 SubRange.NonNegative || OutputTypeRange.NonNegative);
4135 }
4136
4137 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4138 // If we can fold the condition, just take that operand.
4139 bool CondResult;
4140 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
4141 return GetExprRange(C, CondResult ? CO->getTrueExpr()
4142 : CO->getFalseExpr(),
4143 MaxWidth);
4144
4145 // Otherwise, conservatively merge.
4146 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
4147 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
4148 return IntRange::join(L, R);
4149 }
4150
4151 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4152 switch (BO->getOpcode()) {
4153
4154 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00004155 case BO_LAnd:
4156 case BO_LOr:
4157 case BO_LT:
4158 case BO_GT:
4159 case BO_LE:
4160 case BO_GE:
4161 case BO_EQ:
4162 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00004163 return IntRange::forBoolType();
4164
John McCall862ff872011-07-13 06:35:24 +00004165 // The type of the assignments is the type of the LHS, so the RHS
4166 // is not necessarily the same type.
John McCall2de56d12010-08-25 11:45:40 +00004167 case BO_MulAssign:
4168 case BO_DivAssign:
4169 case BO_RemAssign:
4170 case BO_AddAssign:
4171 case BO_SubAssign:
John McCall862ff872011-07-13 06:35:24 +00004172 case BO_XorAssign:
4173 case BO_OrAssign:
4174 // TODO: bitfields?
John McCall1844a6e2010-11-10 23:38:19 +00004175 return IntRange::forValueOfType(C, E->getType());
John McCallc0cd21d2010-02-23 19:22:29 +00004176
John McCall862ff872011-07-13 06:35:24 +00004177 // Simple assignments just pass through the RHS, which will have
4178 // been coerced to the LHS type.
4179 case BO_Assign:
4180 // TODO: bitfields?
4181 return GetExprRange(C, BO->getRHS(), MaxWidth);
4182
John McCallf2370c92010-01-06 05:24:50 +00004183 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00004184 case BO_PtrMemD:
4185 case BO_PtrMemI:
John McCall1844a6e2010-11-10 23:38:19 +00004186 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00004187
John McCall60fad452010-01-06 22:07:33 +00004188 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00004189 case BO_And:
4190 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00004191 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
4192 GetExprRange(C, BO->getRHS(), MaxWidth));
4193
John McCallf2370c92010-01-06 05:24:50 +00004194 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00004195 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00004196 // ...except that we want to treat '1 << (blah)' as logically
4197 // positive. It's an important idiom.
4198 if (IntegerLiteral *I
4199 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
4200 if (I->getValue() == 1) {
John McCall1844a6e2010-11-10 23:38:19 +00004201 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall3aae6092010-04-07 01:14:35 +00004202 return IntRange(R.Width, /*NonNegative*/ true);
4203 }
4204 }
4205 // fallthrough
4206
John McCall2de56d12010-08-25 11:45:40 +00004207 case BO_ShlAssign:
John McCall1844a6e2010-11-10 23:38:19 +00004208 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00004209
John McCall60fad452010-01-06 22:07:33 +00004210 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00004211 case BO_Shr:
4212 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00004213 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4214
4215 // If the shift amount is a positive constant, drop the width by
4216 // that much.
4217 llvm::APSInt shift;
4218 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
4219 shift.isNonNegative()) {
4220 unsigned zext = shift.getZExtValue();
4221 if (zext >= L.Width)
4222 L.Width = (L.NonNegative ? 0 : 1);
4223 else
4224 L.Width -= zext;
4225 }
4226
4227 return L;
4228 }
4229
4230 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00004231 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00004232 return GetExprRange(C, BO->getRHS(), MaxWidth);
4233
John McCall60fad452010-01-06 22:07:33 +00004234 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00004235 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00004236 if (BO->getLHS()->getType()->isPointerType())
John McCall1844a6e2010-11-10 23:38:19 +00004237 return IntRange::forValueOfType(C, E->getType());
John McCall00fe7612011-07-14 22:39:48 +00004238 break;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00004239
John McCall00fe7612011-07-14 22:39:48 +00004240 // The width of a division result is mostly determined by the size
4241 // of the LHS.
4242 case BO_Div: {
4243 // Don't 'pre-truncate' the operands.
4244 unsigned opWidth = C.getIntWidth(E->getType());
4245 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4246
4247 // If the divisor is constant, use that.
4248 llvm::APSInt divisor;
4249 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
4250 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
4251 if (log2 >= L.Width)
4252 L.Width = (L.NonNegative ? 0 : 1);
4253 else
4254 L.Width = std::min(L.Width - log2, MaxWidth);
4255 return L;
4256 }
4257
4258 // Otherwise, just use the LHS's width.
4259 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4260 return IntRange(L.Width, L.NonNegative && R.NonNegative);
4261 }
4262
4263 // The result of a remainder can't be larger than the result of
4264 // either side.
4265 case BO_Rem: {
4266 // Don't 'pre-truncate' the operands.
4267 unsigned opWidth = C.getIntWidth(E->getType());
4268 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4269 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4270
4271 IntRange meet = IntRange::meet(L, R);
4272 meet.Width = std::min(meet.Width, MaxWidth);
4273 return meet;
4274 }
4275
4276 // The default behavior is okay for these.
4277 case BO_Mul:
4278 case BO_Add:
4279 case BO_Xor:
4280 case BO_Or:
John McCallf2370c92010-01-06 05:24:50 +00004281 break;
4282 }
4283
John McCall00fe7612011-07-14 22:39:48 +00004284 // The default case is to treat the operation as if it were closed
4285 // on the narrowest type that encompasses both operands.
John McCallf2370c92010-01-06 05:24:50 +00004286 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4287 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
4288 return IntRange::join(L, R);
4289 }
4290
4291 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
4292 switch (UO->getOpcode()) {
4293 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00004294 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00004295 return IntRange::forBoolType();
4296
4297 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00004298 case UO_Deref:
4299 case UO_AddrOf: // should be impossible
John McCall1844a6e2010-11-10 23:38:19 +00004300 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00004301
4302 default:
4303 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
4304 }
4305 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004306
4307 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall1844a6e2010-11-10 23:38:19 +00004308 IntRange::forValueOfType(C, E->getType());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004309 }
John McCallf2370c92010-01-06 05:24:50 +00004310
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004311 if (FieldDecl *BitField = E->getBitField())
4312 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00004313 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00004314
John McCall1844a6e2010-11-10 23:38:19 +00004315 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00004316}
John McCall51313c32010-01-04 23:31:57 +00004317
Ted Kremenek0692a192012-01-31 05:37:37 +00004318static IntRange GetExprRange(ASTContext &C, Expr *E) {
John McCall323ed742010-05-06 08:58:33 +00004319 return GetExprRange(C, E, C.getIntWidth(E->getType()));
4320}
4321
John McCall51313c32010-01-04 23:31:57 +00004322/// Checks whether the given value, which currently has the given
4323/// source semantics, has the same value when coerced through the
4324/// target semantics.
Ted Kremenek0692a192012-01-31 05:37:37 +00004325static bool IsSameFloatAfterCast(const llvm::APFloat &value,
4326 const llvm::fltSemantics &Src,
4327 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00004328 llvm::APFloat truncated = value;
4329
4330 bool ignored;
4331 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
4332 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
4333
4334 return truncated.bitwiseIsEqual(value);
4335}
4336
4337/// Checks whether the given value, which currently has the given
4338/// source semantics, has the same value when coerced through the
4339/// target semantics.
4340///
4341/// The value might be a vector of floats (or a complex number).
Ted Kremenek0692a192012-01-31 05:37:37 +00004342static bool IsSameFloatAfterCast(const APValue &value,
4343 const llvm::fltSemantics &Src,
4344 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00004345 if (value.isFloat())
4346 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
4347
4348 if (value.isVector()) {
4349 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
4350 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
4351 return false;
4352 return true;
4353 }
4354
4355 assert(value.isComplexFloat());
4356 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
4357 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
4358}
4359
Ted Kremenek0692a192012-01-31 05:37:37 +00004360static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00004361
Ted Kremeneke3b159c2010-09-23 21:43:44 +00004362static bool IsZero(Sema &S, Expr *E) {
4363 // Suppress cases where we are comparing against an enum constant.
4364 if (const DeclRefExpr *DR =
4365 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
4366 if (isa<EnumConstantDecl>(DR->getDecl()))
4367 return false;
4368
4369 // Suppress cases where the '0' value is expanded from a macro.
4370 if (E->getLocStart().isMacroID())
4371 return false;
4372
John McCall323ed742010-05-06 08:58:33 +00004373 llvm::APSInt Value;
4374 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
4375}
4376
John McCall372e1032010-10-06 00:25:24 +00004377static bool HasEnumType(Expr *E) {
4378 // Strip off implicit integral promotions.
4379 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00004380 if (ICE->getCastKind() != CK_IntegralCast &&
4381 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00004382 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00004383 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00004384 }
4385
4386 return E->getType()->isEnumeralType();
4387}
4388
Ted Kremenek0692a192012-01-31 05:37:37 +00004389static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00004390 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00004391 if (E->isValueDependent())
4392 return;
4393
John McCall2de56d12010-08-25 11:45:40 +00004394 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00004395 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004396 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00004397 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004398 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00004399 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004400 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00004401 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004402 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00004403 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004404 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00004405 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004406 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00004407 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004408 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00004409 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4410 }
4411}
4412
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004413static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004414 Expr *Constant, Expr *Other,
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004415 llvm::APSInt Value,
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004416 bool RhsConstant) {
Richard Trieu526e6272012-11-14 22:50:24 +00004417 // 0 values are handled later by CheckTrivialUnsignedComparison().
4418 if (Value == 0)
4419 return;
4420
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004421 BinaryOperatorKind op = E->getOpcode();
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004422 QualType OtherT = Other->getType();
4423 QualType ConstantT = Constant->getType();
Richard Trieu526e6272012-11-14 22:50:24 +00004424 QualType CommonT = E->getLHS()->getType();
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004425 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004426 return;
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004427 assert((OtherT->isIntegerType() && ConstantT->isIntegerType())
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004428 && "comparison with non-integer type");
Richard Trieu526e6272012-11-14 22:50:24 +00004429
4430 bool ConstantSigned = ConstantT->isSignedIntegerType();
Richard Trieu526e6272012-11-14 22:50:24 +00004431 bool CommonSigned = CommonT->isSignedIntegerType();
4432
4433 bool EqualityOnly = false;
4434
4435 // TODO: Investigate using GetExprRange() to get tighter bounds on
4436 // on the bit ranges.
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004437 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
Richard Trieu526e6272012-11-14 22:50:24 +00004438 unsigned OtherWidth = OtherRange.Width;
4439
4440 if (CommonSigned) {
4441 // The common type is signed, therefore no signed to unsigned conversion.
Eli Friedmand87de7b2012-11-30 23:09:29 +00004442 if (!OtherRange.NonNegative) {
Richard Trieu526e6272012-11-14 22:50:24 +00004443 // Check that the constant is representable in type OtherT.
4444 if (ConstantSigned) {
4445 if (OtherWidth >= Value.getMinSignedBits())
4446 return;
4447 } else { // !ConstantSigned
4448 if (OtherWidth >= Value.getActiveBits() + 1)
4449 return;
4450 }
4451 } else { // !OtherSigned
4452 // Check that the constant is representable in type OtherT.
4453 // Negative values are out of range.
4454 if (ConstantSigned) {
4455 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
4456 return;
4457 } else { // !ConstantSigned
4458 if (OtherWidth >= Value.getActiveBits())
4459 return;
4460 }
4461 }
4462 } else { // !CommonSigned
Eli Friedmand87de7b2012-11-30 23:09:29 +00004463 if (OtherRange.NonNegative) {
Richard Trieu526e6272012-11-14 22:50:24 +00004464 if (OtherWidth >= Value.getActiveBits())
4465 return;
Eli Friedmand87de7b2012-11-30 23:09:29 +00004466 } else if (!OtherRange.NonNegative && !ConstantSigned) {
Richard Trieu526e6272012-11-14 22:50:24 +00004467 // Check to see if the constant is representable in OtherT.
4468 if (OtherWidth > Value.getActiveBits())
4469 return;
4470 // Check to see if the constant is equivalent to a negative value
4471 // cast to CommonT.
4472 if (S.Context.getIntWidth(ConstantT) == S.Context.getIntWidth(CommonT) &&
Richard Trieu5d1cf4f2012-11-15 03:43:50 +00004473 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
Richard Trieu526e6272012-11-14 22:50:24 +00004474 return;
4475 // The constant value rests between values that OtherT can represent after
4476 // conversion. Relational comparison still works, but equality
4477 // comparisons will be tautological.
4478 EqualityOnly = true;
4479 } else { // OtherSigned && ConstantSigned
4480 assert(0 && "Two signed types converted to unsigned types.");
4481 }
4482 }
4483
4484 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
4485
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004486 bool IsTrue = true;
Richard Trieu526e6272012-11-14 22:50:24 +00004487 if (op == BO_EQ || op == BO_NE) {
4488 IsTrue = op == BO_NE;
4489 } else if (EqualityOnly) {
4490 return;
4491 } else if (RhsConstant) {
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004492 if (op == BO_GT || op == BO_GE)
Richard Trieu526e6272012-11-14 22:50:24 +00004493 IsTrue = !PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004494 else // op == BO_LT || op == BO_LE
Richard Trieu526e6272012-11-14 22:50:24 +00004495 IsTrue = PositiveConstant;
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004496 } else {
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004497 if (op == BO_LT || op == BO_LE)
Richard Trieu526e6272012-11-14 22:50:24 +00004498 IsTrue = !PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004499 else // op == BO_GT || op == BO_GE
Richard Trieu526e6272012-11-14 22:50:24 +00004500 IsTrue = PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004501 }
Ted Kremenek7adf3a92013-03-15 21:50:10 +00004502
4503 // If this is a comparison to an enum constant, include that
4504 // constant in the diagnostic.
4505 const EnumConstantDecl *ED = 0;
4506 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
4507 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
4508
4509 SmallString<64> PrettySourceValue;
4510 llvm::raw_svector_ostream OS(PrettySourceValue);
4511 if (ED)
Ted Kremenek9de50942013-03-15 22:02:46 +00004512 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenek7adf3a92013-03-15 21:50:10 +00004513 else
4514 OS << Value;
4515
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004516 S.Diag(E->getOperatorLoc(), diag::warn_out_of_range_compare)
Ted Kremenek7adf3a92013-03-15 21:50:10 +00004517 << OS.str() << OtherT << IsTrue
Richard Trieu526e6272012-11-14 22:50:24 +00004518 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004519}
4520
John McCall323ed742010-05-06 08:58:33 +00004521/// Analyze the operands of the given comparison. Implements the
4522/// fallback case from AnalyzeComparison.
Ted Kremenek0692a192012-01-31 05:37:37 +00004523static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00004524 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4525 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00004526}
John McCall51313c32010-01-04 23:31:57 +00004527
John McCallba26e582010-01-04 23:21:16 +00004528/// \brief Implements -Wsign-compare.
4529///
Richard Trieudd225092011-09-15 21:56:47 +00004530/// \param E the binary operator to check for warnings
Ted Kremenek0692a192012-01-31 05:37:37 +00004531static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCall323ed742010-05-06 08:58:33 +00004532 // The type the comparison is being performed in.
4533 QualType T = E->getLHS()->getType();
4534 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
4535 && "comparison with mismatched types");
Fariborz Jahanianab4702f2012-09-18 17:46:26 +00004536 if (E->isValueDependent())
4537 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004538
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004539 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
4540 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004541
4542 bool IsComparisonConstant = false;
4543
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004544 // Check whether an integer constant comparison results in a value
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004545 // of 'true' or 'false'.
4546 if (T->isIntegralType(S.Context)) {
4547 llvm::APSInt RHSValue;
4548 bool IsRHSIntegralLiteral =
4549 RHS->isIntegerConstantExpr(RHSValue, S.Context);
4550 llvm::APSInt LHSValue;
4551 bool IsLHSIntegralLiteral =
4552 LHS->isIntegerConstantExpr(LHSValue, S.Context);
4553 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
4554 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
4555 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
4556 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
4557 else
4558 IsComparisonConstant =
4559 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004560 } else if (!T->hasUnsignedIntegerRepresentation())
4561 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004562
John McCall323ed742010-05-06 08:58:33 +00004563 // We don't do anything special if this isn't an unsigned integral
4564 // comparison: we're only interested in integral comparisons, and
4565 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00004566 //
4567 // We also don't care about value-dependent expressions or expressions
4568 // whose result is a constant.
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004569 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCall323ed742010-05-06 08:58:33 +00004570 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004571
John McCall323ed742010-05-06 08:58:33 +00004572 // Check to see if one of the (unmodified) operands is of different
4573 // signedness.
4574 Expr *signedOperand, *unsignedOperand;
Richard Trieudd225092011-09-15 21:56:47 +00004575 if (LHS->getType()->hasSignedIntegerRepresentation()) {
4576 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00004577 "unsigned comparison between two signed integer expressions?");
Richard Trieudd225092011-09-15 21:56:47 +00004578 signedOperand = LHS;
4579 unsignedOperand = RHS;
4580 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
4581 signedOperand = RHS;
4582 unsignedOperand = LHS;
John McCallba26e582010-01-04 23:21:16 +00004583 } else {
John McCall323ed742010-05-06 08:58:33 +00004584 CheckTrivialUnsignedComparison(S, E);
4585 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004586 }
4587
John McCall323ed742010-05-06 08:58:33 +00004588 // Otherwise, calculate the effective range of the signed operand.
4589 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00004590
John McCall323ed742010-05-06 08:58:33 +00004591 // Go ahead and analyze implicit conversions in the operands. Note
4592 // that we skip the implicit conversions on both sides.
Richard Trieudd225092011-09-15 21:56:47 +00004593 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
4594 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00004595
John McCall323ed742010-05-06 08:58:33 +00004596 // If the signed range is non-negative, -Wsign-compare won't fire,
4597 // but we should still check for comparisons which are always true
4598 // or false.
4599 if (signedRange.NonNegative)
4600 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004601
4602 // For (in)equality comparisons, if the unsigned operand is a
4603 // constant which cannot collide with a overflowed signed operand,
4604 // then reinterpreting the signed operand as unsigned will not
4605 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00004606 if (E->isEqualityOp()) {
4607 unsigned comparisonWidth = S.Context.getIntWidth(T);
4608 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00004609
John McCall323ed742010-05-06 08:58:33 +00004610 // We should never be unable to prove that the unsigned operand is
4611 // non-negative.
4612 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
4613
4614 if (unsignedRange.Width < comparisonWidth)
4615 return;
4616 }
4617
Douglas Gregor6d3b93d2012-05-01 01:53:49 +00004618 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
4619 S.PDiag(diag::warn_mixed_sign_comparison)
4620 << LHS->getType() << RHS->getType()
4621 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallba26e582010-01-04 23:21:16 +00004622}
4623
John McCall15d7d122010-11-11 03:21:53 +00004624/// Analyzes an attempt to assign the given value to a bitfield.
4625///
4626/// Returns true if there was something fishy about the attempt.
Ted Kremenek0692a192012-01-31 05:37:37 +00004627static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
4628 SourceLocation InitLoc) {
John McCall15d7d122010-11-11 03:21:53 +00004629 assert(Bitfield->isBitField());
4630 if (Bitfield->isInvalidDecl())
4631 return false;
4632
John McCall91b60142010-11-11 05:33:51 +00004633 // White-list bool bitfields.
4634 if (Bitfield->getType()->isBooleanType())
4635 return false;
4636
Douglas Gregor46ff3032011-02-04 13:09:01 +00004637 // Ignore value- or type-dependent expressions.
4638 if (Bitfield->getBitWidth()->isValueDependent() ||
4639 Bitfield->getBitWidth()->isTypeDependent() ||
4640 Init->isValueDependent() ||
4641 Init->isTypeDependent())
4642 return false;
4643
John McCall15d7d122010-11-11 03:21:53 +00004644 Expr *OriginalInit = Init->IgnoreParenImpCasts();
4645
Richard Smith80d4b552011-12-28 19:48:30 +00004646 llvm::APSInt Value;
4647 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall15d7d122010-11-11 03:21:53 +00004648 return false;
4649
John McCall15d7d122010-11-11 03:21:53 +00004650 unsigned OriginalWidth = Value.getBitWidth();
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004651 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall15d7d122010-11-11 03:21:53 +00004652
4653 if (OriginalWidth <= FieldWidth)
4654 return false;
4655
Eli Friedman3a643af2012-01-26 23:11:39 +00004656 // Compute the value which the bitfield will contain.
Jay Foad9f71a8f2010-12-07 08:25:34 +00004657 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedman3a643af2012-01-26 23:11:39 +00004658 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall15d7d122010-11-11 03:21:53 +00004659
Eli Friedman3a643af2012-01-26 23:11:39 +00004660 // Check whether the stored value is equal to the original value.
4661 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieue1ecdc12012-07-23 20:21:35 +00004662 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall15d7d122010-11-11 03:21:53 +00004663 return false;
4664
Eli Friedman3a643af2012-01-26 23:11:39 +00004665 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedman34ff0622012-02-02 00:40:20 +00004666 // therefore don't strictly fit into a signed bitfield of width 1.
4667 if (FieldWidth == 1 && Value == 1)
Eli Friedman3a643af2012-01-26 23:11:39 +00004668 return false;
4669
John McCall15d7d122010-11-11 03:21:53 +00004670 std::string PrettyValue = Value.toString(10);
4671 std::string PrettyTrunc = TruncatedValue.toString(10);
4672
4673 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
4674 << PrettyValue << PrettyTrunc << OriginalInit->getType()
4675 << Init->getSourceRange();
4676
4677 return true;
4678}
4679
John McCallbeb22aa2010-11-09 23:24:47 +00004680/// Analyze the given simple or compound assignment for warning-worthy
4681/// operations.
Ted Kremenek0692a192012-01-31 05:37:37 +00004682static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCallbeb22aa2010-11-09 23:24:47 +00004683 // Just recurse on the LHS.
4684 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4685
4686 // We want to recurse on the RHS as normal unless we're assigning to
4687 // a bitfield.
4688 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
Sam Panzer25ffbef2013-03-28 19:07:11 +00004689 if (E->getOpcode() != BO_AndAssign &&
4690 AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall15d7d122010-11-11 03:21:53 +00004691 E->getOperatorLoc())) {
4692 // Recurse, ignoring any implicit conversions on the RHS.
4693 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
4694 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00004695 }
4696 }
4697
4698 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
4699}
4700
John McCall51313c32010-01-04 23:31:57 +00004701/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00004702static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00004703 SourceLocation CContext, unsigned diag,
4704 bool pruneControlFlow = false) {
4705 if (pruneControlFlow) {
4706 S.DiagRuntimeBehavior(E->getExprLoc(), E,
4707 S.PDiag(diag)
4708 << SourceType << T << E->getSourceRange()
4709 << SourceRange(CContext));
4710 return;
4711 }
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004712 S.Diag(E->getExprLoc(), diag)
4713 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
4714}
4715
Chandler Carruthe1b02e02011-04-05 06:47:57 +00004716/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00004717static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00004718 SourceLocation CContext, unsigned diag,
4719 bool pruneControlFlow = false) {
4720 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruthe1b02e02011-04-05 06:47:57 +00004721}
4722
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004723/// Diagnose an implicit cast from a literal expression. Does not warn when the
4724/// cast wouldn't lose information.
Chandler Carruthf65076e2011-04-10 08:36:24 +00004725void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
4726 SourceLocation CContext) {
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004727 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruthf65076e2011-04-10 08:36:24 +00004728 bool isExact = false;
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004729 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00004730 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
4731 T->hasUnsignedIntegerRepresentation());
4732 if (Value.convertToInteger(IntegerValue,
Chandler Carruthf65076e2011-04-10 08:36:24 +00004733 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004734 == llvm::APFloat::opOK && isExact)
Chandler Carruthf65076e2011-04-10 08:36:24 +00004735 return;
4736
David Blaikiebe0ee872012-05-15 16:56:36 +00004737 SmallString<16> PrettySourceValue;
4738 Value.toString(PrettySourceValue);
David Blaikiede7e7b82012-05-15 17:18:27 +00004739 SmallString<16> PrettyTargetValue;
David Blaikiebe0ee872012-05-15 16:56:36 +00004740 if (T->isSpecificBuiltinType(BuiltinType::Bool))
4741 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
4742 else
David Blaikiede7e7b82012-05-15 17:18:27 +00004743 IntegerValue.toString(PrettyTargetValue);
David Blaikiebe0ee872012-05-15 16:56:36 +00004744
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004745 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikiebe0ee872012-05-15 16:56:36 +00004746 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
4747 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruthf65076e2011-04-10 08:36:24 +00004748}
4749
John McCall091f23f2010-11-09 22:22:12 +00004750std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
4751 if (!Range.Width) return "0";
4752
4753 llvm::APSInt ValueInRange = Value;
4754 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00004755 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00004756 return ValueInRange.toString(10);
4757}
4758
Hans Wennborg88617a22012-08-28 15:44:30 +00004759static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
4760 if (!isa<ImplicitCastExpr>(Ex))
4761 return false;
4762
4763 Expr *InnerE = Ex->IgnoreParenImpCasts();
4764 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
4765 const Type *Source =
4766 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
4767 if (Target->isDependentType())
4768 return false;
4769
4770 const BuiltinType *FloatCandidateBT =
4771 dyn_cast<BuiltinType>(ToBool ? Source : Target);
4772 const Type *BoolCandidateType = ToBool ? Target : Source;
4773
4774 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
4775 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
4776}
4777
4778void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
4779 SourceLocation CC) {
4780 unsigned NumArgs = TheCall->getNumArgs();
4781 for (unsigned i = 0; i < NumArgs; ++i) {
4782 Expr *CurrA = TheCall->getArg(i);
4783 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
4784 continue;
4785
4786 bool IsSwapped = ((i > 0) &&
4787 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
4788 IsSwapped |= ((i < (NumArgs - 1)) &&
4789 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
4790 if (IsSwapped) {
4791 // Warn on this floating-point to bool conversion.
4792 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
4793 CurrA->getType(), CC,
4794 diag::warn_impcast_floating_point_to_bool);
4795 }
4796 }
4797}
4798
Sam Panzer25ffbef2013-03-28 19:07:11 +00004799// Try to evaluate E as an integer. If EvaluateAsInt succeeds, Value is set to
4800// the resulting value, ResultExpr is set to E.
4801// Otherwise, the output parameters are not modified.
4802static bool EvalAsInt(ASTContext &Ctx, llvm::APSInt &Value, Expr *E,
4803 Expr **ResultExpr) {
4804 if (E->EvaluateAsInt(Value, Ctx, Expr::SE_AllowSideEffects)) {
4805 *ResultExpr = E;
4806 return true;
4807 }
4808 return false;
4809}
4810
4811// Returns true when Value's value would change when narrowed to TargetRange.
4812static bool TruncationChangesValue(const llvm::APSInt &Value,
4813 const IntRange &TargetRange,
4814 bool IsBitwiseAnd) {
4815 // Checks if there are any active non-sign bits past the width of TargetRange.
4816 if (IsBitwiseAnd)
4817 return Value.getBitWidth() - Value.getNumSignBits() > TargetRange.Width;
4818
4819 llvm::APSInt UnsignedValue(Value);
4820 unsigned BitWidth = TargetRange.NonNegative ?
4821 UnsignedValue.getActiveBits() : Value.getMinSignedBits();
4822 return BitWidth > TargetRange.Width;
4823}
4824
4825// Determine if E is an expression containing or likely to contain an implicit
4826// narrowing bug involving a constant.
4827// If so, Value is set to the value of that constant. NarrowedExpr is set to the
4828// problematic sub-expression if it is a strict subset of E.
4829static bool OperandMightImplicitlyNarrow(ASTContext &Ctx, llvm::APSInt &Value,
4830 Expr *E, IntRange TargetRange,
4831 Expr **NarrowedExpr) {
4832 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
4833 if (!BO)
4834 return false;
4835
4836 switch (BO->getOpcode()) {
4837 case BO_And:
4838 case BO_AndAssign:
4839 return (EvalAsInt(Ctx, Value, BO->getLHS(), NarrowedExpr)
4840 && TruncationChangesValue(Value, TargetRange, true)) ||
4841 (EvalAsInt(Ctx, Value, BO->getRHS(), NarrowedExpr)
4842 && TruncationChangesValue(Value, TargetRange, true));
4843
4844 case BO_Or:
4845 case BO_OrAssign:
4846 // FIXME: Include BO_Add, BO_Sub, and BO_Xor when we avoid false positives.
4847 case BO_AddAssign:
4848 case BO_SubAssign:
4849 case BO_Mul:
4850 case BO_MulAssign:
4851 case BO_XorAssign:
4852 return (EvalAsInt(Ctx, Value, BO->getLHS(), NarrowedExpr)
4853 && TruncationChangesValue(Value, TargetRange, false)) ||
4854 (EvalAsInt(Ctx, Value, BO->getRHS(), NarrowedExpr)
4855 && TruncationChangesValue(Value, TargetRange, false));
4856
4857 // We can ignore the left side of the comma operator, since the value is
4858 // explicitly ignored anyway.
4859 case BO_Comma:
4860 return EvalAsInt(Ctx, Value, BO->getRHS(), NarrowedExpr) &&
4861 TruncationChangesValue(Value, TargetRange, false);
4862
4863 case BO_Shl:
4864 return EvalAsInt(Ctx, Value, BO->getLHS(), NarrowedExpr) &&
4865 TruncationChangesValue(Value, TargetRange, false);
4866
4867 default:
4868 break;
4869 }
4870 return false;
4871}
4872
John McCall323ed742010-05-06 08:58:33 +00004873void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Sam Panzer25ffbef2013-03-28 19:07:11 +00004874 SourceLocation CC, bool *ICContext = NULL) {
John McCall323ed742010-05-06 08:58:33 +00004875 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00004876
John McCall323ed742010-05-06 08:58:33 +00004877 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
4878 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
4879 if (Source == Target) return;
4880 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00004881
Chandler Carruth108f7562011-07-26 05:40:03 +00004882 // If the conversion context location is invalid don't complain. We also
4883 // don't want to emit a warning if the issue occurs from the expansion of
4884 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
4885 // delay this check as long as possible. Once we detect we are in that
4886 // scenario, we just return.
Ted Kremenekef9ff882011-03-10 20:03:42 +00004887 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00004888 return;
4889
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004890 // Diagnose implicit casts to bool.
4891 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
4892 if (isa<StringLiteral>(E))
4893 // Warn on string literal to bool. Checks for string literals in logical
4894 // expressions, for instances, assert(0 && "error here"), is prevented
4895 // by a check in AnalyzeImplicitConversions().
4896 return DiagnoseImpCast(S, E, T, CC,
4897 diag::warn_impcast_string_literal_to_bool);
Lang Hamese14ca9f2011-12-05 20:49:50 +00004898 if (Source->isFunctionType()) {
4899 // Warn on function to bool. Checks free functions and static member
4900 // functions. Weakly imported functions are excluded from the check,
4901 // since it's common to test their value to check whether the linker
4902 // found a definition for them.
4903 ValueDecl *D = 0;
4904 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
4905 D = R->getDecl();
4906 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
4907 D = M->getMemberDecl();
4908 }
4909
4910 if (D && !D->isWeak()) {
Richard Trieu26b45d82011-12-06 04:48:01 +00004911 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
4912 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
4913 << F << E->getSourceRange() << SourceRange(CC);
David Blaikie2def7732011-12-09 21:42:37 +00004914 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
4915 << FixItHint::CreateInsertion(E->getExprLoc(), "&");
4916 QualType ReturnType;
4917 UnresolvedSet<4> NonTemplateOverloads;
4918 S.isExprCallable(*E, ReturnType, NonTemplateOverloads);
4919 if (!ReturnType.isNull()
4920 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
4921 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
4922 << FixItHint::CreateInsertion(
4923 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu26b45d82011-12-06 04:48:01 +00004924 return;
4925 }
Lang Hamese14ca9f2011-12-05 20:49:50 +00004926 }
4927 }
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004928 }
John McCall51313c32010-01-04 23:31:57 +00004929
4930 // Strip vector types.
4931 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004932 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004933 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004934 return;
John McCallb4eb64d2010-10-08 02:01:28 +00004935 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004936 }
Chris Lattnerb792b302011-06-14 04:51:15 +00004937
4938 // If the vector cast is cast between two vectors of the same size, it is
4939 // a bitcast, not a conversion.
4940 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
4941 return;
John McCall51313c32010-01-04 23:31:57 +00004942
4943 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
4944 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
4945 }
4946
4947 // Strip complex types.
4948 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004949 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004950 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004951 return;
4952
John McCallb4eb64d2010-10-08 02:01:28 +00004953 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004954 }
John McCall51313c32010-01-04 23:31:57 +00004955
4956 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
4957 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
4958 }
4959
4960 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
4961 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
4962
4963 // If the source is floating point...
4964 if (SourceBT && SourceBT->isFloatingPoint()) {
4965 // ...and the target is floating point...
4966 if (TargetBT && TargetBT->isFloatingPoint()) {
4967 // ...then warn if we're dropping FP rank.
4968
4969 // Builtin FP kinds are ordered by increasing FP rank.
4970 if (SourceBT->getKind() > TargetBT->getKind()) {
4971 // Don't warn about float constants that are precisely
4972 // representable in the target type.
4973 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00004974 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00004975 // Value might be a float, a float vector, or a float complex.
4976 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00004977 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
4978 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00004979 return;
4980 }
4981
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004982 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004983 return;
4984
John McCallb4eb64d2010-10-08 02:01:28 +00004985 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00004986 }
4987 return;
4988 }
4989
Ted Kremenekef9ff882011-03-10 20:03:42 +00004990 // If the target is integral, always warn.
David Blaikiebe0ee872012-05-15 16:56:36 +00004991 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004992 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004993 return;
4994
Chandler Carrutha5b93322011-02-17 11:05:49 +00004995 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay634c8af2011-09-08 22:30:47 +00004996 // We also want to warn on, e.g., "int i = -1.234"
4997 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
4998 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
4999 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
5000
Chandler Carruthf65076e2011-04-10 08:36:24 +00005001 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
5002 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00005003 } else {
5004 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
5005 }
5006 }
John McCall51313c32010-01-04 23:31:57 +00005007
Hans Wennborg88617a22012-08-28 15:44:30 +00005008 // If the target is bool, warn if expr is a function or method call.
5009 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
5010 isa<CallExpr>(E)) {
5011 // Check last argument of function call to see if it is an
5012 // implicit cast from a type matching the type the result
5013 // is being cast to.
5014 CallExpr *CEx = cast<CallExpr>(E);
5015 unsigned NumArgs = CEx->getNumArgs();
5016 if (NumArgs > 0) {
5017 Expr *LastA = CEx->getArg(NumArgs - 1);
5018 Expr *InnerE = LastA->IgnoreParenImpCasts();
5019 const Type *InnerType =
5020 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5021 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
5022 // Warn on this floating-point to bool conversion
5023 DiagnoseImpCast(S, E, T, CC,
5024 diag::warn_impcast_floating_point_to_bool);
5025 }
5026 }
5027 }
John McCall51313c32010-01-04 23:31:57 +00005028 return;
5029 }
5030
Richard Trieu1838ca52011-05-29 19:59:02 +00005031 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
David Blaikieb26331b2012-06-19 21:19:06 +00005032 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
David Blaikiee81b43b2012-11-08 00:41:20 +00005033 && !Target->isBlockPointerType() && !Target->isMemberPointerType()
David Blaikie896c7dd2013-02-16 00:56:22 +00005034 && Target->isScalarType() && !Target->isNullPtrType()) {
David Blaikieb1360492012-03-16 20:30:12 +00005035 SourceLocation Loc = E->getSourceRange().getBegin();
5036 if (Loc.isMacroID())
5037 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
David Blaikie9fb1ac52012-05-15 21:57:38 +00005038 if (!Loc.isMacroID() || CC.isMacroID())
5039 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
5040 << T << clang::SourceRange(CC)
5041 << FixItHint::CreateReplacement(Loc, S.getFixItZeroLiteralForType(T));
Richard Trieu1838ca52011-05-29 19:59:02 +00005042 }
5043
David Blaikieb26331b2012-06-19 21:19:06 +00005044 if (!Source->isIntegerType() || !Target->isIntegerType())
5045 return;
5046
David Blaikiebe0ee872012-05-15 16:56:36 +00005047 // TODO: remove this early return once the false positives for constant->bool
5048 // in templates, macros, etc, are reduced or removed.
5049 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
5050 return;
5051
John McCall323ed742010-05-06 08:58:33 +00005052 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00005053 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00005054
Sam Panzer25ffbef2013-03-28 19:07:11 +00005055 llvm::APSInt Value(32);
5056 Expr *NarrowedExpr = NULL;
5057 // Use a default-on diagnostic if the source is involved in a
5058 // narrowing-prone binary operation with a constant.
5059 if (OperandMightImplicitlyNarrow(S.Context, Value, E, TargetRange,
5060 &NarrowedExpr)) {
5061 std::string PrettySourceValue = Value.toString(10);
5062 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Ted Kremenekef9ff882011-03-10 20:03:42 +00005063
Sam Panzer25ffbef2013-03-28 19:07:11 +00005064 S.DiagRuntimeBehavior(E->getExprLoc(), NarrowedExpr,
5065 S.PDiag(diag::warn_impcast_integer_precision_binop_constant)
5066 << PrettySourceValue << PrettyTargetValue
5067 << E->getType() << T << NarrowedExpr->getSourceRange()
5068 << clang::SourceRange(CC));
5069 return;
5070 } else if (SourceRange.Width > TargetRange.Width) {
5071 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
5072 if (S.SourceMgr.isInSystemMacro(CC))
5073 return;
5074
5075 // If the source is a constant, use a default-on diagnostic.
5076 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
John McCall091f23f2010-11-09 22:22:12 +00005077 std::string PrettySourceValue = Value.toString(10);
5078 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Ted Kremenek5e745da2011-10-22 02:37:33 +00005079 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5080 S.PDiag(diag::warn_impcast_integer_precision_constant)
5081 << PrettySourceValue << PrettyTargetValue
5082 << E->getType() << T << E->getSourceRange()
5083 << clang::SourceRange(CC));
John McCall091f23f2010-11-09 22:22:12 +00005084 return;
5085 }
5086
David Blaikie37050842012-04-12 22:40:54 +00005087 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaksc36bedc2012-02-01 19:08:57 +00005088 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
5089 /* pruneControlFlow */ true);
John McCallb4eb64d2010-10-08 02:01:28 +00005090 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00005091 }
5092
5093 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
5094 (!TargetRange.NonNegative && SourceRange.NonNegative &&
5095 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00005096
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005097 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005098 return;
5099
John McCall323ed742010-05-06 08:58:33 +00005100 unsigned DiagID = diag::warn_impcast_integer_sign;
5101
5102 // Traditionally, gcc has warned about this under -Wsign-compare.
5103 // We also want to warn about it in -Wconversion.
5104 // So if -Wconversion is off, use a completely identical diagnostic
5105 // in the sign-compare group.
5106 // The conditional-checking code will
5107 if (ICContext) {
5108 DiagID = diag::warn_impcast_integer_sign_conditional;
5109 *ICContext = true;
5110 }
5111
John McCallb4eb64d2010-10-08 02:01:28 +00005112 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00005113 }
5114
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005115 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005116 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
5117 // type, to give us better diagnostics.
5118 QualType SourceType = E->getType();
David Blaikie4e4d0842012-03-11 07:00:24 +00005119 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005120 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5121 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
5122 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
5123 SourceType = S.Context.getTypeDeclType(Enum);
5124 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
5125 }
5126 }
5127
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005128 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
5129 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall83972f12013-03-09 00:54:27 +00005130 if (SourceEnum->getDecl()->hasNameForLinkage() &&
5131 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00005132 SourceEnum != TargetEnum) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005133 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005134 return;
5135
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005136 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005137 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00005138 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005139
John McCall51313c32010-01-04 23:31:57 +00005140 return;
5141}
5142
David Blaikie9fb1ac52012-05-15 21:57:38 +00005143void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5144 SourceLocation CC, QualType T);
John McCall323ed742010-05-06 08:58:33 +00005145
5146void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00005147 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00005148 E = E->IgnoreParenImpCasts();
5149
5150 if (isa<ConditionalOperator>(E))
David Blaikie9fb1ac52012-05-15 21:57:38 +00005151 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCall323ed742010-05-06 08:58:33 +00005152
John McCallb4eb64d2010-10-08 02:01:28 +00005153 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005154 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00005155 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00005156 return;
5157}
5158
David Blaikie9fb1ac52012-05-15 21:57:38 +00005159void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5160 SourceLocation CC, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00005161 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00005162
5163 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00005164 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
5165 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00005166
5167 // If -Wconversion would have warned about either of the candidates
5168 // for a signedness conversion to the context type...
5169 if (!Suspicious) return;
5170
5171 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00005172 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
5173 CC))
John McCall323ed742010-05-06 08:58:33 +00005174 return;
5175
John McCall323ed742010-05-06 08:58:33 +00005176 // ...then check whether it would have warned about either of the
5177 // candidates for a signedness conversion to the condition type.
Richard Trieu52541612011-07-21 02:46:28 +00005178 if (E->getType() == T) return;
5179
5180 Suspicious = false;
5181 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
5182 E->getType(), CC, &Suspicious);
5183 if (!Suspicious)
5184 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00005185 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00005186}
5187
5188/// AnalyzeImplicitConversions - Find and report any interesting
5189/// implicit conversions in the given expression. There are a couple
5190/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00005191void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00005192 QualType T = OrigE->getType();
5193 Expr *E = OrigE->IgnoreParenImpCasts();
5194
Douglas Gregorf8b6e152011-10-10 17:38:18 +00005195 if (E->isTypeDependent() || E->isValueDependent())
5196 return;
5197
John McCall323ed742010-05-06 08:58:33 +00005198 // For conditional operators, we analyze the arguments as if they
5199 // were being fed directly into the output.
5200 if (isa<ConditionalOperator>(E)) {
5201 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie9fb1ac52012-05-15 21:57:38 +00005202 CheckConditionalOperator(S, CO, CC, T);
John McCall323ed742010-05-06 08:58:33 +00005203 return;
5204 }
5205
Hans Wennborg88617a22012-08-28 15:44:30 +00005206 // Check implicit argument conversions for function calls.
5207 if (CallExpr *Call = dyn_cast<CallExpr>(E))
5208 CheckImplicitArgumentConversions(S, Call, CC);
5209
John McCall323ed742010-05-06 08:58:33 +00005210 // Go ahead and check any implicit conversions we might have skipped.
5211 // The non-canonical typecheck is just an optimization;
5212 // CheckImplicitConversion will filter out dead implicit conversions.
5213 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00005214 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00005215
Sam Panzer25ffbef2013-03-28 19:07:11 +00005216 // For CompoundAssignmentOperators, check the conversion from the computed
5217 // LHS type to the type of the assignee.
5218 if (CompoundAssignOperator *CAO = dyn_cast<CompoundAssignOperator>(E)) {
5219 QualType LHST = CAO->getComputationLHSType();
5220 // This CheckImplicitConversion would trigger a warning in addition to the
5221 // more serious problem of using NULLs in arithmetic.
5222 // Let the call to CheckImplicitConversion on the child expressions at the
5223 // bottom of this function handle them by filtering those out here.
5224 // Similarly, disable the extra check for shift assignments, since any
5225 // narrowing would be less serious than a too-large shift count.
5226 if (LHST != T &&
5227 T->isIntegralType(S.Context) && LHST->isIntegralType(S.Context) &&
5228 !CAO->isShiftAssignOp() &&
5229 CAO->getRHS()->isNullPointerConstant(S.Context,
5230 Expr::NPC_ValueDependentIsNotNull)
5231 != Expr::NPCK_GNUNull)
5232 CheckImplicitConversion(S, CAO->getRHS(), T, CC);
5233 }
5234
John McCall323ed742010-05-06 08:58:33 +00005235 // Now continue drilling into this expression.
5236
5237 // Skip past explicit casts.
5238 if (isa<ExplicitCastExpr>(E)) {
5239 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00005240 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005241 }
5242
John McCallbeb22aa2010-11-09 23:24:47 +00005243 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5244 // Do a somewhat different check with comparison operators.
5245 if (BO->isComparisonOp())
5246 return AnalyzeComparison(S, BO);
5247
Sam Panzer25ffbef2013-03-28 19:07:11 +00005248 // And with assignments.
5249 if (BO->isAssignmentOp())
John McCallbeb22aa2010-11-09 23:24:47 +00005250 return AnalyzeAssignment(S, BO);
5251 }
John McCall323ed742010-05-06 08:58:33 +00005252
5253 // These break the otherwise-useful invariant below. Fortunately,
5254 // we don't really need to recurse into them, because any internal
5255 // expressions should have been analyzed already when they were
5256 // built into statements.
5257 if (isa<StmtExpr>(E)) return;
5258
5259 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005260 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00005261
5262 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00005263 CC = E->getExprLoc();
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005264 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
5265 bool IsLogicalOperator = BO && BO->isLogicalOp();
5266 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor54042f12012-02-09 10:18:50 +00005267 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor503384f2012-02-09 00:47:04 +00005268 if (!ChildExpr)
5269 continue;
5270
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005271 if (IsLogicalOperator &&
5272 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
5273 // Ignore checking string literals that are in logical operators.
5274 continue;
5275 AnalyzeImplicitConversions(S, ChildExpr, CC);
5276 }
John McCall323ed742010-05-06 08:58:33 +00005277}
5278
5279} // end anonymous namespace
5280
5281/// Diagnoses "dangerous" implicit conversions within the given
5282/// expression (which is a full expression). Implements -Wconversion
5283/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00005284///
5285/// \param CC the "context" location of the implicit conversion, i.e.
5286/// the most location of the syntactic entity requiring the implicit
5287/// conversion
5288void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00005289 // Don't diagnose in unevaluated contexts.
David Blaikie71f55f72012-08-06 22:47:24 +00005290 if (isUnevaluatedContext())
John McCall323ed742010-05-06 08:58:33 +00005291 return;
5292
5293 // Don't diagnose for value- or type-dependent expressions.
5294 if (E->isTypeDependent() || E->isValueDependent())
5295 return;
5296
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005297 // Check for array bounds violations in cases where the check isn't triggered
5298 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
5299 // ArraySubscriptExpr is on the RHS of a variable initialization.
5300 CheckArrayAccess(E);
5301
John McCallb4eb64d2010-10-08 02:01:28 +00005302 // This is not the right CC for (e.g.) a variable initialization.
5303 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005304}
5305
Fariborz Jahanianad48a502013-01-24 22:11:45 +00005306/// Diagnose when expression is an integer constant expression and its evaluation
5307/// results in integer overflow
5308void Sema::CheckForIntOverflow (Expr *E) {
Fariborz Jahanian1fd8d462013-03-15 20:47:07 +00005309 if (isa<BinaryOperator>(E->IgnoreParens())) {
Fariborz Jahanianad48a502013-01-24 22:11:45 +00005310 llvm::SmallVector<PartialDiagnosticAt, 4> Diags;
5311 E->EvaluateForOverflow(Context, &Diags);
5312 }
5313}
5314
Richard Smith6c3af3d2013-01-17 01:17:56 +00005315namespace {
5316/// \brief Visitor for expressions which looks for unsequenced operations on the
5317/// same object.
5318class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
5319 /// \brief A tree of sequenced regions within an expression. Two regions are
5320 /// unsequenced if one is an ancestor or a descendent of the other. When we
5321 /// finish processing an expression with sequencing, such as a comma
5322 /// expression, we fold its tree nodes into its parent, since they are
5323 /// unsequenced with respect to nodes we will visit later.
5324 class SequenceTree {
5325 struct Value {
5326 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
5327 unsigned Parent : 31;
5328 bool Merged : 1;
5329 };
5330 llvm::SmallVector<Value, 8> Values;
5331
5332 public:
5333 /// \brief A region within an expression which may be sequenced with respect
5334 /// to some other region.
5335 class Seq {
5336 explicit Seq(unsigned N) : Index(N) {}
5337 unsigned Index;
5338 friend class SequenceTree;
5339 public:
5340 Seq() : Index(0) {}
5341 };
5342
5343 SequenceTree() { Values.push_back(Value(0)); }
5344 Seq root() const { return Seq(0); }
5345
5346 /// \brief Create a new sequence of operations, which is an unsequenced
5347 /// subset of \p Parent. This sequence of operations is sequenced with
5348 /// respect to other children of \p Parent.
5349 Seq allocate(Seq Parent) {
5350 Values.push_back(Value(Parent.Index));
5351 return Seq(Values.size() - 1);
5352 }
5353
5354 /// \brief Merge a sequence of operations into its parent.
5355 void merge(Seq S) {
5356 Values[S.Index].Merged = true;
5357 }
5358
5359 /// \brief Determine whether two operations are unsequenced. This operation
5360 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
5361 /// should have been merged into its parent as appropriate.
5362 bool isUnsequenced(Seq Cur, Seq Old) {
5363 unsigned C = representative(Cur.Index);
5364 unsigned Target = representative(Old.Index);
5365 while (C >= Target) {
5366 if (C == Target)
5367 return true;
5368 C = Values[C].Parent;
5369 }
5370 return false;
5371 }
5372
5373 private:
5374 /// \brief Pick a representative for a sequence.
5375 unsigned representative(unsigned K) {
5376 if (Values[K].Merged)
5377 // Perform path compression as we go.
5378 return Values[K].Parent = representative(Values[K].Parent);
5379 return K;
5380 }
5381 };
5382
5383 /// An object for which we can track unsequenced uses.
5384 typedef NamedDecl *Object;
5385
5386 /// Different flavors of object usage which we track. We only track the
5387 /// least-sequenced usage of each kind.
5388 enum UsageKind {
5389 /// A read of an object. Multiple unsequenced reads are OK.
5390 UK_Use,
5391 /// A modification of an object which is sequenced before the value
5392 /// computation of the expression, such as ++n.
5393 UK_ModAsValue,
5394 /// A modification of an object which is not sequenced before the value
5395 /// computation of the expression, such as n++.
5396 UK_ModAsSideEffect,
5397
5398 UK_Count = UK_ModAsSideEffect + 1
5399 };
5400
5401 struct Usage {
5402 Usage() : Use(0), Seq() {}
5403 Expr *Use;
5404 SequenceTree::Seq Seq;
5405 };
5406
5407 struct UsageInfo {
5408 UsageInfo() : Diagnosed(false) {}
5409 Usage Uses[UK_Count];
5410 /// Have we issued a diagnostic for this variable already?
5411 bool Diagnosed;
5412 };
5413 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
5414
5415 Sema &SemaRef;
5416 /// Sequenced regions within the expression.
5417 SequenceTree Tree;
5418 /// Declaration modifications and references which we have seen.
5419 UsageInfoMap UsageMap;
5420 /// The region we are currently within.
5421 SequenceTree::Seq Region;
5422 /// Filled in with declarations which were modified as a side-effect
5423 /// (that is, post-increment operations).
5424 llvm::SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smith1a2dcd52013-01-17 23:18:09 +00005425 /// Expressions to check later. We defer checking these to reduce
5426 /// stack usage.
5427 llvm::SmallVectorImpl<Expr*> &WorkList;
Richard Smith6c3af3d2013-01-17 01:17:56 +00005428
5429 /// RAII object wrapping the visitation of a sequenced subexpression of an
5430 /// expression. At the end of this process, the side-effects of the evaluation
5431 /// become sequenced with respect to the value computation of the result, so
5432 /// we downgrade any UK_ModAsSideEffect within the evaluation to
5433 /// UK_ModAsValue.
5434 struct SequencedSubexpression {
5435 SequencedSubexpression(SequenceChecker &Self)
5436 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
5437 Self.ModAsSideEffect = &ModAsSideEffect;
5438 }
5439 ~SequencedSubexpression() {
5440 for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) {
5441 UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first];
5442 U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second;
5443 Self.addUsage(U, ModAsSideEffect[I].first,
5444 ModAsSideEffect[I].second.Use, UK_ModAsValue);
5445 }
5446 Self.ModAsSideEffect = OldModAsSideEffect;
5447 }
5448
5449 SequenceChecker &Self;
5450 llvm::SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
5451 llvm::SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
5452 };
5453
5454 /// \brief Find the object which is produced by the specified expression,
5455 /// if any.
5456 Object getObject(Expr *E, bool Mod) const {
5457 E = E->IgnoreParenCasts();
5458 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5459 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
5460 return getObject(UO->getSubExpr(), Mod);
5461 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5462 if (BO->getOpcode() == BO_Comma)
5463 return getObject(BO->getRHS(), Mod);
5464 if (Mod && BO->isAssignmentOp())
5465 return getObject(BO->getLHS(), Mod);
5466 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
5467 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
5468 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
5469 return ME->getMemberDecl();
5470 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5471 // FIXME: If this is a reference, map through to its value.
5472 return DRE->getDecl();
5473 return 0;
5474 }
5475
5476 /// \brief Note that an object was modified or used by an expression.
5477 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
5478 Usage &U = UI.Uses[UK];
5479 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
5480 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
5481 ModAsSideEffect->push_back(std::make_pair(O, U));
5482 U.Use = Ref;
5483 U.Seq = Region;
5484 }
5485 }
5486 /// \brief Check whether a modification or use conflicts with a prior usage.
5487 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
5488 bool IsModMod) {
5489 if (UI.Diagnosed)
5490 return;
5491
5492 const Usage &U = UI.Uses[OtherKind];
5493 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
5494 return;
5495
5496 Expr *Mod = U.Use;
5497 Expr *ModOrUse = Ref;
5498 if (OtherKind == UK_Use)
5499 std::swap(Mod, ModOrUse);
5500
5501 SemaRef.Diag(Mod->getExprLoc(),
5502 IsModMod ? diag::warn_unsequenced_mod_mod
5503 : diag::warn_unsequenced_mod_use)
5504 << O << SourceRange(ModOrUse->getExprLoc());
5505 UI.Diagnosed = true;
5506 }
5507
5508 void notePreUse(Object O, Expr *Use) {
5509 UsageInfo &U = UsageMap[O];
5510 // Uses conflict with other modifications.
5511 checkUsage(O, U, Use, UK_ModAsValue, false);
5512 }
5513 void notePostUse(Object O, Expr *Use) {
5514 UsageInfo &U = UsageMap[O];
5515 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
5516 addUsage(U, O, Use, UK_Use);
5517 }
5518
5519 void notePreMod(Object O, Expr *Mod) {
5520 UsageInfo &U = UsageMap[O];
5521 // Modifications conflict with other modifications and with uses.
5522 checkUsage(O, U, Mod, UK_ModAsValue, true);
5523 checkUsage(O, U, Mod, UK_Use, false);
5524 }
5525 void notePostMod(Object O, Expr *Use, UsageKind UK) {
5526 UsageInfo &U = UsageMap[O];
5527 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
5528 addUsage(U, O, Use, UK);
5529 }
5530
5531public:
Richard Smith1a2dcd52013-01-17 23:18:09 +00005532 SequenceChecker(Sema &S, Expr *E,
5533 llvm::SmallVectorImpl<Expr*> &WorkList)
Richard Smithe5096c82013-01-17 01:40:50 +00005534 : EvaluatedExprVisitor<SequenceChecker>(S.Context), SemaRef(S),
Richard Smith1a2dcd52013-01-17 23:18:09 +00005535 Region(Tree.root()), ModAsSideEffect(0), WorkList(WorkList) {
Richard Smith6c3af3d2013-01-17 01:17:56 +00005536 Visit(E);
5537 }
5538
5539 void VisitStmt(Stmt *S) {
5540 // Skip all statements which aren't expressions for now.
5541 }
5542
5543 void VisitExpr(Expr *E) {
5544 // By default, just recurse to evaluated subexpressions.
Richard Smithe5096c82013-01-17 01:40:50 +00005545 EvaluatedExprVisitor<SequenceChecker>::VisitStmt(E);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005546 }
5547
5548 void VisitCastExpr(CastExpr *E) {
5549 Object O = Object();
5550 if (E->getCastKind() == CK_LValueToRValue)
5551 O = getObject(E->getSubExpr(), false);
5552
5553 if (O)
5554 notePreUse(O, E);
5555 VisitExpr(E);
5556 if (O)
5557 notePostUse(O, E);
5558 }
5559
5560 void VisitBinComma(BinaryOperator *BO) {
5561 // C++11 [expr.comma]p1:
5562 // Every value computation and side effect associated with the left
5563 // expression is sequenced before every value computation and side
5564 // effect associated with the right expression.
5565 SequenceTree::Seq LHS = Tree.allocate(Region);
5566 SequenceTree::Seq RHS = Tree.allocate(Region);
5567 SequenceTree::Seq OldRegion = Region;
5568
5569 {
5570 SequencedSubexpression SeqLHS(*this);
5571 Region = LHS;
5572 Visit(BO->getLHS());
5573 }
5574
5575 Region = RHS;
5576 Visit(BO->getRHS());
5577
5578 Region = OldRegion;
5579
5580 // Forget that LHS and RHS are sequenced. They are both unsequenced
5581 // with respect to other stuff.
5582 Tree.merge(LHS);
5583 Tree.merge(RHS);
5584 }
5585
5586 void VisitBinAssign(BinaryOperator *BO) {
5587 // The modification is sequenced after the value computation of the LHS
5588 // and RHS, so check it before inspecting the operands and update the
5589 // map afterwards.
5590 Object O = getObject(BO->getLHS(), true);
5591 if (!O)
5592 return VisitExpr(BO);
5593
5594 notePreMod(O, BO);
5595
5596 // C++11 [expr.ass]p7:
5597 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
5598 // only once.
5599 //
5600 // Therefore, for a compound assignment operator, O is considered used
5601 // everywhere except within the evaluation of E1 itself.
5602 if (isa<CompoundAssignOperator>(BO))
5603 notePreUse(O, BO);
5604
5605 Visit(BO->getLHS());
5606
5607 if (isa<CompoundAssignOperator>(BO))
5608 notePostUse(O, BO);
5609
5610 Visit(BO->getRHS());
5611
5612 notePostMod(O, BO, UK_ModAsValue);
5613 }
5614 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
5615 VisitBinAssign(CAO);
5616 }
5617
5618 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
5619 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
5620 void VisitUnaryPreIncDec(UnaryOperator *UO) {
5621 Object O = getObject(UO->getSubExpr(), true);
5622 if (!O)
5623 return VisitExpr(UO);
5624
5625 notePreMod(O, UO);
5626 Visit(UO->getSubExpr());
5627 notePostMod(O, UO, UK_ModAsValue);
5628 }
5629
5630 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
5631 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
5632 void VisitUnaryPostIncDec(UnaryOperator *UO) {
5633 Object O = getObject(UO->getSubExpr(), true);
5634 if (!O)
5635 return VisitExpr(UO);
5636
5637 notePreMod(O, UO);
5638 Visit(UO->getSubExpr());
5639 notePostMod(O, UO, UK_ModAsSideEffect);
5640 }
5641
5642 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
5643 void VisitBinLOr(BinaryOperator *BO) {
5644 // The side-effects of the LHS of an '&&' are sequenced before the
5645 // value computation of the RHS, and hence before the value computation
5646 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
5647 // as if they were unconditionally sequenced.
5648 {
5649 SequencedSubexpression Sequenced(*this);
5650 Visit(BO->getLHS());
5651 }
5652
5653 bool Result;
5654 if (!BO->getLHS()->isValueDependent() &&
Richard Smith995e4a72013-01-17 22:06:26 +00005655 BO->getLHS()->EvaluateAsBooleanCondition(Result, SemaRef.Context)) {
5656 if (!Result)
5657 Visit(BO->getRHS());
5658 } else {
5659 // Check for unsequenced operations in the RHS, treating it as an
5660 // entirely separate evaluation.
5661 //
5662 // FIXME: If there are operations in the RHS which are unsequenced
5663 // with respect to operations outside the RHS, and those operations
5664 // are unconditionally evaluated, diagnose them.
Richard Smith1a2dcd52013-01-17 23:18:09 +00005665 WorkList.push_back(BO->getRHS());
Richard Smith995e4a72013-01-17 22:06:26 +00005666 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00005667 }
5668 void VisitBinLAnd(BinaryOperator *BO) {
5669 {
5670 SequencedSubexpression Sequenced(*this);
5671 Visit(BO->getLHS());
5672 }
5673
5674 bool Result;
5675 if (!BO->getLHS()->isValueDependent() &&
Richard Smith995e4a72013-01-17 22:06:26 +00005676 BO->getLHS()->EvaluateAsBooleanCondition(Result, SemaRef.Context)) {
5677 if (Result)
5678 Visit(BO->getRHS());
5679 } else {
Richard Smith1a2dcd52013-01-17 23:18:09 +00005680 WorkList.push_back(BO->getRHS());
Richard Smith995e4a72013-01-17 22:06:26 +00005681 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00005682 }
5683
5684 // Only visit the condition, unless we can be sure which subexpression will
5685 // be chosen.
5686 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
5687 SequencedSubexpression Sequenced(*this);
5688 Visit(CO->getCond());
5689
5690 bool Result;
5691 if (!CO->getCond()->isValueDependent() &&
5692 CO->getCond()->EvaluateAsBooleanCondition(Result, SemaRef.Context))
5693 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith995e4a72013-01-17 22:06:26 +00005694 else {
Richard Smith1a2dcd52013-01-17 23:18:09 +00005695 WorkList.push_back(CO->getTrueExpr());
5696 WorkList.push_back(CO->getFalseExpr());
Richard Smith995e4a72013-01-17 22:06:26 +00005697 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00005698 }
5699
5700 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
5701 if (!CCE->isListInitialization())
5702 return VisitExpr(CCE);
5703
5704 // In C++11, list initializations are sequenced.
5705 llvm::SmallVector<SequenceTree::Seq, 32> Elts;
5706 SequenceTree::Seq Parent = Region;
5707 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
5708 E = CCE->arg_end();
5709 I != E; ++I) {
5710 Region = Tree.allocate(Parent);
5711 Elts.push_back(Region);
5712 Visit(*I);
5713 }
5714
5715 // Forget that the initializers are sequenced.
5716 Region = Parent;
5717 for (unsigned I = 0; I < Elts.size(); ++I)
5718 Tree.merge(Elts[I]);
5719 }
5720
5721 void VisitInitListExpr(InitListExpr *ILE) {
5722 if (!SemaRef.getLangOpts().CPlusPlus11)
5723 return VisitExpr(ILE);
5724
5725 // In C++11, list initializations are sequenced.
5726 llvm::SmallVector<SequenceTree::Seq, 32> Elts;
5727 SequenceTree::Seq Parent = Region;
5728 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
5729 Expr *E = ILE->getInit(I);
5730 if (!E) continue;
5731 Region = Tree.allocate(Parent);
5732 Elts.push_back(Region);
5733 Visit(E);
5734 }
5735
5736 // Forget that the initializers are sequenced.
5737 Region = Parent;
5738 for (unsigned I = 0; I < Elts.size(); ++I)
5739 Tree.merge(Elts[I]);
5740 }
5741};
5742}
5743
5744void Sema::CheckUnsequencedOperations(Expr *E) {
Richard Smith1a2dcd52013-01-17 23:18:09 +00005745 llvm::SmallVector<Expr*, 8> WorkList;
5746 WorkList.push_back(E);
5747 while (!WorkList.empty()) {
5748 Expr *Item = WorkList.back();
5749 WorkList.pop_back();
5750 SequenceChecker(*this, Item, WorkList);
5751 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00005752}
5753
Fariborz Jahanianad48a502013-01-24 22:11:45 +00005754void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
5755 bool IsConstexpr) {
Richard Smith6c3af3d2013-01-17 01:17:56 +00005756 CheckImplicitConversions(E, CheckLoc);
5757 CheckUnsequencedOperations(E);
Fariborz Jahanianad48a502013-01-24 22:11:45 +00005758 if (!IsConstexpr && !E->isValueDependent())
5759 CheckForIntOverflow(E);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005760}
5761
John McCall15d7d122010-11-11 03:21:53 +00005762void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
5763 FieldDecl *BitField,
5764 Expr *Init) {
5765 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
5766}
5767
Mike Stumpf8c49212010-01-21 03:59:47 +00005768/// CheckParmsForFunctionDef - Check that the parameters of the given
5769/// function are appropriate for the definition of a function. This
5770/// takes care of any checks that cannot be performed on the
5771/// declaration itself, e.g., that the types of each of the function
5772/// parameters are complete.
Douglas Gregor82aa7132010-11-01 18:37:59 +00005773bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
5774 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00005775 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00005776 for (; P != PEnd; ++P) {
5777 ParmVarDecl *Param = *P;
5778
Mike Stumpf8c49212010-01-21 03:59:47 +00005779 // C99 6.7.5.3p4: the parameters in a parameter type list in a
5780 // function declarator that is part of a function definition of
5781 // that function shall not have incomplete type.
5782 //
5783 // This is also C++ [dcl.fct]p6.
5784 if (!Param->isInvalidDecl() &&
5785 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00005786 diag::err_typecheck_decl_incomplete_type)) {
Mike Stumpf8c49212010-01-21 03:59:47 +00005787 Param->setInvalidDecl();
5788 HasInvalidParm = true;
5789 }
5790
5791 // C99 6.9.1p5: If the declarator includes a parameter type list, the
5792 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00005793 if (CheckParameterNames &&
5794 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00005795 !Param->isImplicit() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00005796 !getLangOpts().CPlusPlus)
Mike Stumpf8c49212010-01-21 03:59:47 +00005797 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00005798
5799 // C99 6.7.5.3p12:
5800 // If the function declarator is not part of a definition of that
5801 // function, parameters may have incomplete type and may use the [*]
5802 // notation in their sequences of declarator specifiers to specify
5803 // variable length array types.
5804 QualType PType = Param->getOriginalType();
5805 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
5806 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitfc093362013-03-01 21:41:22 +00005807 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigd17e3402010-02-01 05:02:49 +00005808 // information is added for it.
5809 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
5810 }
5811 }
Mike Stumpf8c49212010-01-21 03:59:47 +00005812 }
5813
5814 return HasInvalidParm;
5815}
John McCallb7f4ffe2010-08-12 21:44:57 +00005816
5817/// CheckCastAlign - Implements -Wcast-align, which warns when a
5818/// pointer cast increases the alignment requirements.
5819void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
5820 // This is actually a lot of work to potentially be doing on every
5821 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00005822 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
5823 TRange.getBegin())
David Blaikied6471f72011-09-25 23:23:43 +00005824 == DiagnosticsEngine::Ignored)
John McCallb7f4ffe2010-08-12 21:44:57 +00005825 return;
5826
5827 // Ignore dependent types.
5828 if (T->isDependentType() || Op->getType()->isDependentType())
5829 return;
5830
5831 // Require that the destination be a pointer type.
5832 const PointerType *DestPtr = T->getAs<PointerType>();
5833 if (!DestPtr) return;
5834
5835 // If the destination has alignment 1, we're done.
5836 QualType DestPointee = DestPtr->getPointeeType();
5837 if (DestPointee->isIncompleteType()) return;
5838 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
5839 if (DestAlign.isOne()) return;
5840
5841 // Require that the source be a pointer type.
5842 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
5843 if (!SrcPtr) return;
5844 QualType SrcPointee = SrcPtr->getPointeeType();
5845
5846 // Whitelist casts from cv void*. We already implicitly
5847 // whitelisted casts to cv void*, since they have alignment 1.
5848 // Also whitelist casts involving incomplete types, which implicitly
5849 // includes 'void'.
5850 if (SrcPointee->isIncompleteType()) return;
5851
5852 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
5853 if (SrcAlign >= DestAlign) return;
5854
5855 Diag(TRange.getBegin(), diag::warn_cast_align)
5856 << Op->getType() << T
5857 << static_cast<unsigned>(SrcAlign.getQuantity())
5858 << static_cast<unsigned>(DestAlign.getQuantity())
5859 << TRange << Op->getSourceRange();
5860}
5861
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005862static const Type* getElementType(const Expr *BaseExpr) {
5863 const Type* EltType = BaseExpr->getType().getTypePtr();
5864 if (EltType->isAnyPointerType())
5865 return EltType->getPointeeType().getTypePtr();
5866 else if (EltType->isArrayType())
5867 return EltType->getBaseElementTypeUnsafe();
5868 return EltType;
5869}
5870
Chandler Carruthc2684342011-08-05 09:10:50 +00005871/// \brief Check whether this array fits the idiom of a size-one tail padded
5872/// array member of a struct.
5873///
5874/// We avoid emitting out-of-bounds access warnings for such arrays as they are
5875/// commonly used to emulate flexible arrays in C89 code.
5876static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
5877 const NamedDecl *ND) {
5878 if (Size != 1 || !ND) return false;
5879
5880 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
5881 if (!FD) return false;
5882
5883 // Don't consider sizes resulting from macro expansions or template argument
5884 // substitution to form C89 tail-padded arrays.
Sean Callanand2cf3482012-05-04 18:22:53 +00005885
5886 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00005887 while (TInfo) {
5888 TypeLoc TL = TInfo->getTypeLoc();
5889 // Look through typedefs.
David Blaikie39e6ab42013-02-18 22:06:02 +00005890 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
5891 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00005892 TInfo = TDL->getTypeSourceInfo();
5893 continue;
5894 }
David Blaikie39e6ab42013-02-18 22:06:02 +00005895 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
5896 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier5e253012013-02-06 00:58:34 +00005897 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
5898 return false;
5899 }
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00005900 break;
Sean Callanand2cf3482012-05-04 18:22:53 +00005901 }
Chandler Carruthc2684342011-08-05 09:10:50 +00005902
5903 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gay381711c2011-11-29 22:43:53 +00005904 if (!RD) return false;
5905 if (RD->isUnion()) return false;
5906 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
5907 if (!CRD->isStandardLayout()) return false;
5908 }
Chandler Carruthc2684342011-08-05 09:10:50 +00005909
Benjamin Kramer22d4fed2011-08-06 03:04:42 +00005910 // See if this is the last field decl in the record.
5911 const Decl *D = FD;
5912 while ((D = D->getNextDeclInContext()))
5913 if (isa<FieldDecl>(D))
5914 return false;
5915 return true;
Chandler Carruthc2684342011-08-05 09:10:50 +00005916}
5917
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005918void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005919 const ArraySubscriptExpr *ASE,
Richard Smith25b009a2011-12-16 19:31:14 +00005920 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman92b670e2012-02-27 21:21:40 +00005921 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005922 if (IndexExpr->isValueDependent())
5923 return;
5924
Matt Beaumont-Gay8ef8f432011-12-12 22:35:02 +00005925 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005926 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00005927 const ConstantArrayType *ArrayTy =
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005928 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00005929 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00005930 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00005931
Chandler Carruth34064582011-02-17 20:55:08 +00005932 llvm::APSInt index;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005933 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00005934 return;
Richard Smith25b009a2011-12-16 19:31:14 +00005935 if (IndexNegated)
5936 index = -index;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00005937
Chandler Carruthba447122011-08-05 08:07:29 +00005938 const NamedDecl *ND = NULL;
Chandler Carruthba447122011-08-05 08:07:29 +00005939 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
5940 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruthc2684342011-08-05 09:10:50 +00005941 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruthba447122011-08-05 08:07:29 +00005942 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruthba447122011-08-05 08:07:29 +00005943
Ted Kremenek9e060ca2011-02-23 23:06:04 +00005944 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00005945 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00005946 if (!size.isStrictlyPositive())
5947 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005948
5949 const Type* BaseType = getElementType(BaseExpr);
Nico Weberde5998f2011-09-17 22:59:41 +00005950 if (BaseType != EffectiveType) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005951 // Make sure we're comparing apples to apples when comparing index to size
5952 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
5953 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhraind10f4bc2011-08-10 19:47:25 +00005954 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhrain18f16972011-08-10 18:49:28 +00005955 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005956 if (ptrarith_typesize != array_typesize) {
5957 // There's a cast to a different size type involved
5958 uint64_t ratio = array_typesize / ptrarith_typesize;
5959 // TODO: Be smarter about handling cases where array_typesize is not a
5960 // multiple of ptrarith_typesize
5961 if (ptrarith_typesize * ratio == array_typesize)
5962 size *= llvm::APInt(size.getBitWidth(), ratio);
5963 }
5964 }
5965
Chandler Carruth34064582011-02-17 20:55:08 +00005966 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00005967 index = index.zext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00005968 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00005969 size = size.zext(index.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00005970
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005971 // For array subscripting the index must be less than size, but for pointer
5972 // arithmetic also allow the index (offset) to be equal to size since
5973 // computing the next address after the end of the array is legal and
5974 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman92b670e2012-02-27 21:21:40 +00005975 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruthba447122011-08-05 08:07:29 +00005976 return;
5977
5978 // Also don't warn for arrays of size 1 which are members of some
5979 // structure. These are often used to approximate flexible arrays in C89
5980 // code.
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005981 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00005982 return;
Chandler Carruth34064582011-02-17 20:55:08 +00005983
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005984 // Suppress the warning if the subscript expression (as identified by the
5985 // ']' location) and the index expression are both from macro expansions
5986 // within a system header.
5987 if (ASE) {
5988 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
5989 ASE->getRBracketLoc());
5990 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
5991 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
5992 IndexExpr->getLocStart());
5993 if (SourceMgr.isFromSameFile(RBracketLoc, IndexLoc))
5994 return;
5995 }
5996 }
5997
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005998 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005999 if (ASE)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006000 DiagID = diag::warn_array_index_exceeds_bounds;
6001
6002 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6003 PDiag(DiagID) << index.toString(10, true)
6004 << size.toString(10, true)
6005 << (unsigned)size.getLimitedValue(~0U)
6006 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00006007 } else {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006008 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006009 if (!ASE) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006010 DiagID = diag::warn_ptr_arith_precedes_bounds;
6011 if (index.isNegative()) index = -index;
6012 }
6013
6014 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6015 PDiag(DiagID) << index.toString(10, true)
6016 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00006017 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00006018
Matt Beaumont-Gaycfbc5b52011-11-29 19:27:11 +00006019 if (!ND) {
6020 // Try harder to find a NamedDecl to point at in the note.
6021 while (const ArraySubscriptExpr *ASE =
6022 dyn_cast<ArraySubscriptExpr>(BaseExpr))
6023 BaseExpr = ASE->getBase()->IgnoreParenCasts();
6024 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
6025 ND = dyn_cast<NamedDecl>(DRE->getDecl());
6026 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
6027 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
6028 }
6029
Chandler Carruth35001ca2011-02-17 21:10:52 +00006030 if (ND)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006031 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
6032 PDiag(diag::note_array_index_out_of_bounds)
6033 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00006034}
6035
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006036void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006037 int AllowOnePastEnd = 0;
6038 while (expr) {
6039 expr = expr->IgnoreParenImpCasts();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006040 switch (expr->getStmtClass()) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006041 case Stmt::ArraySubscriptExprClass: {
6042 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006043 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006044 AllowOnePastEnd > 0);
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006045 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006046 }
6047 case Stmt::UnaryOperatorClass: {
6048 // Only unwrap the * and & unary operators
6049 const UnaryOperator *UO = cast<UnaryOperator>(expr);
6050 expr = UO->getSubExpr();
6051 switch (UO->getOpcode()) {
6052 case UO_AddrOf:
6053 AllowOnePastEnd++;
6054 break;
6055 case UO_Deref:
6056 AllowOnePastEnd--;
6057 break;
6058 default:
6059 return;
6060 }
6061 break;
6062 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006063 case Stmt::ConditionalOperatorClass: {
6064 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
6065 if (const Expr *lhs = cond->getLHS())
6066 CheckArrayAccess(lhs);
6067 if (const Expr *rhs = cond->getRHS())
6068 CheckArrayAccess(rhs);
6069 return;
6070 }
6071 default:
6072 return;
6073 }
Peter Collingbournef111d932011-04-15 00:35:48 +00006074 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006075}
John McCallf85e1932011-06-15 23:02:42 +00006076
6077//===--- CHECK: Objective-C retain cycles ----------------------------------//
6078
6079namespace {
6080 struct RetainCycleOwner {
6081 RetainCycleOwner() : Variable(0), Indirect(false) {}
6082 VarDecl *Variable;
6083 SourceRange Range;
6084 SourceLocation Loc;
6085 bool Indirect;
6086
6087 void setLocsFrom(Expr *e) {
6088 Loc = e->getExprLoc();
6089 Range = e->getSourceRange();
6090 }
6091 };
6092}
6093
6094/// Consider whether capturing the given variable can possibly lead to
6095/// a retain cycle.
6096static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledruf3477c12012-09-27 10:16:10 +00006097 // In ARC, it's captured strongly iff the variable has __strong
John McCallf85e1932011-06-15 23:02:42 +00006098 // lifetime. In MRR, it's captured strongly if the variable is
6099 // __block and has an appropriate type.
6100 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
6101 return false;
6102
6103 owner.Variable = var;
Jordan Rosee10f4d32012-09-15 02:48:31 +00006104 if (ref)
6105 owner.setLocsFrom(ref);
John McCallf85e1932011-06-15 23:02:42 +00006106 return true;
6107}
6108
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006109static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCallf85e1932011-06-15 23:02:42 +00006110 while (true) {
6111 e = e->IgnoreParens();
6112 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
6113 switch (cast->getCastKind()) {
6114 case CK_BitCast:
6115 case CK_LValueBitCast:
6116 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00006117 case CK_ARCReclaimReturnedObject:
John McCallf85e1932011-06-15 23:02:42 +00006118 e = cast->getSubExpr();
6119 continue;
6120
John McCallf85e1932011-06-15 23:02:42 +00006121 default:
6122 return false;
6123 }
6124 }
6125
6126 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
6127 ObjCIvarDecl *ivar = ref->getDecl();
6128 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
6129 return false;
6130
6131 // Try to find a retain cycle in the base.
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006132 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCallf85e1932011-06-15 23:02:42 +00006133 return false;
6134
6135 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
6136 owner.Indirect = true;
6137 return true;
6138 }
6139
6140 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
6141 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
6142 if (!var) return false;
6143 return considerVariable(var, ref, owner);
6144 }
6145
John McCallf85e1932011-06-15 23:02:42 +00006146 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
6147 if (member->isArrow()) return false;
6148
6149 // Don't count this as an indirect ownership.
6150 e = member->getBase();
6151 continue;
6152 }
6153
John McCall4b9c2d22011-11-06 09:01:30 +00006154 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
6155 // Only pay attention to pseudo-objects on property references.
6156 ObjCPropertyRefExpr *pre
6157 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
6158 ->IgnoreParens());
6159 if (!pre) return false;
6160 if (pre->isImplicitProperty()) return false;
6161 ObjCPropertyDecl *property = pre->getExplicitProperty();
6162 if (!property->isRetaining() &&
6163 !(property->getPropertyIvarDecl() &&
6164 property->getPropertyIvarDecl()->getType()
6165 .getObjCLifetime() == Qualifiers::OCL_Strong))
6166 return false;
6167
6168 owner.Indirect = true;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006169 if (pre->isSuperReceiver()) {
6170 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
6171 if (!owner.Variable)
6172 return false;
6173 owner.Loc = pre->getLocation();
6174 owner.Range = pre->getSourceRange();
6175 return true;
6176 }
John McCall4b9c2d22011-11-06 09:01:30 +00006177 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
6178 ->getSourceExpr());
6179 continue;
6180 }
6181
John McCallf85e1932011-06-15 23:02:42 +00006182 // Array ivars?
6183
6184 return false;
6185 }
6186}
6187
6188namespace {
6189 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
6190 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
6191 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
6192 Variable(variable), Capturer(0) {}
6193
6194 VarDecl *Variable;
6195 Expr *Capturer;
6196
6197 void VisitDeclRefExpr(DeclRefExpr *ref) {
6198 if (ref->getDecl() == Variable && !Capturer)
6199 Capturer = ref;
6200 }
6201
John McCallf85e1932011-06-15 23:02:42 +00006202 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
6203 if (Capturer) return;
6204 Visit(ref->getBase());
6205 if (Capturer && ref->isFreeIvar())
6206 Capturer = ref;
6207 }
6208
6209 void VisitBlockExpr(BlockExpr *block) {
6210 // Look inside nested blocks
6211 if (block->getBlockDecl()->capturesVariable(Variable))
6212 Visit(block->getBlockDecl()->getBody());
6213 }
Fariborz Jahanian7e2e4c32012-08-31 20:04:47 +00006214
6215 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
6216 if (Capturer) return;
6217 if (OVE->getSourceExpr())
6218 Visit(OVE->getSourceExpr());
6219 }
John McCallf85e1932011-06-15 23:02:42 +00006220 };
6221}
6222
6223/// Check whether the given argument is a block which captures a
6224/// variable.
6225static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
6226 assert(owner.Variable && owner.Loc.isValid());
6227
6228 e = e->IgnoreParenCasts();
Jordan Rose1fac58a2012-09-17 17:54:30 +00006229
6230 // Look through [^{...} copy] and Block_copy(^{...}).
6231 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
6232 Selector Cmd = ME->getSelector();
6233 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
6234 e = ME->getInstanceReceiver();
6235 if (!e)
6236 return 0;
6237 e = e->IgnoreParenCasts();
6238 }
6239 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
6240 if (CE->getNumArgs() == 1) {
6241 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekd13eff62012-10-02 04:36:54 +00006242 if (Fn) {
6243 const IdentifierInfo *FnI = Fn->getIdentifier();
6244 if (FnI && FnI->isStr("_Block_copy")) {
6245 e = CE->getArg(0)->IgnoreParenCasts();
6246 }
6247 }
Jordan Rose1fac58a2012-09-17 17:54:30 +00006248 }
6249 }
6250
John McCallf85e1932011-06-15 23:02:42 +00006251 BlockExpr *block = dyn_cast<BlockExpr>(e);
6252 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
6253 return 0;
6254
6255 FindCaptureVisitor visitor(S.Context, owner.Variable);
6256 visitor.Visit(block->getBlockDecl()->getBody());
6257 return visitor.Capturer;
6258}
6259
6260static void diagnoseRetainCycle(Sema &S, Expr *capturer,
6261 RetainCycleOwner &owner) {
6262 assert(capturer);
6263 assert(owner.Variable && owner.Loc.isValid());
6264
6265 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
6266 << owner.Variable << capturer->getSourceRange();
6267 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
6268 << owner.Indirect << owner.Range;
6269}
6270
6271/// Check for a keyword selector that starts with the word 'add' or
6272/// 'set'.
6273static bool isSetterLikeSelector(Selector sel) {
6274 if (sel.isUnarySelector()) return false;
6275
Chris Lattner5f9e2722011-07-23 10:55:15 +00006276 StringRef str = sel.getNameForSlot(0);
John McCallf85e1932011-06-15 23:02:42 +00006277 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00006278 if (str.startswith("set"))
John McCallf85e1932011-06-15 23:02:42 +00006279 str = str.substr(3);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00006280 else if (str.startswith("add")) {
6281 // Specially whitelist 'addOperationWithBlock:'.
6282 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
6283 return false;
6284 str = str.substr(3);
6285 }
John McCallf85e1932011-06-15 23:02:42 +00006286 else
6287 return false;
6288
6289 if (str.empty()) return true;
Jordan Rose3f6f51e2013-02-08 22:30:41 +00006290 return !isLowercase(str.front());
John McCallf85e1932011-06-15 23:02:42 +00006291}
6292
6293/// Check a message send to see if it's likely to cause a retain cycle.
6294void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
6295 // Only check instance methods whose selector looks like a setter.
6296 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
6297 return;
6298
6299 // Try to find a variable that the receiver is strongly owned by.
6300 RetainCycleOwner owner;
6301 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006302 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCallf85e1932011-06-15 23:02:42 +00006303 return;
6304 } else {
6305 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
6306 owner.Variable = getCurMethodDecl()->getSelfDecl();
6307 owner.Loc = msg->getSuperLoc();
6308 owner.Range = msg->getSuperLoc();
6309 }
6310
6311 // Check whether the receiver is captured by any of the arguments.
6312 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
6313 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
6314 return diagnoseRetainCycle(*this, capturer, owner);
6315}
6316
6317/// Check a property assign to see if it's likely to cause a retain cycle.
6318void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
6319 RetainCycleOwner owner;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006320 if (!findRetainCycleOwner(*this, receiver, owner))
John McCallf85e1932011-06-15 23:02:42 +00006321 return;
6322
6323 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
6324 diagnoseRetainCycle(*this, capturer, owner);
6325}
6326
Jordan Rosee10f4d32012-09-15 02:48:31 +00006327void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
6328 RetainCycleOwner Owner;
6329 if (!considerVariable(Var, /*DeclRefExpr=*/0, Owner))
6330 return;
6331
6332 // Because we don't have an expression for the variable, we have to set the
6333 // location explicitly here.
6334 Owner.Loc = Var->getLocation();
6335 Owner.Range = Var->getSourceRange();
6336
6337 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
6338 diagnoseRetainCycle(*this, Capturer, Owner);
6339}
6340
Ted Kremenek9d084012012-12-21 08:04:28 +00006341static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
6342 Expr *RHS, bool isProperty) {
6343 // Check if RHS is an Objective-C object literal, which also can get
6344 // immediately zapped in a weak reference. Note that we explicitly
6345 // allow ObjCStringLiterals, since those are designed to never really die.
6346 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenekf530ff72012-12-21 21:59:39 +00006347
Ted Kremenekd3292c82012-12-21 22:46:35 +00006348 // This enum needs to match with the 'select' in
6349 // warn_objc_arc_literal_assign (off-by-1).
6350 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
6351 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
6352 return false;
Ted Kremenekf530ff72012-12-21 21:59:39 +00006353
6354 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenekd3292c82012-12-21 22:46:35 +00006355 << (unsigned) Kind
Ted Kremenek9d084012012-12-21 08:04:28 +00006356 << (isProperty ? 0 : 1)
6357 << RHS->getSourceRange();
Ted Kremenekf530ff72012-12-21 21:59:39 +00006358
6359 return true;
Ted Kremenek9d084012012-12-21 08:04:28 +00006360}
6361
Ted Kremenekb29b30f2012-12-21 19:45:30 +00006362static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
6363 Qualifiers::ObjCLifetime LT,
6364 Expr *RHS, bool isProperty) {
6365 // Strip off any implicit cast added to get to the one ARC-specific.
6366 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
6367 if (cast->getCastKind() == CK_ARCConsumeObject) {
6368 S.Diag(Loc, diag::warn_arc_retained_assign)
6369 << (LT == Qualifiers::OCL_ExplicitNone)
6370 << (isProperty ? 0 : 1)
6371 << RHS->getSourceRange();
6372 return true;
6373 }
6374 RHS = cast->getSubExpr();
6375 }
6376
6377 if (LT == Qualifiers::OCL_Weak &&
6378 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
6379 return true;
6380
6381 return false;
6382}
6383
Ted Kremenekb1ea5102012-12-21 08:04:20 +00006384bool Sema::checkUnsafeAssigns(SourceLocation Loc,
6385 QualType LHS, Expr *RHS) {
6386 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
6387
6388 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
6389 return false;
6390
6391 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
6392 return true;
6393
6394 return false;
6395}
6396
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006397void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
6398 Expr *LHS, Expr *RHS) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006399 QualType LHSType;
6400 // PropertyRef on LHS type need be directly obtained from
6401 // its declaration as it has a PsuedoType.
6402 ObjCPropertyRefExpr *PRE
6403 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
6404 if (PRE && !PRE->isImplicitProperty()) {
6405 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
6406 if (PD)
6407 LHSType = PD->getType();
6408 }
6409
6410 if (LHSType.isNull())
6411 LHSType = LHS->getType();
Jordan Rose7a270482012-09-28 22:21:35 +00006412
6413 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
6414
6415 if (LT == Qualifiers::OCL_Weak) {
6416 DiagnosticsEngine::Level Level =
6417 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
6418 if (Level != DiagnosticsEngine::Ignored)
6419 getCurFunction()->markSafeWeakUse(LHS);
6420 }
6421
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006422 if (checkUnsafeAssigns(Loc, LHSType, RHS))
6423 return;
Jordan Rose7a270482012-09-28 22:21:35 +00006424
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006425 // FIXME. Check for other life times.
6426 if (LT != Qualifiers::OCL_None)
6427 return;
6428
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006429 if (PRE) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006430 if (PRE->isImplicitProperty())
6431 return;
6432 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
6433 if (!PD)
6434 return;
6435
Bill Wendlingad017fa2012-12-20 19:22:21 +00006436 unsigned Attributes = PD->getPropertyAttributes();
6437 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006438 // when 'assign' attribute was not explicitly specified
6439 // by user, ignore it and rely on property type itself
6440 // for lifetime info.
6441 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
6442 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
6443 LHSType->isObjCRetainableType())
6444 return;
6445
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006446 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00006447 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006448 Diag(Loc, diag::warn_arc_retained_property_assign)
6449 << RHS->getSourceRange();
6450 return;
6451 }
6452 RHS = cast->getSubExpr();
6453 }
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006454 }
Bill Wendlingad017fa2012-12-20 19:22:21 +00006455 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb1ea5102012-12-21 08:04:20 +00006456 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
6457 return;
Fariborz Jahanianbd2e27e2012-07-06 21:09:27 +00006458 }
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006459 }
6460}
Dmitri Gribenko625bb562012-02-14 22:14:32 +00006461
6462//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
6463
6464namespace {
6465bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
6466 SourceLocation StmtLoc,
6467 const NullStmt *Body) {
6468 // Do not warn if the body is a macro that expands to nothing, e.g:
6469 //
6470 // #define CALL(x)
6471 // if (condition)
6472 // CALL(0);
6473 //
6474 if (Body->hasLeadingEmptyMacro())
6475 return false;
6476
6477 // Get line numbers of statement and body.
6478 bool StmtLineInvalid;
6479 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
6480 &StmtLineInvalid);
6481 if (StmtLineInvalid)
6482 return false;
6483
6484 bool BodyLineInvalid;
6485 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
6486 &BodyLineInvalid);
6487 if (BodyLineInvalid)
6488 return false;
6489
6490 // Warn if null statement and body are on the same line.
6491 if (StmtLine != BodyLine)
6492 return false;
6493
6494 return true;
6495}
6496} // Unnamed namespace
6497
6498void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
6499 const Stmt *Body,
6500 unsigned DiagID) {
6501 // Since this is a syntactic check, don't emit diagnostic for template
6502 // instantiations, this just adds noise.
6503 if (CurrentInstantiationScope)
6504 return;
6505
6506 // The body should be a null statement.
6507 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
6508 if (!NBody)
6509 return;
6510
6511 // Do the usual checks.
6512 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
6513 return;
6514
6515 Diag(NBody->getSemiLoc(), DiagID);
6516 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
6517}
6518
6519void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
6520 const Stmt *PossibleBody) {
6521 assert(!CurrentInstantiationScope); // Ensured by caller
6522
6523 SourceLocation StmtLoc;
6524 const Stmt *Body;
6525 unsigned DiagID;
6526 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
6527 StmtLoc = FS->getRParenLoc();
6528 Body = FS->getBody();
6529 DiagID = diag::warn_empty_for_body;
6530 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
6531 StmtLoc = WS->getCond()->getSourceRange().getEnd();
6532 Body = WS->getBody();
6533 DiagID = diag::warn_empty_while_body;
6534 } else
6535 return; // Neither `for' nor `while'.
6536
6537 // The body should be a null statement.
6538 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
6539 if (!NBody)
6540 return;
6541
6542 // Skip expensive checks if diagnostic is disabled.
6543 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
6544 DiagnosticsEngine::Ignored)
6545 return;
6546
6547 // Do the usual checks.
6548 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
6549 return;
6550
6551 // `for(...);' and `while(...);' are popular idioms, so in order to keep
6552 // noise level low, emit diagnostics only if for/while is followed by a
6553 // CompoundStmt, e.g.:
6554 // for (int i = 0; i < n; i++);
6555 // {
6556 // a(i);
6557 // }
6558 // or if for/while is followed by a statement with more indentation
6559 // than for/while itself:
6560 // for (int i = 0; i < n; i++);
6561 // a(i);
6562 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
6563 if (!ProbableTypo) {
6564 bool BodyColInvalid;
6565 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
6566 PossibleBody->getLocStart(),
6567 &BodyColInvalid);
6568 if (BodyColInvalid)
6569 return;
6570
6571 bool StmtColInvalid;
6572 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
6573 S->getLocStart(),
6574 &StmtColInvalid);
6575 if (StmtColInvalid)
6576 return;
6577
6578 if (BodyCol > StmtCol)
6579 ProbableTypo = true;
6580 }
6581
6582 if (ProbableTypo) {
6583 Diag(NBody->getSemiLoc(), DiagID);
6584 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
6585 }
6586}
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00006587
6588//===--- Layout compatibility ----------------------------------------------//
6589
6590namespace {
6591
6592bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
6593
6594/// \brief Check if two enumeration types are layout-compatible.
6595bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
6596 // C++11 [dcl.enum] p8:
6597 // Two enumeration types are layout-compatible if they have the same
6598 // underlying type.
6599 return ED1->isComplete() && ED2->isComplete() &&
6600 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
6601}
6602
6603/// \brief Check if two fields are layout-compatible.
6604bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
6605 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
6606 return false;
6607
6608 if (Field1->isBitField() != Field2->isBitField())
6609 return false;
6610
6611 if (Field1->isBitField()) {
6612 // Make sure that the bit-fields are the same length.
6613 unsigned Bits1 = Field1->getBitWidthValue(C);
6614 unsigned Bits2 = Field2->getBitWidthValue(C);
6615
6616 if (Bits1 != Bits2)
6617 return false;
6618 }
6619
6620 return true;
6621}
6622
6623/// \brief Check if two standard-layout structs are layout-compatible.
6624/// (C++11 [class.mem] p17)
6625bool isLayoutCompatibleStruct(ASTContext &C,
6626 RecordDecl *RD1,
6627 RecordDecl *RD2) {
6628 // If both records are C++ classes, check that base classes match.
6629 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
6630 // If one of records is a CXXRecordDecl we are in C++ mode,
6631 // thus the other one is a CXXRecordDecl, too.
6632 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
6633 // Check number of base classes.
6634 if (D1CXX->getNumBases() != D2CXX->getNumBases())
6635 return false;
6636
6637 // Check the base classes.
6638 for (CXXRecordDecl::base_class_const_iterator
6639 Base1 = D1CXX->bases_begin(),
6640 BaseEnd1 = D1CXX->bases_end(),
6641 Base2 = D2CXX->bases_begin();
6642 Base1 != BaseEnd1;
6643 ++Base1, ++Base2) {
6644 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
6645 return false;
6646 }
6647 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
6648 // If only RD2 is a C++ class, it should have zero base classes.
6649 if (D2CXX->getNumBases() > 0)
6650 return false;
6651 }
6652
6653 // Check the fields.
6654 RecordDecl::field_iterator Field2 = RD2->field_begin(),
6655 Field2End = RD2->field_end(),
6656 Field1 = RD1->field_begin(),
6657 Field1End = RD1->field_end();
6658 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
6659 if (!isLayoutCompatible(C, *Field1, *Field2))
6660 return false;
6661 }
6662 if (Field1 != Field1End || Field2 != Field2End)
6663 return false;
6664
6665 return true;
6666}
6667
6668/// \brief Check if two standard-layout unions are layout-compatible.
6669/// (C++11 [class.mem] p18)
6670bool isLayoutCompatibleUnion(ASTContext &C,
6671 RecordDecl *RD1,
6672 RecordDecl *RD2) {
6673 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
6674 for (RecordDecl::field_iterator Field2 = RD2->field_begin(),
6675 Field2End = RD2->field_end();
6676 Field2 != Field2End; ++Field2) {
6677 UnmatchedFields.insert(*Field2);
6678 }
6679
6680 for (RecordDecl::field_iterator Field1 = RD1->field_begin(),
6681 Field1End = RD1->field_end();
6682 Field1 != Field1End; ++Field1) {
6683 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
6684 I = UnmatchedFields.begin(),
6685 E = UnmatchedFields.end();
6686
6687 for ( ; I != E; ++I) {
6688 if (isLayoutCompatible(C, *Field1, *I)) {
6689 bool Result = UnmatchedFields.erase(*I);
6690 (void) Result;
6691 assert(Result);
6692 break;
6693 }
6694 }
6695 if (I == E)
6696 return false;
6697 }
6698
6699 return UnmatchedFields.empty();
6700}
6701
6702bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
6703 if (RD1->isUnion() != RD2->isUnion())
6704 return false;
6705
6706 if (RD1->isUnion())
6707 return isLayoutCompatibleUnion(C, RD1, RD2);
6708 else
6709 return isLayoutCompatibleStruct(C, RD1, RD2);
6710}
6711
6712/// \brief Check if two types are layout-compatible in C++11 sense.
6713bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
6714 if (T1.isNull() || T2.isNull())
6715 return false;
6716
6717 // C++11 [basic.types] p11:
6718 // If two types T1 and T2 are the same type, then T1 and T2 are
6719 // layout-compatible types.
6720 if (C.hasSameType(T1, T2))
6721 return true;
6722
6723 T1 = T1.getCanonicalType().getUnqualifiedType();
6724 T2 = T2.getCanonicalType().getUnqualifiedType();
6725
6726 const Type::TypeClass TC1 = T1->getTypeClass();
6727 const Type::TypeClass TC2 = T2->getTypeClass();
6728
6729 if (TC1 != TC2)
6730 return false;
6731
6732 if (TC1 == Type::Enum) {
6733 return isLayoutCompatible(C,
6734 cast<EnumType>(T1)->getDecl(),
6735 cast<EnumType>(T2)->getDecl());
6736 } else if (TC1 == Type::Record) {
6737 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
6738 return false;
6739
6740 return isLayoutCompatible(C,
6741 cast<RecordType>(T1)->getDecl(),
6742 cast<RecordType>(T2)->getDecl());
6743 }
6744
6745 return false;
6746}
6747}
6748
6749//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
6750
6751namespace {
6752/// \brief Given a type tag expression find the type tag itself.
6753///
6754/// \param TypeExpr Type tag expression, as it appears in user's code.
6755///
6756/// \param VD Declaration of an identifier that appears in a type tag.
6757///
6758/// \param MagicValue Type tag magic value.
6759bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
6760 const ValueDecl **VD, uint64_t *MagicValue) {
6761 while(true) {
6762 if (!TypeExpr)
6763 return false;
6764
6765 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
6766
6767 switch (TypeExpr->getStmtClass()) {
6768 case Stmt::UnaryOperatorClass: {
6769 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
6770 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
6771 TypeExpr = UO->getSubExpr();
6772 continue;
6773 }
6774 return false;
6775 }
6776
6777 case Stmt::DeclRefExprClass: {
6778 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
6779 *VD = DRE->getDecl();
6780 return true;
6781 }
6782
6783 case Stmt::IntegerLiteralClass: {
6784 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
6785 llvm::APInt MagicValueAPInt = IL->getValue();
6786 if (MagicValueAPInt.getActiveBits() <= 64) {
6787 *MagicValue = MagicValueAPInt.getZExtValue();
6788 return true;
6789 } else
6790 return false;
6791 }
6792
6793 case Stmt::BinaryConditionalOperatorClass:
6794 case Stmt::ConditionalOperatorClass: {
6795 const AbstractConditionalOperator *ACO =
6796 cast<AbstractConditionalOperator>(TypeExpr);
6797 bool Result;
6798 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
6799 if (Result)
6800 TypeExpr = ACO->getTrueExpr();
6801 else
6802 TypeExpr = ACO->getFalseExpr();
6803 continue;
6804 }
6805 return false;
6806 }
6807
6808 case Stmt::BinaryOperatorClass: {
6809 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
6810 if (BO->getOpcode() == BO_Comma) {
6811 TypeExpr = BO->getRHS();
6812 continue;
6813 }
6814 return false;
6815 }
6816
6817 default:
6818 return false;
6819 }
6820 }
6821}
6822
6823/// \brief Retrieve the C type corresponding to type tag TypeExpr.
6824///
6825/// \param TypeExpr Expression that specifies a type tag.
6826///
6827/// \param MagicValues Registered magic values.
6828///
6829/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
6830/// kind.
6831///
6832/// \param TypeInfo Information about the corresponding C type.
6833///
6834/// \returns true if the corresponding C type was found.
6835bool GetMatchingCType(
6836 const IdentifierInfo *ArgumentKind,
6837 const Expr *TypeExpr, const ASTContext &Ctx,
6838 const llvm::DenseMap<Sema::TypeTagMagicValue,
6839 Sema::TypeTagData> *MagicValues,
6840 bool &FoundWrongKind,
6841 Sema::TypeTagData &TypeInfo) {
6842 FoundWrongKind = false;
6843
6844 // Variable declaration that has type_tag_for_datatype attribute.
6845 const ValueDecl *VD = NULL;
6846
6847 uint64_t MagicValue;
6848
6849 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
6850 return false;
6851
6852 if (VD) {
6853 for (specific_attr_iterator<TypeTagForDatatypeAttr>
6854 I = VD->specific_attr_begin<TypeTagForDatatypeAttr>(),
6855 E = VD->specific_attr_end<TypeTagForDatatypeAttr>();
6856 I != E; ++I) {
6857 if (I->getArgumentKind() != ArgumentKind) {
6858 FoundWrongKind = true;
6859 return false;
6860 }
6861 TypeInfo.Type = I->getMatchingCType();
6862 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
6863 TypeInfo.MustBeNull = I->getMustBeNull();
6864 return true;
6865 }
6866 return false;
6867 }
6868
6869 if (!MagicValues)
6870 return false;
6871
6872 llvm::DenseMap<Sema::TypeTagMagicValue,
6873 Sema::TypeTagData>::const_iterator I =
6874 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
6875 if (I == MagicValues->end())
6876 return false;
6877
6878 TypeInfo = I->second;
6879 return true;
6880}
6881} // unnamed namespace
6882
6883void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
6884 uint64_t MagicValue, QualType Type,
6885 bool LayoutCompatible,
6886 bool MustBeNull) {
6887 if (!TypeTagForDatatypeMagicValues)
6888 TypeTagForDatatypeMagicValues.reset(
6889 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
6890
6891 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
6892 (*TypeTagForDatatypeMagicValues)[Magic] =
6893 TypeTagData(Type, LayoutCompatible, MustBeNull);
6894}
6895
6896namespace {
6897bool IsSameCharType(QualType T1, QualType T2) {
6898 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
6899 if (!BT1)
6900 return false;
6901
6902 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
6903 if (!BT2)
6904 return false;
6905
6906 BuiltinType::Kind T1Kind = BT1->getKind();
6907 BuiltinType::Kind T2Kind = BT2->getKind();
6908
6909 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
6910 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
6911 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
6912 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
6913}
6914} // unnamed namespace
6915
6916void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
6917 const Expr * const *ExprArgs) {
6918 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
6919 bool IsPointerAttr = Attr->getIsPointer();
6920
6921 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
6922 bool FoundWrongKind;
6923 TypeTagData TypeInfo;
6924 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
6925 TypeTagForDatatypeMagicValues.get(),
6926 FoundWrongKind, TypeInfo)) {
6927 if (FoundWrongKind)
6928 Diag(TypeTagExpr->getExprLoc(),
6929 diag::warn_type_tag_for_datatype_wrong_kind)
6930 << TypeTagExpr->getSourceRange();
6931 return;
6932 }
6933
6934 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
6935 if (IsPointerAttr) {
6936 // Skip implicit cast of pointer to `void *' (as a function argument).
6937 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5a249802012-11-03 16:07:49 +00006938 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkob57ce4e2012-11-03 22:10:18 +00006939 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00006940 ArgumentExpr = ICE->getSubExpr();
6941 }
6942 QualType ArgumentType = ArgumentExpr->getType();
6943
6944 // Passing a `void*' pointer shouldn't trigger a warning.
6945 if (IsPointerAttr && ArgumentType->isVoidPointerType())
6946 return;
6947
6948 if (TypeInfo.MustBeNull) {
6949 // Type tag with matching void type requires a null pointer.
6950 if (!ArgumentExpr->isNullPointerConstant(Context,
6951 Expr::NPC_ValueDependentIsNotNull)) {
6952 Diag(ArgumentExpr->getExprLoc(),
6953 diag::warn_type_safety_null_pointer_required)
6954 << ArgumentKind->getName()
6955 << ArgumentExpr->getSourceRange()
6956 << TypeTagExpr->getSourceRange();
6957 }
6958 return;
6959 }
6960
6961 QualType RequiredType = TypeInfo.Type;
6962 if (IsPointerAttr)
6963 RequiredType = Context.getPointerType(RequiredType);
6964
6965 bool mismatch = false;
6966 if (!TypeInfo.LayoutCompatible) {
6967 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
6968
6969 // C++11 [basic.fundamental] p1:
6970 // Plain char, signed char, and unsigned char are three distinct types.
6971 //
6972 // But we treat plain `char' as equivalent to `signed char' or `unsigned
6973 // char' depending on the current char signedness mode.
6974 if (mismatch)
6975 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
6976 RequiredType->getPointeeType())) ||
6977 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
6978 mismatch = false;
6979 } else
6980 if (IsPointerAttr)
6981 mismatch = !isLayoutCompatible(Context,
6982 ArgumentType->getPointeeType(),
6983 RequiredType->getPointeeType());
6984 else
6985 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
6986
6987 if (mismatch)
6988 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
6989 << ArgumentType << ArgumentKind->getName()
6990 << TypeInfo.LayoutCompatible << RequiredType
6991 << ArgumentExpr->getSourceRange()
6992 << TypeTagExpr->getSourceRange();
6993}