blob: ca75a4f1b8ad0462ec833e5a31e61bc6ec32ce97 [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;
Richard Trieu0538f0e2013-06-22 00:20:41 +0000502 if (FDecl)
503 for (specific_attr_iterator<FormatAttr>
504 I = FDecl->specific_attr_begin<FormatAttr>(),
505 E = FDecl->specific_attr_end<FormatAttr>(); I != E ; ++I)
506 if (CheckFormatArguments(*I, Args, IsMemberFunction, CallType, Loc,
507 Range))
508 HandledFormatString = true;
Richard Smith831421f2012-06-25 20:30:08 +0000509
510 // Refuse POD arguments that weren't caught by the format string
511 // checks above.
512 if (!HandledFormatString && CallType != VariadicDoesNotApply)
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000513 for (unsigned ArgIdx = NumProtoArgs; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek0234bfa2012-10-11 19:06:43 +0000514 // Args[ArgIdx] can be null in malformed code.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000515 if (const Expr *Arg = Args[ArgIdx])
Ted Kremenek0234bfa2012-10-11 19:06:43 +0000516 variadicArgumentPODCheck(Arg, CallType);
517 }
Mike Stump1eb44332009-09-09 15:08:12 +0000518
Richard Trieu0538f0e2013-06-22 00:20:41 +0000519 if (FDecl) {
520 for (specific_attr_iterator<NonNullAttr>
521 I = FDecl->specific_attr_begin<NonNullAttr>(),
522 E = FDecl->specific_attr_end<NonNullAttr>(); I != E; ++I)
523 CheckNonNullArguments(*I, Args.data(), Loc);
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +0000524
Richard Trieu0538f0e2013-06-22 00:20:41 +0000525 // Type safety checking.
526 for (specific_attr_iterator<ArgumentWithTypeTagAttr>
527 i = FDecl->specific_attr_begin<ArgumentWithTypeTagAttr>(),
528 e = FDecl->specific_attr_end<ArgumentWithTypeTagAttr>();
529 i != e; ++i) {
530 CheckArgumentWithTypeTag(*i, Args.data());
531 }
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +0000532 }
Richard Smith831421f2012-06-25 20:30:08 +0000533}
534
535/// CheckConstructorCall - Check a constructor call for correctness and safety
536/// properties not enforced by the C type system.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000537void Sema::CheckConstructorCall(FunctionDecl *FDecl,
538 ArrayRef<const Expr *> Args,
Richard Smith831421f2012-06-25 20:30:08 +0000539 const FunctionProtoType *Proto,
540 SourceLocation Loc) {
541 VariadicCallType CallType =
542 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000543 checkCall(FDecl, Args, Proto->getNumArgs(),
Richard Smith831421f2012-06-25 20:30:08 +0000544 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
545}
546
547/// CheckFunctionCall - Check a direct function call for various correctness
548/// and safety properties not strictly enforced by the C type system.
549bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
550 const FunctionProtoType *Proto) {
Eli Friedman2edcde82012-10-11 00:30:58 +0000551 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
552 isa<CXXMethodDecl>(FDecl);
553 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
554 IsMemberOperatorCall;
Richard Smith831421f2012-06-25 20:30:08 +0000555 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
556 TheCall->getCallee());
557 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
Eli Friedman2edcde82012-10-11 00:30:58 +0000558 Expr** Args = TheCall->getArgs();
559 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmandf75b0c2012-10-11 00:34:15 +0000560 if (IsMemberOperatorCall) {
Eli Friedman2edcde82012-10-11 00:30:58 +0000561 // If this is a call to a member operator, hide the first argument
562 // from checkCall.
563 // FIXME: Our choice of AST representation here is less than ideal.
564 ++Args;
565 --NumArgs;
566 }
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000567 checkCall(FDecl, llvm::makeArrayRef<const Expr *>(Args, NumArgs),
568 NumProtoArgs,
Richard Smith831421f2012-06-25 20:30:08 +0000569 IsMemberFunction, TheCall->getRParenLoc(),
570 TheCall->getCallee()->getSourceRange(), CallType);
571
572 IdentifierInfo *FnInfo = FDecl->getIdentifier();
573 // None of the checks below are needed for functions that don't have
574 // simple names (e.g., C++ conversion functions).
575 if (!FnInfo)
576 return false;
Sebastian Redl0eb23302009-01-19 00:08:26 +0000577
Anna Zaks0a151a12012-01-17 00:37:07 +0000578 unsigned CMId = FDecl->getMemoryFunctionKind();
579 if (CMId == 0)
Anna Zaksd9b859a2012-01-13 21:52:01 +0000580 return false;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000581
Anna Zaksd9b859a2012-01-13 21:52:01 +0000582 // Handle memory setting and copying functions.
Anna Zaks0a151a12012-01-17 00:37:07 +0000583 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000584 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaksc36bedc2012-02-01 19:08:57 +0000585 else if (CMId == Builtin::BIstrncat)
586 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaksd9b859a2012-01-13 21:52:01 +0000587 else
Anna Zaks0a151a12012-01-17 00:37:07 +0000588 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth7ccc95b2011-04-27 07:05:31 +0000589
Anders Carlssond406bf02009-08-16 01:56:34 +0000590 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000591}
592
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000593bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko287f24d2013-05-05 19:42:09 +0000594 ArrayRef<const Expr *> Args) {
Richard Smith831421f2012-06-25 20:30:08 +0000595 VariadicCallType CallType =
596 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000597
Dmitri Gribenko287f24d2013-05-05 19:42:09 +0000598 checkCall(Method, Args, Method->param_size(),
Richard Smith831421f2012-06-25 20:30:08 +0000599 /*IsMemberFunction=*/false,
600 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000601
602 return false;
603}
604
Richard Trieuf462b012013-06-20 21:03:13 +0000605bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
606 const FunctionProtoType *Proto) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000607 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
608 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000609 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000610
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000611 QualType Ty = V->getType();
Richard Trieuf462b012013-06-20 21:03:13 +0000612 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000613 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000614
Richard Trieuf462b012013-06-20 21:03:13 +0000615 VariadicCallType CallType;
Richard Trieua4993772013-06-20 23:21:54 +0000616 if (!Proto || !Proto->isVariadic()) {
Richard Trieuf462b012013-06-20 21:03:13 +0000617 CallType = VariadicDoesNotApply;
618 } else if (Ty->isBlockPointerType()) {
619 CallType = VariadicBlock;
620 } else { // Ty->isFunctionPointerType()
621 CallType = VariadicFunction;
622 }
Richard Smith831421f2012-06-25 20:30:08 +0000623 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
Anders Carlssond406bf02009-08-16 01:56:34 +0000624
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000625 checkCall(NDecl,
626 llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
627 TheCall->getNumArgs()),
Richard Smith831421f2012-06-25 20:30:08 +0000628 NumProtoArgs, /*IsMemberFunction=*/false,
629 TheCall->getRParenLoc(),
630 TheCall->getCallee()->getSourceRange(), CallType);
631
Anders Carlssond406bf02009-08-16 01:56:34 +0000632 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000633}
634
Richard Trieu0538f0e2013-06-22 00:20:41 +0000635/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
636/// such as function pointers returned from functions.
637bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
638 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/0, Proto,
639 TheCall->getCallee());
640 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
641
642 checkCall(/*FDecl=*/0,
643 llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
644 TheCall->getNumArgs()),
645 NumProtoArgs, /*IsMemberFunction=*/false,
646 TheCall->getRParenLoc(),
647 TheCall->getCallee()->getSourceRange(), CallType);
648
649 return false;
650}
651
Richard Smithff34d402012-04-12 05:08:17 +0000652ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
653 AtomicExpr::AtomicOp Op) {
Eli Friedman276b0612011-10-11 02:20:01 +0000654 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
655 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedman276b0612011-10-11 02:20:01 +0000656
Richard Smithff34d402012-04-12 05:08:17 +0000657 // All these operations take one of the following forms:
658 enum {
659 // C __c11_atomic_init(A *, C)
660 Init,
661 // C __c11_atomic_load(A *, int)
662 Load,
663 // void __atomic_load(A *, CP, int)
664 Copy,
665 // C __c11_atomic_add(A *, M, int)
666 Arithmetic,
667 // C __atomic_exchange_n(A *, CP, int)
668 Xchg,
669 // void __atomic_exchange(A *, C *, CP, int)
670 GNUXchg,
671 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
672 C11CmpXchg,
673 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
674 GNUCmpXchg
675 } Form = Init;
676 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
677 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
678 // where:
679 // C is an appropriate type,
680 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
681 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
682 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
683 // the int parameters are for orderings.
Eli Friedman276b0612011-10-11 02:20:01 +0000684
Richard Smithff34d402012-04-12 05:08:17 +0000685 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
686 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
687 && "need to update code for modified C11 atomics");
688 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
689 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
690 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
691 Op == AtomicExpr::AO__atomic_store_n ||
692 Op == AtomicExpr::AO__atomic_exchange_n ||
693 Op == AtomicExpr::AO__atomic_compare_exchange_n;
694 bool IsAddSub = false;
695
696 switch (Op) {
697 case AtomicExpr::AO__c11_atomic_init:
698 Form = Init;
699 break;
700
701 case AtomicExpr::AO__c11_atomic_load:
702 case AtomicExpr::AO__atomic_load_n:
703 Form = Load;
704 break;
705
706 case AtomicExpr::AO__c11_atomic_store:
707 case AtomicExpr::AO__atomic_load:
708 case AtomicExpr::AO__atomic_store:
709 case AtomicExpr::AO__atomic_store_n:
710 Form = Copy;
711 break;
712
713 case AtomicExpr::AO__c11_atomic_fetch_add:
714 case AtomicExpr::AO__c11_atomic_fetch_sub:
715 case AtomicExpr::AO__atomic_fetch_add:
716 case AtomicExpr::AO__atomic_fetch_sub:
717 case AtomicExpr::AO__atomic_add_fetch:
718 case AtomicExpr::AO__atomic_sub_fetch:
719 IsAddSub = true;
720 // Fall through.
721 case AtomicExpr::AO__c11_atomic_fetch_and:
722 case AtomicExpr::AO__c11_atomic_fetch_or:
723 case AtomicExpr::AO__c11_atomic_fetch_xor:
724 case AtomicExpr::AO__atomic_fetch_and:
725 case AtomicExpr::AO__atomic_fetch_or:
726 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smith51b92402012-04-13 06:31:38 +0000727 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithff34d402012-04-12 05:08:17 +0000728 case AtomicExpr::AO__atomic_and_fetch:
729 case AtomicExpr::AO__atomic_or_fetch:
730 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smith51b92402012-04-13 06:31:38 +0000731 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithff34d402012-04-12 05:08:17 +0000732 Form = Arithmetic;
733 break;
734
735 case AtomicExpr::AO__c11_atomic_exchange:
736 case AtomicExpr::AO__atomic_exchange_n:
737 Form = Xchg;
738 break;
739
740 case AtomicExpr::AO__atomic_exchange:
741 Form = GNUXchg;
742 break;
743
744 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
745 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
746 Form = C11CmpXchg;
747 break;
748
749 case AtomicExpr::AO__atomic_compare_exchange:
750 case AtomicExpr::AO__atomic_compare_exchange_n:
751 Form = GNUCmpXchg;
752 break;
753 }
754
755 // Check we have the right number of arguments.
756 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedman276b0612011-10-11 02:20:01 +0000757 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithff34d402012-04-12 05:08:17 +0000758 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +0000759 << TheCall->getCallee()->getSourceRange();
760 return ExprError();
Richard Smithff34d402012-04-12 05:08:17 +0000761 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
762 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedman276b0612011-10-11 02:20:01 +0000763 diag::err_typecheck_call_too_many_args)
Richard Smithff34d402012-04-12 05:08:17 +0000764 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +0000765 << TheCall->getCallee()->getSourceRange();
766 return ExprError();
767 }
768
Richard Smithff34d402012-04-12 05:08:17 +0000769 // Inspect the first argument of the atomic operation.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000770 Expr *Ptr = TheCall->getArg(0);
Eli Friedman276b0612011-10-11 02:20:01 +0000771 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
772 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
773 if (!pointerType) {
Richard Smithff34d402012-04-12 05:08:17 +0000774 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedman276b0612011-10-11 02:20:01 +0000775 << Ptr->getType() << Ptr->getSourceRange();
776 return ExprError();
777 }
778
Richard Smithff34d402012-04-12 05:08:17 +0000779 // For a __c11 builtin, this should be a pointer to an _Atomic type.
780 QualType AtomTy = pointerType->getPointeeType(); // 'A'
781 QualType ValType = AtomTy; // 'C'
782 if (IsC11) {
783 if (!AtomTy->isAtomicType()) {
784 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
785 << Ptr->getType() << Ptr->getSourceRange();
786 return ExprError();
787 }
Richard Smithbc57b102012-09-15 06:09:58 +0000788 if (AtomTy.isConstQualified()) {
789 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
790 << Ptr->getType() << Ptr->getSourceRange();
791 return ExprError();
792 }
Richard Smithff34d402012-04-12 05:08:17 +0000793 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedman276b0612011-10-11 02:20:01 +0000794 }
Eli Friedman276b0612011-10-11 02:20:01 +0000795
Richard Smithff34d402012-04-12 05:08:17 +0000796 // For an arithmetic operation, the implied arithmetic must be well-formed.
797 if (Form == Arithmetic) {
798 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
799 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
800 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
801 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
802 return ExprError();
803 }
804 if (!IsAddSub && !ValType->isIntegerType()) {
805 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
806 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
807 return ExprError();
808 }
809 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
810 // For __atomic_*_n operations, the value type must be a scalar integral or
811 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedman276b0612011-10-11 02:20:01 +0000812 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithff34d402012-04-12 05:08:17 +0000813 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
814 return ExprError();
815 }
816
817 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context)) {
818 // For GNU atomics, require a trivially-copyable type. This is not part of
819 // the GNU atomics specification, but we enforce it for sanity.
820 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedman276b0612011-10-11 02:20:01 +0000821 << Ptr->getType() << Ptr->getSourceRange();
822 return ExprError();
823 }
824
Richard Smithff34d402012-04-12 05:08:17 +0000825 // FIXME: For any builtin other than a load, the ValType must not be
826 // const-qualified.
Eli Friedman276b0612011-10-11 02:20:01 +0000827
828 switch (ValType.getObjCLifetime()) {
829 case Qualifiers::OCL_None:
830 case Qualifiers::OCL_ExplicitNone:
831 // okay
832 break;
833
834 case Qualifiers::OCL_Weak:
835 case Qualifiers::OCL_Strong:
836 case Qualifiers::OCL_Autoreleasing:
Richard Smithff34d402012-04-12 05:08:17 +0000837 // FIXME: Can this happen? By this point, ValType should be known
838 // to be trivially copyable.
Eli Friedman276b0612011-10-11 02:20:01 +0000839 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
840 << ValType << Ptr->getSourceRange();
841 return ExprError();
842 }
843
844 QualType ResultType = ValType;
Richard Smithff34d402012-04-12 05:08:17 +0000845 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedman276b0612011-10-11 02:20:01 +0000846 ResultType = Context.VoidTy;
Richard Smithff34d402012-04-12 05:08:17 +0000847 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedman276b0612011-10-11 02:20:01 +0000848 ResultType = Context.BoolTy;
849
Richard Smithff34d402012-04-12 05:08:17 +0000850 // The type of a parameter passed 'by value'. In the GNU atomics, such
851 // arguments are actually passed as pointers.
852 QualType ByValType = ValType; // 'CP'
853 if (!IsC11 && !IsN)
854 ByValType = Ptr->getType();
855
Eli Friedman276b0612011-10-11 02:20:01 +0000856 // The first argument --- the pointer --- has a fixed type; we
857 // deduce the types of the rest of the arguments accordingly. Walk
858 // the remaining arguments, converting them to the deduced value type.
Richard Smithff34d402012-04-12 05:08:17 +0000859 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedman276b0612011-10-11 02:20:01 +0000860 QualType Ty;
Richard Smithff34d402012-04-12 05:08:17 +0000861 if (i < NumVals[Form] + 1) {
862 switch (i) {
863 case 1:
864 // The second argument is the non-atomic operand. For arithmetic, this
865 // is always passed by value, and for a compare_exchange it is always
866 // passed by address. For the rest, GNU uses by-address and C11 uses
867 // by-value.
868 assert(Form != Load);
869 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
870 Ty = ValType;
871 else if (Form == Copy || Form == Xchg)
872 Ty = ByValType;
873 else if (Form == Arithmetic)
874 Ty = Context.getPointerDiffType();
875 else
876 Ty = Context.getPointerType(ValType.getUnqualifiedType());
877 break;
878 case 2:
879 // The third argument to compare_exchange / GNU exchange is a
880 // (pointer to a) desired value.
881 Ty = ByValType;
882 break;
883 case 3:
884 // The fourth argument to GNU compare_exchange is a 'weak' flag.
885 Ty = Context.BoolTy;
886 break;
887 }
Eli Friedman276b0612011-10-11 02:20:01 +0000888 } else {
889 // The order(s) are always converted to int.
890 Ty = Context.IntTy;
891 }
Richard Smithff34d402012-04-12 05:08:17 +0000892
Eli Friedman276b0612011-10-11 02:20:01 +0000893 InitializedEntity Entity =
894 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithff34d402012-04-12 05:08:17 +0000895 ExprResult Arg = TheCall->getArg(i);
Eli Friedman276b0612011-10-11 02:20:01 +0000896 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
897 if (Arg.isInvalid())
898 return true;
899 TheCall->setArg(i, Arg.get());
900 }
901
Richard Smithff34d402012-04-12 05:08:17 +0000902 // Permute the arguments into a 'consistent' order.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000903 SmallVector<Expr*, 5> SubExprs;
904 SubExprs.push_back(Ptr);
Richard Smithff34d402012-04-12 05:08:17 +0000905 switch (Form) {
906 case Init:
907 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnall7a7ee302012-01-16 17:27:18 +0000908 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +0000909 break;
910 case Load:
911 SubExprs.push_back(TheCall->getArg(1)); // Order
912 break;
913 case Copy:
914 case Arithmetic:
915 case Xchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000916 SubExprs.push_back(TheCall->getArg(2)); // Order
917 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +0000918 break;
919 case GNUXchg:
920 // Note, AtomicExpr::getVal2() has a special case for this atomic.
921 SubExprs.push_back(TheCall->getArg(3)); // Order
922 SubExprs.push_back(TheCall->getArg(1)); // Val1
923 SubExprs.push_back(TheCall->getArg(2)); // Val2
924 break;
925 case C11CmpXchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000926 SubExprs.push_back(TheCall->getArg(3)); // Order
927 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000928 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall2ebb98a2012-03-29 17:58:59 +0000929 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithff34d402012-04-12 05:08:17 +0000930 break;
931 case GNUCmpXchg:
932 SubExprs.push_back(TheCall->getArg(4)); // Order
933 SubExprs.push_back(TheCall->getArg(1)); // Val1
934 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
935 SubExprs.push_back(TheCall->getArg(2)); // Val2
936 SubExprs.push_back(TheCall->getArg(3)); // Weak
937 break;
Eli Friedman276b0612011-10-11 02:20:01 +0000938 }
Fariborz Jahanian538bbe52013-05-28 17:37:39 +0000939
940 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
941 SubExprs, ResultType, Op,
942 TheCall->getRParenLoc());
943
944 if ((Op == AtomicExpr::AO__c11_atomic_load ||
945 (Op == AtomicExpr::AO__c11_atomic_store)) &&
946 Context.AtomicUsesUnsupportedLibcall(AE))
947 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
948 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000949
Fariborz Jahanian538bbe52013-05-28 17:37:39 +0000950 return Owned(AE);
Eli Friedman276b0612011-10-11 02:20:01 +0000951}
952
953
John McCall5f8d6042011-08-27 01:09:30 +0000954/// checkBuiltinArgument - Given a call to a builtin function, perform
955/// normal type-checking on the given argument, updating the call in
956/// place. This is useful when a builtin function requires custom
957/// type-checking for some of its arguments but not necessarily all of
958/// them.
959///
960/// Returns true on error.
961static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
962 FunctionDecl *Fn = E->getDirectCallee();
963 assert(Fn && "builtin call without direct callee!");
964
965 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
966 InitializedEntity Entity =
967 InitializedEntity::InitializeParameter(S.Context, Param);
968
969 ExprResult Arg = E->getArg(0);
970 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
971 if (Arg.isInvalid())
972 return true;
973
974 E->setArg(ArgIndex, Arg.take());
975 return false;
976}
977
Chris Lattner5caa3702009-05-08 06:58:22 +0000978/// SemaBuiltinAtomicOverloaded - We have a call to a function like
979/// __sync_fetch_and_add, which is an overloaded function based on the pointer
980/// type of its first argument. The main ActOnCallExpr routines have already
981/// promoted the types of arguments because all of these calls are prototyped as
982/// void(...).
983///
984/// This function goes through and does final semantic checking for these
985/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +0000986ExprResult
987Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000988 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +0000989 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
990 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
991
992 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +0000993 if (TheCall->getNumArgs() < 1) {
994 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
995 << 0 << 1 << TheCall->getNumArgs()
996 << TheCall->getCallee()->getSourceRange();
997 return ExprError();
998 }
Mike Stump1eb44332009-09-09 15:08:12 +0000999
Chris Lattner5caa3702009-05-08 06:58:22 +00001000 // Inspect the first argument of the atomic builtin. This should always be
1001 // a pointer type, whose element is an integral scalar or pointer type.
1002 // Because it is a pointer type, we don't have to worry about any implicit
1003 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +00001004 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +00001005 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman8c382062012-01-23 02:35:22 +00001006 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1007 if (FirstArgResult.isInvalid())
1008 return ExprError();
1009 FirstArg = FirstArgResult.take();
1010 TheCall->setArg(0, FirstArg);
1011
John McCallf85e1932011-06-15 23:02:42 +00001012 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1013 if (!pointerType) {
Chandler Carruthd2014572010-07-09 18:59:35 +00001014 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1015 << FirstArg->getType() << FirstArg->getSourceRange();
1016 return ExprError();
1017 }
Mike Stump1eb44332009-09-09 15:08:12 +00001018
John McCallf85e1932011-06-15 23:02:42 +00001019 QualType ValType = pointerType->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +00001020 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +00001021 !ValType->isBlockPointerType()) {
1022 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1023 << FirstArg->getType() << FirstArg->getSourceRange();
1024 return ExprError();
1025 }
Chris Lattner5caa3702009-05-08 06:58:22 +00001026
John McCallf85e1932011-06-15 23:02:42 +00001027 switch (ValType.getObjCLifetime()) {
1028 case Qualifiers::OCL_None:
1029 case Qualifiers::OCL_ExplicitNone:
1030 // okay
1031 break;
1032
1033 case Qualifiers::OCL_Weak:
1034 case Qualifiers::OCL_Strong:
1035 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00001036 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCallf85e1932011-06-15 23:02:42 +00001037 << ValType << FirstArg->getSourceRange();
1038 return ExprError();
1039 }
1040
John McCallb45ae252011-10-05 07:41:44 +00001041 // Strip any qualifiers off ValType.
1042 ValType = ValType.getUnqualifiedType();
1043
Chandler Carruth8d13d222010-07-18 20:54:12 +00001044 // The majority of builtins return a value, but a few have special return
1045 // types, so allow them to override appropriately below.
1046 QualType ResultType = ValType;
1047
Chris Lattner5caa3702009-05-08 06:58:22 +00001048 // We need to figure out which concrete builtin this maps onto. For example,
1049 // __sync_fetch_and_add with a 2 byte object turns into
1050 // __sync_fetch_and_add_2.
1051#define BUILTIN_ROW(x) \
1052 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1053 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +00001054
Chris Lattner5caa3702009-05-08 06:58:22 +00001055 static const unsigned BuiltinIndices[][5] = {
1056 BUILTIN_ROW(__sync_fetch_and_add),
1057 BUILTIN_ROW(__sync_fetch_and_sub),
1058 BUILTIN_ROW(__sync_fetch_and_or),
1059 BUILTIN_ROW(__sync_fetch_and_and),
1060 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +00001061
Chris Lattner5caa3702009-05-08 06:58:22 +00001062 BUILTIN_ROW(__sync_add_and_fetch),
1063 BUILTIN_ROW(__sync_sub_and_fetch),
1064 BUILTIN_ROW(__sync_and_and_fetch),
1065 BUILTIN_ROW(__sync_or_and_fetch),
1066 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +00001067
Chris Lattner5caa3702009-05-08 06:58:22 +00001068 BUILTIN_ROW(__sync_val_compare_and_swap),
1069 BUILTIN_ROW(__sync_bool_compare_and_swap),
1070 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +00001071 BUILTIN_ROW(__sync_lock_release),
1072 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +00001073 };
Mike Stump1eb44332009-09-09 15:08:12 +00001074#undef BUILTIN_ROW
1075
Chris Lattner5caa3702009-05-08 06:58:22 +00001076 // Determine the index of the size.
1077 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +00001078 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +00001079 case 1: SizeIndex = 0; break;
1080 case 2: SizeIndex = 1; break;
1081 case 4: SizeIndex = 2; break;
1082 case 8: SizeIndex = 3; break;
1083 case 16: SizeIndex = 4; break;
1084 default:
Chandler Carruthd2014572010-07-09 18:59:35 +00001085 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1086 << FirstArg->getType() << FirstArg->getSourceRange();
1087 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +00001088 }
Mike Stump1eb44332009-09-09 15:08:12 +00001089
Chris Lattner5caa3702009-05-08 06:58:22 +00001090 // Each of these builtins has one pointer argument, followed by some number of
1091 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1092 // that we ignore. Find out which row of BuiltinIndices to read from as well
1093 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00001094 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +00001095 unsigned BuiltinIndex, NumFixed = 1;
1096 switch (BuiltinID) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001097 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregora9766412011-11-28 16:30:08 +00001098 case Builtin::BI__sync_fetch_and_add:
1099 case Builtin::BI__sync_fetch_and_add_1:
1100 case Builtin::BI__sync_fetch_and_add_2:
1101 case Builtin::BI__sync_fetch_and_add_4:
1102 case Builtin::BI__sync_fetch_and_add_8:
1103 case Builtin::BI__sync_fetch_and_add_16:
1104 BuiltinIndex = 0;
1105 break;
1106
1107 case Builtin::BI__sync_fetch_and_sub:
1108 case Builtin::BI__sync_fetch_and_sub_1:
1109 case Builtin::BI__sync_fetch_and_sub_2:
1110 case Builtin::BI__sync_fetch_and_sub_4:
1111 case Builtin::BI__sync_fetch_and_sub_8:
1112 case Builtin::BI__sync_fetch_and_sub_16:
1113 BuiltinIndex = 1;
1114 break;
1115
1116 case Builtin::BI__sync_fetch_and_or:
1117 case Builtin::BI__sync_fetch_and_or_1:
1118 case Builtin::BI__sync_fetch_and_or_2:
1119 case Builtin::BI__sync_fetch_and_or_4:
1120 case Builtin::BI__sync_fetch_and_or_8:
1121 case Builtin::BI__sync_fetch_and_or_16:
1122 BuiltinIndex = 2;
1123 break;
1124
1125 case Builtin::BI__sync_fetch_and_and:
1126 case Builtin::BI__sync_fetch_and_and_1:
1127 case Builtin::BI__sync_fetch_and_and_2:
1128 case Builtin::BI__sync_fetch_and_and_4:
1129 case Builtin::BI__sync_fetch_and_and_8:
1130 case Builtin::BI__sync_fetch_and_and_16:
1131 BuiltinIndex = 3;
1132 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001133
Douglas Gregora9766412011-11-28 16:30:08 +00001134 case Builtin::BI__sync_fetch_and_xor:
1135 case Builtin::BI__sync_fetch_and_xor_1:
1136 case Builtin::BI__sync_fetch_and_xor_2:
1137 case Builtin::BI__sync_fetch_and_xor_4:
1138 case Builtin::BI__sync_fetch_and_xor_8:
1139 case Builtin::BI__sync_fetch_and_xor_16:
1140 BuiltinIndex = 4;
1141 break;
1142
1143 case Builtin::BI__sync_add_and_fetch:
1144 case Builtin::BI__sync_add_and_fetch_1:
1145 case Builtin::BI__sync_add_and_fetch_2:
1146 case Builtin::BI__sync_add_and_fetch_4:
1147 case Builtin::BI__sync_add_and_fetch_8:
1148 case Builtin::BI__sync_add_and_fetch_16:
1149 BuiltinIndex = 5;
1150 break;
1151
1152 case Builtin::BI__sync_sub_and_fetch:
1153 case Builtin::BI__sync_sub_and_fetch_1:
1154 case Builtin::BI__sync_sub_and_fetch_2:
1155 case Builtin::BI__sync_sub_and_fetch_4:
1156 case Builtin::BI__sync_sub_and_fetch_8:
1157 case Builtin::BI__sync_sub_and_fetch_16:
1158 BuiltinIndex = 6;
1159 break;
1160
1161 case Builtin::BI__sync_and_and_fetch:
1162 case Builtin::BI__sync_and_and_fetch_1:
1163 case Builtin::BI__sync_and_and_fetch_2:
1164 case Builtin::BI__sync_and_and_fetch_4:
1165 case Builtin::BI__sync_and_and_fetch_8:
1166 case Builtin::BI__sync_and_and_fetch_16:
1167 BuiltinIndex = 7;
1168 break;
1169
1170 case Builtin::BI__sync_or_and_fetch:
1171 case Builtin::BI__sync_or_and_fetch_1:
1172 case Builtin::BI__sync_or_and_fetch_2:
1173 case Builtin::BI__sync_or_and_fetch_4:
1174 case Builtin::BI__sync_or_and_fetch_8:
1175 case Builtin::BI__sync_or_and_fetch_16:
1176 BuiltinIndex = 8;
1177 break;
1178
1179 case Builtin::BI__sync_xor_and_fetch:
1180 case Builtin::BI__sync_xor_and_fetch_1:
1181 case Builtin::BI__sync_xor_and_fetch_2:
1182 case Builtin::BI__sync_xor_and_fetch_4:
1183 case Builtin::BI__sync_xor_and_fetch_8:
1184 case Builtin::BI__sync_xor_and_fetch_16:
1185 BuiltinIndex = 9;
1186 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001187
Chris Lattner5caa3702009-05-08 06:58:22 +00001188 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001189 case Builtin::BI__sync_val_compare_and_swap_1:
1190 case Builtin::BI__sync_val_compare_and_swap_2:
1191 case Builtin::BI__sync_val_compare_and_swap_4:
1192 case Builtin::BI__sync_val_compare_and_swap_8:
1193 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001194 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +00001195 NumFixed = 2;
1196 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001197
Chris Lattner5caa3702009-05-08 06:58:22 +00001198 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001199 case Builtin::BI__sync_bool_compare_and_swap_1:
1200 case Builtin::BI__sync_bool_compare_and_swap_2:
1201 case Builtin::BI__sync_bool_compare_and_swap_4:
1202 case Builtin::BI__sync_bool_compare_and_swap_8:
1203 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001204 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +00001205 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001206 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001207 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001208
1209 case Builtin::BI__sync_lock_test_and_set:
1210 case Builtin::BI__sync_lock_test_and_set_1:
1211 case Builtin::BI__sync_lock_test_and_set_2:
1212 case Builtin::BI__sync_lock_test_and_set_4:
1213 case Builtin::BI__sync_lock_test_and_set_8:
1214 case Builtin::BI__sync_lock_test_and_set_16:
1215 BuiltinIndex = 12;
1216 break;
1217
Chris Lattner5caa3702009-05-08 06:58:22 +00001218 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +00001219 case Builtin::BI__sync_lock_release_1:
1220 case Builtin::BI__sync_lock_release_2:
1221 case Builtin::BI__sync_lock_release_4:
1222 case Builtin::BI__sync_lock_release_8:
1223 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001224 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +00001225 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001226 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001227 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001228
1229 case Builtin::BI__sync_swap:
1230 case Builtin::BI__sync_swap_1:
1231 case Builtin::BI__sync_swap_2:
1232 case Builtin::BI__sync_swap_4:
1233 case Builtin::BI__sync_swap_8:
1234 case Builtin::BI__sync_swap_16:
1235 BuiltinIndex = 14;
1236 break;
Chris Lattner5caa3702009-05-08 06:58:22 +00001237 }
Mike Stump1eb44332009-09-09 15:08:12 +00001238
Chris Lattner5caa3702009-05-08 06:58:22 +00001239 // Now that we know how many fixed arguments we expect, first check that we
1240 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +00001241 if (TheCall->getNumArgs() < 1+NumFixed) {
1242 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1243 << 0 << 1+NumFixed << TheCall->getNumArgs()
1244 << TheCall->getCallee()->getSourceRange();
1245 return ExprError();
1246 }
Mike Stump1eb44332009-09-09 15:08:12 +00001247
Chris Lattnere7ac0a92009-05-08 15:36:58 +00001248 // Get the decl for the concrete builtin from this, we can tell what the
1249 // concrete integer type we should convert to is.
1250 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1251 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara2ad11cd2012-09-22 09:05:22 +00001252 FunctionDecl *NewBuiltinDecl;
1253 if (NewBuiltinID == BuiltinID)
1254 NewBuiltinDecl = FDecl;
1255 else {
1256 // Perform builtin lookup to avoid redeclaring it.
1257 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1258 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1259 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1260 assert(Res.getFoundDecl());
1261 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
1262 if (NewBuiltinDecl == 0)
1263 return ExprError();
1264 }
Chandler Carruthd2014572010-07-09 18:59:35 +00001265
John McCallf871d0c2010-08-07 06:22:56 +00001266 // The first argument --- the pointer --- has a fixed type; we
1267 // deduce the types of the rest of the arguments accordingly. Walk
1268 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +00001269 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +00001270 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +00001271
Chris Lattner5caa3702009-05-08 06:58:22 +00001272 // GCC does an implicit conversion to the pointer or integer ValType. This
1273 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb45ae252011-10-05 07:41:44 +00001274 // Initialize the argument.
1275 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1276 ValType, /*consume*/ false);
1277 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley429bb272011-04-08 18:41:53 +00001278 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +00001279 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001280
Chris Lattner5caa3702009-05-08 06:58:22 +00001281 // Okay, we have something that *can* be converted to the right type. Check
1282 // to see if there is a potentially weird extension going on here. This can
1283 // happen when you do an atomic operation on something like an char* and
1284 // pass in 42. The 42 gets converted to char. This is even more strange
1285 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +00001286 // FIXME: Do this check.
John McCallb45ae252011-10-05 07:41:44 +00001287 TheCall->setArg(i+1, Arg.take());
Chris Lattner5caa3702009-05-08 06:58:22 +00001288 }
Mike Stump1eb44332009-09-09 15:08:12 +00001289
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001290 ASTContext& Context = this->getASTContext();
1291
1292 // Create a new DeclRefExpr to refer to the new decl.
1293 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1294 Context,
1295 DRE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001296 SourceLocation(),
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001297 NewBuiltinDecl,
John McCallf4b88a42012-03-10 09:33:50 +00001298 /*enclosing*/ false,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001299 DRE->getLocation(),
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001300 Context.BuiltinFnTy,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001301 DRE->getValueKind());
Mike Stump1eb44332009-09-09 15:08:12 +00001302
Chris Lattner5caa3702009-05-08 06:58:22 +00001303 // Set the callee in the CallExpr.
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001304 // FIXME: This loses syntactic information.
1305 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1306 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1307 CK_BuiltinFnToFnPtr);
John Wiegley429bb272011-04-08 18:41:53 +00001308 TheCall->setCallee(PromotedCall.take());
Mike Stump1eb44332009-09-09 15:08:12 +00001309
Chandler Carruthdb4325b2010-07-18 07:23:17 +00001310 // Change the result type of the call to match the original value type. This
1311 // is arbitrary, but the codegen for these builtins ins design to handle it
1312 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +00001313 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +00001314
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001315 return TheCallResult;
Chris Lattner5caa3702009-05-08 06:58:22 +00001316}
1317
Chris Lattner69039812009-02-18 06:01:06 +00001318/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +00001319/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +00001320/// Note: It might also make sense to do the UTF-16 conversion here (would
1321/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +00001322bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +00001323 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +00001324 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1325
Douglas Gregor5cee1192011-07-27 05:40:30 +00001326 if (!Literal || !Literal->isAscii()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001327 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1328 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001329 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +00001330 }
Mike Stump1eb44332009-09-09 15:08:12 +00001331
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001332 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001333 StringRef String = Literal->getString();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001334 unsigned NumBytes = String.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001335 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divacky31ba6132012-09-06 15:59:27 +00001336 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001337 UTF16 *ToPtr = &ToBuf[0];
1338
1339 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1340 &ToPtr, ToPtr + NumBytes,
1341 strictConversion);
1342 // Check for conversion failure.
1343 if (Result != conversionOK)
1344 Diag(Arg->getLocStart(),
1345 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1346 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001347 return false;
Chris Lattner59907c42007-08-10 20:18:51 +00001348}
1349
Chris Lattnerc27c6652007-12-20 00:05:45 +00001350/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1351/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +00001352bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1353 Expr *Fn = TheCall->getCallee();
1354 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +00001355 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001356 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001357 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1358 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +00001359 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001360 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +00001361 return true;
1362 }
Eli Friedman56f20ae2008-12-15 22:05:35 +00001363
1364 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +00001365 return Diag(TheCall->getLocEnd(),
1366 diag::err_typecheck_call_too_few_args_at_least)
1367 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +00001368 }
1369
John McCall5f8d6042011-08-27 01:09:30 +00001370 // Type-check the first argument normally.
1371 if (checkBuiltinArgument(*this, TheCall, 0))
1372 return true;
1373
Chris Lattnerc27c6652007-12-20 00:05:45 +00001374 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001375 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +00001376 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001377 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +00001378 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +00001379 else if (FunctionDecl *FD = getCurFunctionDecl())
1380 isVariadic = FD->isVariadic();
1381 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001382 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +00001383
Chris Lattnerc27c6652007-12-20 00:05:45 +00001384 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001385 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1386 return true;
1387 }
Mike Stump1eb44332009-09-09 15:08:12 +00001388
Chris Lattner30ce3442007-12-19 23:59:04 +00001389 // Verify that the second argument to the builtin is the last argument of the
1390 // current function or method.
1391 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +00001392 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001393
Nico Weberb07d4482013-05-24 23:31:57 +00001394 // These are valid if SecondArgIsLastNamedArgument is false after the next
1395 // block.
1396 QualType Type;
1397 SourceLocation ParamLoc;
1398
Anders Carlsson88cf2262008-02-11 04:20:54 +00001399 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1400 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001401 // FIXME: This isn't correct for methods (results in bogus warning).
1402 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +00001403 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001404 if (CurBlock)
1405 LastArg = *(CurBlock->TheDecl->param_end()-1);
1406 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +00001407 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001408 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001409 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001410 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weberb07d4482013-05-24 23:31:57 +00001411
1412 Type = PV->getType();
1413 ParamLoc = PV->getLocation();
Chris Lattner30ce3442007-12-19 23:59:04 +00001414 }
1415 }
Mike Stump1eb44332009-09-09 15:08:12 +00001416
Chris Lattner30ce3442007-12-19 23:59:04 +00001417 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001418 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +00001419 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weberb07d4482013-05-24 23:31:57 +00001420 else if (Type->isReferenceType()) {
1421 Diag(Arg->getLocStart(),
1422 diag::warn_va_start_of_reference_type_is_undefined);
1423 Diag(ParamLoc, diag::note_parameter_type) << Type;
1424 }
1425
Chris Lattner30ce3442007-12-19 23:59:04 +00001426 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +00001427}
Chris Lattner30ce3442007-12-19 23:59:04 +00001428
Chris Lattner1b9a0792007-12-20 00:26:33 +00001429/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1430/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +00001431bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1432 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +00001433 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001434 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +00001435 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +00001436 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001437 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001438 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001439 << SourceRange(TheCall->getArg(2)->getLocStart(),
1440 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001441
John Wiegley429bb272011-04-08 18:41:53 +00001442 ExprResult OrigArg0 = TheCall->getArg(0);
1443 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +00001444
Chris Lattner1b9a0792007-12-20 00:26:33 +00001445 // Do standard promotions between the two arguments, returning their common
1446 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +00001447 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +00001448 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1449 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +00001450
1451 // Make sure any conversions are pushed back into the call; this is
1452 // type safe since unordered compare builtins are declared as "_Bool
1453 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +00001454 TheCall->setArg(0, OrigArg0.get());
1455 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001456
John Wiegley429bb272011-04-08 18:41:53 +00001457 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +00001458 return false;
1459
Chris Lattner1b9a0792007-12-20 00:26:33 +00001460 // If the common type isn't a real floating type, then the arguments were
1461 // invalid for this operation.
Eli Friedman860a3192012-06-16 02:19:17 +00001462 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +00001463 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001464 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +00001465 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1466 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001467
Chris Lattner1b9a0792007-12-20 00:26:33 +00001468 return false;
1469}
1470
Benjamin Kramere771a7a2010-02-15 22:42:31 +00001471/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1472/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001473/// to check everything. We expect the last argument to be a floating point
1474/// value.
1475bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1476 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +00001477 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001478 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001479 if (TheCall->getNumArgs() > NumArgs)
1480 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001481 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001482 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001483 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001484 (*(TheCall->arg_end()-1))->getLocEnd());
1485
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001486 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001487
Eli Friedman9ac6f622009-08-31 20:06:00 +00001488 if (OrigArg->isTypeDependent())
1489 return false;
1490
Chris Lattner81368fb2010-05-06 05:50:07 +00001491 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +00001492 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +00001493 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001494 diag::err_typecheck_call_invalid_unary_fp)
1495 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001496
Chris Lattner81368fb2010-05-06 05:50:07 +00001497 // If this is an implicit conversion from float -> double, remove it.
1498 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1499 Expr *CastArg = Cast->getSubExpr();
1500 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1501 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1502 "promotion from float to double is the only expected cast here");
1503 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +00001504 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner81368fb2010-05-06 05:50:07 +00001505 }
1506 }
1507
Eli Friedman9ac6f622009-08-31 20:06:00 +00001508 return false;
1509}
1510
Eli Friedmand38617c2008-05-14 19:38:39 +00001511/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1512// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +00001513ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001514 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001515 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +00001516 diag::err_typecheck_call_too_few_args_at_least)
Nate Begeman37b6a572010-06-08 00:16:34 +00001517 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherd77b9a22010-04-16 04:48:22 +00001518 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001519
Nate Begeman37b6a572010-06-08 00:16:34 +00001520 // Determine which of the following types of shufflevector we're checking:
1521 // 1) unary, vector mask: (lhs, mask)
1522 // 2) binary, vector mask: (lhs, rhs, mask)
1523 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1524 QualType resType = TheCall->getArg(0)->getType();
1525 unsigned numElements = 0;
1526
Douglas Gregorcde01732009-05-19 22:10:17 +00001527 if (!TheCall->getArg(0)->isTypeDependent() &&
1528 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001529 QualType LHSType = TheCall->getArg(0)->getType();
1530 QualType RHSType = TheCall->getArg(1)->getType();
1531
1532 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001533 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001534 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001535 TheCall->getArg(1)->getLocEnd());
1536 return ExprError();
1537 }
Nate Begeman37b6a572010-06-08 00:16:34 +00001538
1539 numElements = LHSType->getAs<VectorType>()->getNumElements();
1540 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +00001541
Nate Begeman37b6a572010-06-08 00:16:34 +00001542 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1543 // with mask. If so, verify that RHS is an integer vector type with the
1544 // same number of elts as lhs.
1545 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru4cb3d902013-07-06 08:00:09 +00001546 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +00001547 RHSType->getAs<VectorType>()->getNumElements() != numElements)
1548 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1549 << SourceRange(TheCall->getArg(1)->getLocStart(),
1550 TheCall->getArg(1)->getLocEnd());
Nate Begeman37b6a572010-06-08 00:16:34 +00001551 }
1552 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001553 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001554 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001555 TheCall->getArg(1)->getLocEnd());
1556 return ExprError();
Nate Begeman37b6a572010-06-08 00:16:34 +00001557 } else if (numElements != numResElements) {
1558 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +00001559 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001560 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +00001561 }
Eli Friedmand38617c2008-05-14 19:38:39 +00001562 }
1563
1564 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001565 if (TheCall->getArg(i)->isTypeDependent() ||
1566 TheCall->getArg(i)->isValueDependent())
1567 continue;
1568
Nate Begeman37b6a572010-06-08 00:16:34 +00001569 llvm::APSInt Result(32);
1570 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1571 return ExprError(Diag(TheCall->getLocStart(),
1572 diag::err_shufflevector_nonconstant_argument)
1573 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001574
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001575 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001576 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001577 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001578 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001579 }
1580
Chris Lattner5f9e2722011-07-23 10:55:15 +00001581 SmallVector<Expr*, 32> exprs;
Eli Friedmand38617c2008-05-14 19:38:39 +00001582
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001583 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +00001584 exprs.push_back(TheCall->getArg(i));
1585 TheCall->setArg(i, 0);
1586 }
1587
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001588 return Owned(new (Context) ShuffleVectorExpr(Context, exprs, resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001589 TheCall->getCallee()->getLocStart(),
1590 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +00001591}
Chris Lattner30ce3442007-12-19 23:59:04 +00001592
Daniel Dunbar4493f792008-07-21 22:59:13 +00001593/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1594// This is declared to take (const void*, ...) and can take two
1595// optional constant int args.
1596bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001597 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001598
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001599 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +00001600 return Diag(TheCall->getLocEnd(),
1601 diag::err_typecheck_call_too_many_args_at_most)
1602 << 0 /*function call*/ << 3 << NumArgs
1603 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001604
1605 // Argument 0 is checked for us and the remaining arguments must be
1606 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001607 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +00001608 Expr *Arg = TheCall->getArg(i);
Douglas Gregor592a4232012-06-29 01:05:22 +00001609
1610 // We can't check the value of a dependent argument.
1611 if (Arg->isTypeDependent() || Arg->isValueDependent())
1612 continue;
1613
Eli Friedman9aef7262009-12-04 00:30:06 +00001614 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +00001615 if (SemaBuiltinConstantArg(TheCall, i, Result))
1616 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001617
Daniel Dunbar4493f792008-07-21 22:59:13 +00001618 // FIXME: gcc issues a warning and rewrites these to 0. These
1619 // seems especially odd for the third argument since the default
1620 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001621 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +00001622 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001623 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001624 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001625 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +00001626 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001627 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001628 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001629 }
1630 }
1631
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001632 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +00001633}
1634
Eric Christopher691ebc32010-04-17 02:26:23 +00001635/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1636/// TheCall is a constant expression.
1637bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1638 llvm::APSInt &Result) {
1639 Expr *Arg = TheCall->getArg(ArgNum);
1640 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1641 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1642
1643 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1644
1645 if (!Arg->isIntegerConstantExpr(Result, Context))
1646 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +00001647 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +00001648
Chris Lattner21fb98e2009-09-23 06:06:36 +00001649 return false;
1650}
1651
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001652/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1653/// int type). This simply type checks that type is one of the defined
1654/// constants (0-3).
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001655// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001656bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +00001657 llvm::APSInt Result;
Douglas Gregor592a4232012-06-29 01:05:22 +00001658
1659 // We can't check the value of a dependent argument.
1660 if (TheCall->getArg(1)->isTypeDependent() ||
1661 TheCall->getArg(1)->isValueDependent())
1662 return false;
1663
Eric Christopher691ebc32010-04-17 02:26:23 +00001664 // Check constant-ness first.
1665 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1666 return true;
1667
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001668 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001669 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001670 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1671 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001672 }
1673
1674 return false;
1675}
1676
Eli Friedman586d6a82009-05-03 06:04:26 +00001677/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +00001678/// This checks that val is a constant 1.
1679bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1680 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +00001681 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +00001682
Eric Christopher691ebc32010-04-17 02:26:23 +00001683 // TODO: This is less than ideal. Overload this to take a value.
1684 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1685 return true;
1686
1687 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +00001688 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1689 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1690
1691 return false;
1692}
1693
Richard Smith831421f2012-06-25 20:30:08 +00001694// Determine if an expression is a string literal or constant string.
1695// If this function returns false on the arguments to a function expecting a
1696// format string, we will usually need to emit a warning.
1697// True string literals are then checked by CheckFormatString.
1698Sema::StringLiteralCheckType
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001699Sema::checkFormatStringExpr(const Expr *E, ArrayRef<const Expr *> Args,
1700 bool HasVAListArg,
Richard Smith831421f2012-06-25 20:30:08 +00001701 unsigned format_idx, unsigned firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001702 FormatStringType Type, VariadicCallType CallType,
1703 bool inFunctionCall) {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001704 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +00001705 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith831421f2012-06-25 20:30:08 +00001706 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001707
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001708 E = E->IgnoreParenCasts();
Peter Collingbournef111d932011-04-15 00:35:48 +00001709
David Blaikiea73cdcb2012-02-10 21:07:25 +00001710 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
1711 // Technically -Wformat-nonliteral does not warn about this case.
1712 // The behavior of printf and friends in this case is implementation
1713 // dependent. Ideally if the format string cannot be null then
1714 // it should have a 'nonnull' attribute in the function prototype.
Richard Smith831421f2012-06-25 20:30:08 +00001715 return SLCT_CheckedLiteral;
David Blaikiea73cdcb2012-02-10 21:07:25 +00001716
Ted Kremenekd30ef872009-01-12 23:09:09 +00001717 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +00001718 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +00001719 case Stmt::ConditionalOperatorClass: {
Richard Smith831421f2012-06-25 20:30:08 +00001720 // The expression is a literal if both sub-expressions were, and it was
1721 // completely checked only if both sub-expressions were checked.
1722 const AbstractConditionalOperator *C =
1723 cast<AbstractConditionalOperator>(E);
1724 StringLiteralCheckType Left =
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001725 checkFormatStringExpr(C->getTrueExpr(), Args,
Richard Smith831421f2012-06-25 20:30:08 +00001726 HasVAListArg, format_idx, firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001727 Type, CallType, inFunctionCall);
Richard Smith831421f2012-06-25 20:30:08 +00001728 if (Left == SLCT_NotALiteral)
1729 return SLCT_NotALiteral;
1730 StringLiteralCheckType Right =
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001731 checkFormatStringExpr(C->getFalseExpr(), Args,
Richard Smith831421f2012-06-25 20:30:08 +00001732 HasVAListArg, format_idx, firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001733 Type, CallType, inFunctionCall);
Richard Smith831421f2012-06-25 20:30:08 +00001734 return Left < Right ? Left : Right;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001735 }
1736
1737 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001738 E = cast<ImplicitCastExpr>(E)->getSubExpr();
1739 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001740 }
1741
John McCall56ca35d2011-02-17 10:25:35 +00001742 case Stmt::OpaqueValueExprClass:
1743 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
1744 E = src;
1745 goto tryAgain;
1746 }
Richard Smith831421f2012-06-25 20:30:08 +00001747 return SLCT_NotALiteral;
John McCall56ca35d2011-02-17 10:25:35 +00001748
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001749 case Stmt::PredefinedExprClass:
1750 // While __func__, etc., are technically not string literals, they
1751 // cannot contain format specifiers and thus are not a security
1752 // liability.
Richard Smith831421f2012-06-25 20:30:08 +00001753 return SLCT_UncheckedLiteral;
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001754
Ted Kremenek082d9362009-03-20 21:35:28 +00001755 case Stmt::DeclRefExprClass: {
1756 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001757
Ted Kremenek082d9362009-03-20 21:35:28 +00001758 // As an exception, do not flag errors for variables binding to
1759 // const string literals.
1760 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1761 bool isConstant = false;
1762 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001763
Ted Kremenek082d9362009-03-20 21:35:28 +00001764 if (const ArrayType *AT = Context.getAsArrayType(T)) {
1765 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001766 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001767 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +00001768 PT->getPointeeType().isConstant(Context);
Jean-Daniel Dupase98e5b52012-01-25 10:35:33 +00001769 } else if (T->isObjCObjectPointerType()) {
1770 // In ObjC, there is usually no "const ObjectPointer" type,
1771 // so don't check if the pointee type is constant.
1772 isConstant = T.isConstant(Context);
Ted Kremenek082d9362009-03-20 21:35:28 +00001773 }
Mike Stump1eb44332009-09-09 15:08:12 +00001774
Ted Kremenek082d9362009-03-20 21:35:28 +00001775 if (isConstant) {
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00001776 if (const Expr *Init = VD->getAnyInitializer()) {
1777 // Look through initializers like const char c[] = { "foo" }
1778 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
1779 if (InitList->isStringLiteralInit())
1780 Init = InitList->getInit(0)->IgnoreParenImpCasts();
1781 }
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001782 return checkFormatStringExpr(Init, Args,
Richard Smith831421f2012-06-25 20:30:08 +00001783 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001784 firstDataArg, Type, CallType,
Richard Smith831421f2012-06-25 20:30:08 +00001785 /*inFunctionCall*/false);
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00001786 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001787 }
Mike Stump1eb44332009-09-09 15:08:12 +00001788
Anders Carlssond966a552009-06-28 19:55:58 +00001789 // For vprintf* functions (i.e., HasVAListArg==true), we add a
1790 // special check to see if the format string is a function parameter
1791 // of the function calling the printf function. If the function
1792 // has an attribute indicating it is a printf-like function, then we
1793 // should suppress warnings concerning non-literals being used in a call
1794 // to a vprintf function. For example:
1795 //
1796 // void
1797 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1798 // va_list ap;
1799 // va_start(ap, fmt);
1800 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
1801 // ...
1802 //
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00001803 if (HasVAListArg) {
1804 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
1805 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
1806 int PVIndex = PV->getFunctionScopeIndex() + 1;
1807 for (specific_attr_iterator<FormatAttr>
1808 i = ND->specific_attr_begin<FormatAttr>(),
1809 e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) {
1810 FormatAttr *PVFormat = *i;
1811 // adjust for implicit parameter
1812 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1813 if (MD->isInstance())
1814 ++PVIndex;
1815 // We also check if the formats are compatible.
1816 // We can't pass a 'scanf' string to a 'printf' function.
1817 if (PVIndex == PVFormat->getFormatIdx() &&
1818 Type == GetFormatStringType(PVFormat))
Richard Smith831421f2012-06-25 20:30:08 +00001819 return SLCT_UncheckedLiteral;
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00001820 }
1821 }
1822 }
1823 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001824 }
Mike Stump1eb44332009-09-09 15:08:12 +00001825
Richard Smith831421f2012-06-25 20:30:08 +00001826 return SLCT_NotALiteral;
Ted Kremenek082d9362009-03-20 21:35:28 +00001827 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00001828
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001829 case Stmt::CallExprClass:
1830 case Stmt::CXXMemberCallExprClass: {
Anders Carlsson8f031b32009-06-27 04:05:33 +00001831 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001832 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
1833 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
1834 unsigned ArgIndex = FA->getFormatIdx();
1835 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1836 if (MD->isInstance())
1837 --ArgIndex;
1838 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001839
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001840 return checkFormatStringExpr(Arg, Args,
Richard Smith831421f2012-06-25 20:30:08 +00001841 HasVAListArg, format_idx, firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001842 Type, CallType, inFunctionCall);
Jordan Rose50687312012-06-04 23:52:23 +00001843 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
1844 unsigned BuiltinID = FD->getBuiltinID();
1845 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
1846 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
1847 const Expr *Arg = CE->getArg(0);
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001848 return checkFormatStringExpr(Arg, Args,
Richard Smith831421f2012-06-25 20:30:08 +00001849 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001850 firstDataArg, Type, CallType,
1851 inFunctionCall);
Jordan Rose50687312012-06-04 23:52:23 +00001852 }
Anders Carlsson8f031b32009-06-27 04:05:33 +00001853 }
1854 }
Mike Stump1eb44332009-09-09 15:08:12 +00001855
Richard Smith831421f2012-06-25 20:30:08 +00001856 return SLCT_NotALiteral;
Anders Carlsson8f031b32009-06-27 04:05:33 +00001857 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001858 case Stmt::ObjCStringLiteralClass:
1859 case Stmt::StringLiteralClass: {
1860 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001861
Ted Kremenek082d9362009-03-20 21:35:28 +00001862 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00001863 StrE = ObjCFExpr->getString();
1864 else
Ted Kremenek082d9362009-03-20 21:35:28 +00001865 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001866
Ted Kremenekd30ef872009-01-12 23:09:09 +00001867 if (StrE) {
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001868 CheckFormatString(StrE, E, Args, HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001869 firstDataArg, Type, inFunctionCall, CallType);
Richard Smith831421f2012-06-25 20:30:08 +00001870 return SLCT_CheckedLiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001871 }
Mike Stump1eb44332009-09-09 15:08:12 +00001872
Richard Smith831421f2012-06-25 20:30:08 +00001873 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001874 }
Mike Stump1eb44332009-09-09 15:08:12 +00001875
Ted Kremenek082d9362009-03-20 21:35:28 +00001876 default:
Richard Smith831421f2012-06-25 20:30:08 +00001877 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001878 }
1879}
1880
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001881void
Mike Stump1eb44332009-09-09 15:08:12 +00001882Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewycky909a70d2011-03-25 01:44:32 +00001883 const Expr * const *ExprArgs,
1884 SourceLocation CallSiteLoc) {
Sean Huntcf807c42010-08-18 23:23:40 +00001885 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1886 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001887 i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +00001888 const Expr *ArgExpr = ExprArgs[*i];
Nick Lewycky3edf3872013-01-23 05:08:29 +00001889
1890 // As a special case, transparent unions initialized with zero are
1891 // considered null for the purposes of the nonnull attribute.
1892 if (const RecordType *UT = ArgExpr->getType()->getAsUnionType()) {
1893 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
1894 if (const CompoundLiteralExpr *CLE =
1895 dyn_cast<CompoundLiteralExpr>(ArgExpr))
1896 if (const InitListExpr *ILE =
1897 dyn_cast<InitListExpr>(CLE->getInitializer()))
1898 ArgExpr = ILE->getInit(0);
1899 }
1900
1901 bool Result;
1902 if (ArgExpr->EvaluateAsBooleanCondition(Result, Context) && !Result)
Nick Lewycky909a70d2011-03-25 01:44:32 +00001903 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001904 }
1905}
Ted Kremenekd30ef872009-01-12 23:09:09 +00001906
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001907Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
1908 return llvm::StringSwitch<FormatStringType>(Format->getType())
1909 .Case("scanf", FST_Scanf)
1910 .Cases("printf", "printf0", FST_Printf)
1911 .Cases("NSString", "CFString", FST_NSString)
1912 .Case("strftime", FST_Strftime)
1913 .Case("strfmon", FST_Strfmon)
1914 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
1915 .Default(FST_Unknown);
1916}
1917
Jordan Roseddcfbc92012-07-19 18:10:23 +00001918/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek826a3452010-07-16 02:11:22 +00001919/// functions) for correct use of format strings.
Richard Smith831421f2012-06-25 20:30:08 +00001920/// Returns true if a format string has been fully checked.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001921bool Sema::CheckFormatArguments(const FormatAttr *Format,
1922 ArrayRef<const Expr *> Args,
1923 bool IsCXXMember,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001924 VariadicCallType CallType,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001925 SourceLocation Loc, SourceRange Range) {
Richard Smith831421f2012-06-25 20:30:08 +00001926 FormatStringInfo FSI;
1927 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001928 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith831421f2012-06-25 20:30:08 +00001929 FSI.FirstDataArg, GetFormatStringType(Format),
Jordan Roseddcfbc92012-07-19 18:10:23 +00001930 CallType, Loc, Range);
Richard Smith831421f2012-06-25 20:30:08 +00001931 return false;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001932}
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001933
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001934bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001935 bool HasVAListArg, unsigned format_idx,
1936 unsigned firstDataArg, FormatStringType Type,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001937 VariadicCallType CallType,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001938 SourceLocation Loc, SourceRange Range) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001939 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001940 if (format_idx >= Args.size()) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001941 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith831421f2012-06-25 20:30:08 +00001942 return false;
Ted Kremenek71895b92007-08-14 17:39:48 +00001943 }
Mike Stump1eb44332009-09-09 15:08:12 +00001944
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001945 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001946
Chris Lattner59907c42007-08-10 20:18:51 +00001947 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001948 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001949 // Dynamically generated format strings are difficult to
1950 // automatically vet at compile time. Requiring that format strings
1951 // are string literals: (1) permits the checking of format strings by
1952 // the compiler and thereby (2) can practically remove the source of
1953 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001954
Mike Stump1eb44332009-09-09 15:08:12 +00001955 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001956 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001957 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001958 // the same format string checking logic for both ObjC and C strings.
Richard Smith831421f2012-06-25 20:30:08 +00001959 StringLiteralCheckType CT =
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001960 checkFormatStringExpr(OrigFormatExpr, Args, HasVAListArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001961 format_idx, firstDataArg, Type, CallType);
Richard Smith831421f2012-06-25 20:30:08 +00001962 if (CT != SLCT_NotALiteral)
1963 // Literal format string found, check done!
1964 return CT == SLCT_CheckedLiteral;
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001965
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00001966 // Strftime is particular as it always uses a single 'time' argument,
1967 // so it is safe to pass a non-literal string.
1968 if (Type == FST_Strftime)
Richard Smith831421f2012-06-25 20:30:08 +00001969 return false;
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00001970
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00001971 // Do not emit diag when the string param is a macro expansion and the
1972 // format is either NSString or CFString. This is a hack to prevent
1973 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
1974 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupasdc170202012-05-04 21:08:08 +00001975 if (Type == FST_NSString &&
1976 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith831421f2012-06-25 20:30:08 +00001977 return false;
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00001978
Chris Lattner655f1412009-04-29 04:59:47 +00001979 // If there are no arguments specified, warn with -Wformat-security, otherwise
1980 // warn only with -Wformat-nonliteral.
Eli Friedman2243e782013-06-18 18:10:01 +00001981 if (Args.size() == firstDataArg)
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001982 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001983 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00001984 << OrigFormatExpr->getSourceRange();
1985 else
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001986 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001987 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00001988 << OrigFormatExpr->getSourceRange();
Richard Smith831421f2012-06-25 20:30:08 +00001989 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001990}
Ted Kremenek71895b92007-08-14 17:39:48 +00001991
Ted Kremeneke0e53132010-01-28 23:39:18 +00001992namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00001993class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1994protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001995 Sema &S;
1996 const StringLiteral *FExpr;
1997 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001998 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001999 const unsigned NumDataArgs;
Ted Kremeneke0e53132010-01-28 23:39:18 +00002000 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00002001 const bool HasVAListArg;
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002002 ArrayRef<const Expr *> Args;
Ted Kremenek0d277352010-01-29 01:06:55 +00002003 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002004 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00002005 bool usesPositionalArgs;
2006 bool atFirstArg;
Richard Trieu55733de2011-10-28 00:41:25 +00002007 bool inFunctionCall;
Jordan Roseddcfbc92012-07-19 18:10:23 +00002008 Sema::VariadicCallType CallType;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002009public:
Ted Kremenek826a3452010-07-16 02:11:22 +00002010 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00002011 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002012 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002013 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002014 unsigned formatIdx, bool inFunctionCall,
2015 Sema::VariadicCallType callType)
Ted Kremeneke0e53132010-01-28 23:39:18 +00002016 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose50687312012-06-04 23:52:23 +00002017 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2018 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002019 Args(Args), FormatIdx(formatIdx),
Richard Trieu55733de2011-10-28 00:41:25 +00002020 usesPositionalArgs(false), atFirstArg(true),
Jordan Roseddcfbc92012-07-19 18:10:23 +00002021 inFunctionCall(inFunctionCall), CallType(callType) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002022 CoveredArgs.resize(numDataArgs);
2023 CoveredArgs.reset();
2024 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002025
Ted Kremenek07d161f2010-01-29 01:50:07 +00002026 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002027
Ted Kremenek826a3452010-07-16 02:11:22 +00002028 void HandleIncompleteSpecifier(const char *startSpecifier,
2029 unsigned specifierLen);
Hans Wennborg76517422012-02-22 10:17:01 +00002030
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002031 void HandleInvalidLengthModifier(
2032 const analyze_format_string::FormatSpecifier &FS,
2033 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose8be066e2012-09-08 04:00:12 +00002034 const char *startSpecifier, unsigned specifierLen, unsigned DiagID);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002035
Hans Wennborg76517422012-02-22 10:17:01 +00002036 void HandleNonStandardLengthModifier(
Jordan Rose8be066e2012-09-08 04:00:12 +00002037 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborg76517422012-02-22 10:17:01 +00002038 const char *startSpecifier, unsigned specifierLen);
2039
2040 void HandleNonStandardConversionSpecifier(
2041 const analyze_format_string::ConversionSpecifier &CS,
2042 const char *startSpecifier, unsigned specifierLen);
2043
Hans Wennborgf8562642012-03-09 10:10:54 +00002044 virtual void HandlePosition(const char *startPos, unsigned posLen);
2045
Ted Kremenekefaff192010-02-27 01:41:03 +00002046 virtual void HandleInvalidPosition(const char *startSpecifier,
2047 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00002048 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00002049
2050 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
2051
Ted Kremeneke0e53132010-01-28 23:39:18 +00002052 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002053
Richard Trieu55733de2011-10-28 00:41:25 +00002054 template <typename Range>
2055 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2056 const Expr *ArgumentExpr,
2057 PartialDiagnostic PDiag,
2058 SourceLocation StringLoc,
2059 bool IsStringLocation, Range StringRange,
Dmitri Gribenko55431692013-05-05 00:41:58 +00002060 ArrayRef<FixItHint> Fixit = None);
Richard Trieu55733de2011-10-28 00:41:25 +00002061
Ted Kremenek826a3452010-07-16 02:11:22 +00002062protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002063 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2064 const char *startSpec,
2065 unsigned specifierLen,
2066 const char *csStart, unsigned csLen);
Richard Trieu55733de2011-10-28 00:41:25 +00002067
2068 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2069 const char *startSpec,
2070 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002071
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002072 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00002073 CharSourceRange getSpecifierRange(const char *startSpecifier,
2074 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002075 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002076
Ted Kremenek0d277352010-01-29 01:06:55 +00002077 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00002078
2079 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2080 const analyze_format_string::ConversionSpecifier &CS,
2081 const char *startSpecifier, unsigned specifierLen,
2082 unsigned argIndex);
Richard Trieu55733de2011-10-28 00:41:25 +00002083
2084 template <typename Range>
2085 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2086 bool IsStringLocation, Range StringRange,
Dmitri Gribenko55431692013-05-05 00:41:58 +00002087 ArrayRef<FixItHint> Fixit = None);
Richard Trieu55733de2011-10-28 00:41:25 +00002088
2089 void CheckPositionalAndNonpositionalArgs(
2090 const analyze_format_string::FormatSpecifier *FS);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002091};
2092}
2093
Ted Kremenek826a3452010-07-16 02:11:22 +00002094SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00002095 return OrigFormatExpr->getSourceRange();
2096}
2097
Ted Kremenek826a3452010-07-16 02:11:22 +00002098CharSourceRange CheckFormatHandler::
2099getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002100 SourceLocation Start = getLocationOfByte(startSpecifier);
2101 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2102
2103 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002104 End = End.getLocWithOffset(1);
Tom Care45f9b7e2010-06-21 21:21:01 +00002105
2106 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002107}
2108
Ted Kremenek826a3452010-07-16 02:11:22 +00002109SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002110 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002111}
2112
Ted Kremenek826a3452010-07-16 02:11:22 +00002113void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2114 unsigned specifierLen){
Richard Trieu55733de2011-10-28 00:41:25 +00002115 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2116 getLocationOfByte(startSpecifier),
2117 /*IsStringLocation*/true,
2118 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek808015a2010-01-29 03:16:21 +00002119}
2120
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002121void CheckFormatHandler::HandleInvalidLengthModifier(
2122 const analyze_format_string::FormatSpecifier &FS,
2123 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose8be066e2012-09-08 04:00:12 +00002124 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002125 using namespace analyze_format_string;
2126
2127 const LengthModifier &LM = FS.getLengthModifier();
2128 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2129
2130 // See if we know how to fix this length modifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002131 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002132 if (FixedLM) {
Jordan Rose8be066e2012-09-08 04:00:12 +00002133 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002134 getLocationOfByte(LM.getStart()),
2135 /*IsStringLocation*/true,
2136 getSpecifierRange(startSpecifier, specifierLen));
2137
2138 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2139 << FixedLM->toString()
2140 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2141
2142 } else {
Jordan Rose8be066e2012-09-08 04:00:12 +00002143 FixItHint Hint;
2144 if (DiagID == diag::warn_format_nonsensical_length)
2145 Hint = FixItHint::CreateRemoval(LMRange);
2146
2147 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002148 getLocationOfByte(LM.getStart()),
2149 /*IsStringLocation*/true,
2150 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose8be066e2012-09-08 04:00:12 +00002151 Hint);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002152 }
2153}
2154
Hans Wennborg76517422012-02-22 10:17:01 +00002155void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose8be066e2012-09-08 04:00:12 +00002156 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborg76517422012-02-22 10:17:01 +00002157 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose8be066e2012-09-08 04:00:12 +00002158 using namespace analyze_format_string;
2159
2160 const LengthModifier &LM = FS.getLengthModifier();
2161 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2162
2163 // See if we know how to fix this length modifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002164 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose8be066e2012-09-08 04:00:12 +00002165 if (FixedLM) {
2166 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2167 << LM.toString() << 0,
2168 getLocationOfByte(LM.getStart()),
2169 /*IsStringLocation*/true,
2170 getSpecifierRange(startSpecifier, specifierLen));
2171
2172 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2173 << FixedLM->toString()
2174 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2175
2176 } else {
2177 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2178 << LM.toString() << 0,
2179 getLocationOfByte(LM.getStart()),
2180 /*IsStringLocation*/true,
2181 getSpecifierRange(startSpecifier, specifierLen));
2182 }
Hans Wennborg76517422012-02-22 10:17:01 +00002183}
2184
2185void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2186 const analyze_format_string::ConversionSpecifier &CS,
2187 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose670941c2012-09-13 02:11:15 +00002188 using namespace analyze_format_string;
2189
2190 // See if we know how to fix this conversion specifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002191 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose670941c2012-09-13 02:11:15 +00002192 if (FixedCS) {
2193 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2194 << CS.toString() << /*conversion specifier*/1,
2195 getLocationOfByte(CS.getStart()),
2196 /*IsStringLocation*/true,
2197 getSpecifierRange(startSpecifier, specifierLen));
2198
2199 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2200 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2201 << FixedCS->toString()
2202 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2203 } else {
2204 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2205 << CS.toString() << /*conversion specifier*/1,
2206 getLocationOfByte(CS.getStart()),
2207 /*IsStringLocation*/true,
2208 getSpecifierRange(startSpecifier, specifierLen));
2209 }
Hans Wennborg76517422012-02-22 10:17:01 +00002210}
2211
Hans Wennborgf8562642012-03-09 10:10:54 +00002212void CheckFormatHandler::HandlePosition(const char *startPos,
2213 unsigned posLen) {
2214 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2215 getLocationOfByte(startPos),
2216 /*IsStringLocation*/true,
2217 getSpecifierRange(startPos, posLen));
2218}
2219
Ted Kremenekefaff192010-02-27 01:41:03 +00002220void
Ted Kremenek826a3452010-07-16 02:11:22 +00002221CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2222 analyze_format_string::PositionContext p) {
Richard Trieu55733de2011-10-28 00:41:25 +00002223 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2224 << (unsigned) p,
2225 getLocationOfByte(startPos), /*IsStringLocation*/true,
2226 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002227}
2228
Ted Kremenek826a3452010-07-16 02:11:22 +00002229void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00002230 unsigned posLen) {
Richard Trieu55733de2011-10-28 00:41:25 +00002231 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2232 getLocationOfByte(startPos),
2233 /*IsStringLocation*/true,
2234 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002235}
2236
Ted Kremenek826a3452010-07-16 02:11:22 +00002237void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose50687312012-06-04 23:52:23 +00002238 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0c069442011-03-15 21:18:48 +00002239 // The presence of a null character is likely an error.
Richard Trieu55733de2011-10-28 00:41:25 +00002240 EmitFormatDiagnostic(
2241 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2242 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2243 getFormatStringRange());
Ted Kremenek0c069442011-03-15 21:18:48 +00002244 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002245}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002246
Jordan Rose48716662012-07-19 18:10:08 +00002247// Note that this may return NULL if there was an error parsing or building
2248// one of the argument expressions.
Ted Kremenek826a3452010-07-16 02:11:22 +00002249const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002250 return Args[FirstDataArg + i];
Ted Kremenek826a3452010-07-16 02:11:22 +00002251}
2252
2253void CheckFormatHandler::DoneProcessing() {
2254 // Does the number of data arguments exceed the number of
2255 // format conversions in the format string?
2256 if (!HasVAListArg) {
2257 // Find any arguments that weren't covered.
2258 CoveredArgs.flip();
2259 signed notCoveredArg = CoveredArgs.find_first();
2260 if (notCoveredArg >= 0) {
2261 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose48716662012-07-19 18:10:08 +00002262 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2263 SourceLocation Loc = E->getLocStart();
2264 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2265 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2266 Loc, /*IsStringLocation*/false,
2267 getFormatStringRange());
2268 }
Bob Wilsonc03f2df2012-05-03 19:47:19 +00002269 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002270 }
2271 }
2272}
2273
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002274bool
2275CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2276 SourceLocation Loc,
2277 const char *startSpec,
2278 unsigned specifierLen,
2279 const char *csStart,
2280 unsigned csLen) {
2281
2282 bool keepGoing = true;
2283 if (argIndex < NumDataArgs) {
2284 // Consider the argument coverered, even though the specifier doesn't
2285 // make sense.
2286 CoveredArgs.set(argIndex);
2287 }
2288 else {
2289 // If argIndex exceeds the number of data arguments we
2290 // don't issue a warning because that is just a cascade of warnings (and
2291 // they may have intended '%%' anyway). We don't want to continue processing
2292 // the format string after this point, however, as we will like just get
2293 // gibberish when trying to match arguments.
2294 keepGoing = false;
2295 }
2296
Richard Trieu55733de2011-10-28 00:41:25 +00002297 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2298 << StringRef(csStart, csLen),
2299 Loc, /*IsStringLocation*/true,
2300 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002301
2302 return keepGoing;
2303}
2304
Richard Trieu55733de2011-10-28 00:41:25 +00002305void
2306CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2307 const char *startSpec,
2308 unsigned specifierLen) {
2309 EmitFormatDiagnostic(
2310 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2311 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2312}
2313
Ted Kremenek666a1972010-07-26 19:45:42 +00002314bool
2315CheckFormatHandler::CheckNumArgs(
2316 const analyze_format_string::FormatSpecifier &FS,
2317 const analyze_format_string::ConversionSpecifier &CS,
2318 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2319
2320 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002321 PartialDiagnostic PDiag = FS.usesPositionalArg()
2322 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2323 << (argIndex+1) << NumDataArgs)
2324 : S.PDiag(diag::warn_printf_insufficient_data_args);
2325 EmitFormatDiagnostic(
2326 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2327 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek666a1972010-07-26 19:45:42 +00002328 return false;
2329 }
2330 return true;
2331}
2332
Richard Trieu55733de2011-10-28 00:41:25 +00002333template<typename Range>
2334void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2335 SourceLocation Loc,
2336 bool IsStringLocation,
2337 Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002338 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002339 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu55733de2011-10-28 00:41:25 +00002340 Loc, IsStringLocation, StringRange, FixIt);
2341}
2342
2343/// \brief If the format string is not within the funcion call, emit a note
2344/// so that the function call and string are in diagnostic messages.
2345///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00002346/// \param InFunctionCall if true, the format string is within the function
Richard Trieu55733de2011-10-28 00:41:25 +00002347/// call and only one diagnostic message will be produced. Otherwise, an
2348/// extra note will be emitted pointing to location of the format string.
2349///
2350/// \param ArgumentExpr the expression that is passed as the format string
2351/// argument in the function call. Used for getting locations when two
2352/// diagnostics are emitted.
2353///
2354/// \param PDiag the callee should already have provided any strings for the
2355/// diagnostic message. This function only adds locations and fixits
2356/// to diagnostics.
2357///
2358/// \param Loc primary location for diagnostic. If two diagnostics are
2359/// required, one will be at Loc and a new SourceLocation will be created for
2360/// the other one.
2361///
2362/// \param IsStringLocation if true, Loc points to the format string should be
2363/// used for the note. Otherwise, Loc points to the argument list and will
2364/// be used with PDiag.
2365///
2366/// \param StringRange some or all of the string to highlight. This is
2367/// templated so it can accept either a CharSourceRange or a SourceRange.
2368///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00002369/// \param FixIt optional fix it hint for the format string.
Richard Trieu55733de2011-10-28 00:41:25 +00002370template<typename Range>
2371void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2372 const Expr *ArgumentExpr,
2373 PartialDiagnostic PDiag,
2374 SourceLocation Loc,
2375 bool IsStringLocation,
2376 Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002377 ArrayRef<FixItHint> FixIt) {
2378 if (InFunctionCall) {
2379 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2380 D << StringRange;
2381 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2382 I != E; ++I) {
2383 D << *I;
2384 }
2385 } else {
Richard Trieu55733de2011-10-28 00:41:25 +00002386 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2387 << ArgumentExpr->getSourceRange();
Jordan Roseec087352012-09-05 22:56:26 +00002388
2389 const Sema::SemaDiagnosticBuilder &Note =
2390 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2391 diag::note_format_string_defined);
2392
2393 Note << StringRange;
2394 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2395 I != E; ++I) {
2396 Note << *I;
2397 }
Richard Trieu55733de2011-10-28 00:41:25 +00002398 }
2399}
2400
Ted Kremenek826a3452010-07-16 02:11:22 +00002401//===--- CHECK: Printf format string checking ------------------------------===//
2402
2403namespace {
2404class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose50687312012-06-04 23:52:23 +00002405 bool ObjCContext;
Ted Kremenek826a3452010-07-16 02:11:22 +00002406public:
2407 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2408 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002409 unsigned numDataArgs, bool isObjC,
Ted Kremenek826a3452010-07-16 02:11:22 +00002410 const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002411 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002412 unsigned formatIdx, bool inFunctionCall,
2413 Sema::VariadicCallType CallType)
Ted Kremenek826a3452010-07-16 02:11:22 +00002414 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002415 numDataArgs, beg, hasVAListArg, Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002416 formatIdx, inFunctionCall, CallType), ObjCContext(isObjC)
2417 {}
2418
Ted Kremenek826a3452010-07-16 02:11:22 +00002419
2420 bool HandleInvalidPrintfConversionSpecifier(
2421 const analyze_printf::PrintfSpecifier &FS,
2422 const char *startSpecifier,
2423 unsigned specifierLen);
2424
2425 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2426 const char *startSpecifier,
2427 unsigned specifierLen);
Richard Smith831421f2012-06-25 20:30:08 +00002428 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2429 const char *StartSpecifier,
2430 unsigned SpecifierLen,
2431 const Expr *E);
2432
Ted Kremenek826a3452010-07-16 02:11:22 +00002433 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2434 const char *startSpecifier, unsigned specifierLen);
2435 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2436 const analyze_printf::OptionalAmount &Amt,
2437 unsigned type,
2438 const char *startSpecifier, unsigned specifierLen);
2439 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2440 const analyze_printf::OptionalFlag &flag,
2441 const char *startSpecifier, unsigned specifierLen);
2442 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2443 const analyze_printf::OptionalFlag &ignoredFlag,
2444 const analyze_printf::OptionalFlag &flag,
2445 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgf3749f42012-08-07 08:11:26 +00002446 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith831421f2012-06-25 20:30:08 +00002447 const Expr *E, const CharSourceRange &CSR);
2448
Ted Kremenek826a3452010-07-16 02:11:22 +00002449};
2450}
2451
2452bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2453 const analyze_printf::PrintfSpecifier &FS,
2454 const char *startSpecifier,
2455 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002456 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002457 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002458
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002459 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2460 getLocationOfByte(CS.getStart()),
2461 startSpecifier, specifierLen,
2462 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00002463}
2464
Ted Kremenek826a3452010-07-16 02:11:22 +00002465bool CheckPrintfHandler::HandleAmount(
2466 const analyze_format_string::OptionalAmount &Amt,
2467 unsigned k, const char *startSpecifier,
2468 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002469
2470 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002471 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002472 unsigned argIndex = Amt.getArgIndex();
2473 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002474 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2475 << k,
2476 getLocationOfByte(Amt.getStart()),
2477 /*IsStringLocation*/true,
2478 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002479 // Don't do any more checking. We will just emit
2480 // spurious errors.
2481 return false;
2482 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002483
Ted Kremenek0d277352010-01-29 01:06:55 +00002484 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00002485 // Although not in conformance with C99, we also allow the argument to be
2486 // an 'unsigned int' as that is a reasonably safe case. GCC also
2487 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002488 CoveredArgs.set(argIndex);
2489 const Expr *Arg = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00002490 if (!Arg)
2491 return false;
2492
Ted Kremenek0d277352010-01-29 01:06:55 +00002493 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002494
Hans Wennborgf3749f42012-08-07 08:11:26 +00002495 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
2496 assert(AT.isValid());
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002497
Hans Wennborgf3749f42012-08-07 08:11:26 +00002498 if (!AT.matchesType(S.Context, T)) {
Richard Trieu55733de2011-10-28 00:41:25 +00002499 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgf3749f42012-08-07 08:11:26 +00002500 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu55733de2011-10-28 00:41:25 +00002501 << T << Arg->getSourceRange(),
2502 getLocationOfByte(Amt.getStart()),
2503 /*IsStringLocation*/true,
2504 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002505 // Don't do any more checking. We will just emit
2506 // spurious errors.
2507 return false;
2508 }
2509 }
2510 }
2511 return true;
2512}
Ted Kremenek0d277352010-01-29 01:06:55 +00002513
Tom Caree4ee9662010-06-17 19:00:27 +00002514void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00002515 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002516 const analyze_printf::OptionalAmount &Amt,
2517 unsigned type,
2518 const char *startSpecifier,
2519 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002520 const analyze_printf::PrintfConversionSpecifier &CS =
2521 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00002522
Richard Trieu55733de2011-10-28 00:41:25 +00002523 FixItHint fixit =
2524 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2525 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2526 Amt.getConstantLength()))
2527 : FixItHint();
2528
2529 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2530 << type << CS.toString(),
2531 getLocationOfByte(Amt.getStart()),
2532 /*IsStringLocation*/true,
2533 getSpecifierRange(startSpecifier, specifierLen),
2534 fixit);
Tom Caree4ee9662010-06-17 19:00:27 +00002535}
2536
Ted Kremenek826a3452010-07-16 02:11:22 +00002537void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002538 const analyze_printf::OptionalFlag &flag,
2539 const char *startSpecifier,
2540 unsigned specifierLen) {
2541 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002542 const analyze_printf::PrintfConversionSpecifier &CS =
2543 FS.getConversionSpecifier();
Richard Trieu55733de2011-10-28 00:41:25 +00002544 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2545 << flag.toString() << CS.toString(),
2546 getLocationOfByte(flag.getPosition()),
2547 /*IsStringLocation*/true,
2548 getSpecifierRange(startSpecifier, specifierLen),
2549 FixItHint::CreateRemoval(
2550 getSpecifierRange(flag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002551}
2552
2553void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00002554 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002555 const analyze_printf::OptionalFlag &ignoredFlag,
2556 const analyze_printf::OptionalFlag &flag,
2557 const char *startSpecifier,
2558 unsigned specifierLen) {
2559 // Warn about ignored flag with a fixit removal.
Richard Trieu55733de2011-10-28 00:41:25 +00002560 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2561 << ignoredFlag.toString() << flag.toString(),
2562 getLocationOfByte(ignoredFlag.getPosition()),
2563 /*IsStringLocation*/true,
2564 getSpecifierRange(startSpecifier, specifierLen),
2565 FixItHint::CreateRemoval(
2566 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002567}
2568
Richard Smith831421f2012-06-25 20:30:08 +00002569// Determines if the specified is a C++ class or struct containing
2570// a member with the specified name and kind (e.g. a CXXMethodDecl named
2571// "c_str()").
2572template<typename MemberKind>
2573static llvm::SmallPtrSet<MemberKind*, 1>
2574CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2575 const RecordType *RT = Ty->getAs<RecordType>();
2576 llvm::SmallPtrSet<MemberKind*, 1> Results;
2577
2578 if (!RT)
2579 return Results;
2580 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
2581 if (!RD)
2582 return Results;
2583
2584 LookupResult R(S, &S.PP.getIdentifierTable().get(Name), SourceLocation(),
2585 Sema::LookupMemberName);
2586
2587 // We just need to include all members of the right kind turned up by the
2588 // filter, at this point.
2589 if (S.LookupQualifiedName(R, RT->getDecl()))
2590 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2591 NamedDecl *decl = (*I)->getUnderlyingDecl();
2592 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
2593 Results.insert(FK);
2594 }
2595 return Results;
2596}
2597
2598// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgf3749f42012-08-07 08:11:26 +00002599// better diagnostic if so. AT is assumed to be valid.
Richard Smith831421f2012-06-25 20:30:08 +00002600// Returns true when a c_str() conversion method is found.
2601bool CheckPrintfHandler::checkForCStrMembers(
Hans Wennborgf3749f42012-08-07 08:11:26 +00002602 const analyze_printf::ArgType &AT, const Expr *E,
Richard Smith831421f2012-06-25 20:30:08 +00002603 const CharSourceRange &CSR) {
2604 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2605
2606 MethodSet Results =
2607 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
2608
2609 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2610 MI != ME; ++MI) {
2611 const CXXMethodDecl *Method = *MI;
2612 if (Method->getNumParams() == 0 &&
Hans Wennborgf3749f42012-08-07 08:11:26 +00002613 AT.matchesType(S.Context, Method->getResultType())) {
Richard Smith831421f2012-06-25 20:30:08 +00002614 // FIXME: Suggest parens if the expression needs them.
2615 SourceLocation EndLoc =
2616 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd());
2617 S.Diag(E->getLocStart(), diag::note_printf_c_str)
2618 << "c_str()"
2619 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
2620 return true;
2621 }
2622 }
2623
2624 return false;
2625}
2626
Ted Kremeneke0e53132010-01-28 23:39:18 +00002627bool
Ted Kremenek826a3452010-07-16 02:11:22 +00002628CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002629 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00002630 const char *startSpecifier,
2631 unsigned specifierLen) {
2632
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002633 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00002634 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002635 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00002636
Ted Kremenekbaa40062010-07-19 22:01:06 +00002637 if (FS.consumesDataArgument()) {
2638 if (atFirstArg) {
2639 atFirstArg = false;
2640 usesPositionalArgs = FS.usesPositionalArg();
2641 }
2642 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002643 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2644 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002645 return false;
2646 }
Ted Kremenek0d277352010-01-29 01:06:55 +00002647 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002648
Ted Kremenekefaff192010-02-27 01:41:03 +00002649 // First check if the field width, precision, and conversion specifier
2650 // have matching data arguments.
2651 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2652 startSpecifier, specifierLen)) {
2653 return false;
2654 }
2655
2656 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2657 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002658 return false;
2659 }
2660
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002661 if (!CS.consumesDataArgument()) {
2662 // FIXME: Technically specifying a precision or field width here
2663 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002664 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002665 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002666
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002667 // Consume the argument.
2668 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00002669 if (argIndex < NumDataArgs) {
2670 // The check to see if the argIndex is valid will come later.
2671 // We set the bit here because we may exit early from this
2672 // function if we encounter some other error.
2673 CoveredArgs.set(argIndex);
2674 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002675
2676 // Check for using an Objective-C specific conversion specifier
2677 // in a non-ObjC literal.
Jordan Rose50687312012-06-04 23:52:23 +00002678 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002679 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2680 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002681 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002682
Tom Caree4ee9662010-06-17 19:00:27 +00002683 // Check for invalid use of field width
2684 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002685 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00002686 startSpecifier, specifierLen);
2687 }
2688
2689 // Check for invalid use of precision
2690 if (!FS.hasValidPrecision()) {
2691 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
2692 startSpecifier, specifierLen);
2693 }
2694
2695 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00002696 if (!FS.hasValidThousandsGroupingPrefix())
2697 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002698 if (!FS.hasValidLeadingZeros())
2699 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
2700 if (!FS.hasValidPlusPrefix())
2701 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00002702 if (!FS.hasValidSpacePrefix())
2703 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002704 if (!FS.hasValidAlternativeForm())
2705 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
2706 if (!FS.hasValidLeftJustified())
2707 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
2708
2709 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00002710 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
2711 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
2712 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002713 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
2714 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
2715 startSpecifier, specifierLen);
2716
2717 // Check the length modifier is valid with the given conversion specifier.
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002718 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose8be066e2012-09-08 04:00:12 +00002719 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
2720 diag::warn_format_nonsensical_length);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002721 else if (!FS.hasStandardLengthModifier())
Jordan Rose8be066e2012-09-08 04:00:12 +00002722 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002723 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose8be066e2012-09-08 04:00:12 +00002724 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
2725 diag::warn_format_non_standard_conversion_spec);
Tom Caree4ee9662010-06-17 19:00:27 +00002726
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002727 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
2728 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
2729
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002730 // The remaining checks depend on the data arguments.
2731 if (HasVAListArg)
2732 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002733
Ted Kremenek666a1972010-07-26 19:45:42 +00002734 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002735 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002736
Jordan Rose48716662012-07-19 18:10:08 +00002737 const Expr *Arg = getDataArg(argIndex);
2738 if (!Arg)
2739 return true;
2740
2741 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith831421f2012-06-25 20:30:08 +00002742}
2743
Jordan Roseec087352012-09-05 22:56:26 +00002744static bool requiresParensToAddCast(const Expr *E) {
2745 // FIXME: We should have a general way to reason about operator
2746 // precedence and whether parens are actually needed here.
2747 // Take care of a few common cases where they aren't.
2748 const Expr *Inside = E->IgnoreImpCasts();
2749 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
2750 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
2751
2752 switch (Inside->getStmtClass()) {
2753 case Stmt::ArraySubscriptExprClass:
2754 case Stmt::CallExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00002755 case Stmt::CharacterLiteralClass:
2756 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00002757 case Stmt::DeclRefExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00002758 case Stmt::FloatingLiteralClass:
2759 case Stmt::IntegerLiteralClass:
Jordan Roseec087352012-09-05 22:56:26 +00002760 case Stmt::MemberExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00002761 case Stmt::ObjCArrayLiteralClass:
2762 case Stmt::ObjCBoolLiteralExprClass:
2763 case Stmt::ObjCBoxedExprClass:
2764 case Stmt::ObjCDictionaryLiteralClass:
2765 case Stmt::ObjCEncodeExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00002766 case Stmt::ObjCIvarRefExprClass:
2767 case Stmt::ObjCMessageExprClass:
2768 case Stmt::ObjCPropertyRefExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00002769 case Stmt::ObjCStringLiteralClass:
2770 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00002771 case Stmt::ParenExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00002772 case Stmt::StringLiteralClass:
Jordan Roseec087352012-09-05 22:56:26 +00002773 case Stmt::UnaryOperatorClass:
2774 return false;
2775 default:
2776 return true;
2777 }
2778}
2779
Richard Smith831421f2012-06-25 20:30:08 +00002780bool
2781CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2782 const char *StartSpecifier,
2783 unsigned SpecifierLen,
2784 const Expr *E) {
2785 using namespace analyze_format_string;
2786 using namespace analyze_printf;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002787 // Now type check the data expression that matches the
2788 // format specifier.
Hans Wennborgf3749f42012-08-07 08:11:26 +00002789 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
2790 ObjCContext);
Jordan Rose614a8652012-09-05 22:56:19 +00002791 if (!AT.isValid())
2792 return true;
Jordan Roseec087352012-09-05 22:56:26 +00002793
Jordan Rose448ac3e2012-12-05 18:44:40 +00002794 QualType ExprTy = E->getType();
Ted Kremenek02be9682013-04-10 06:26:26 +00002795 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
2796 ExprTy = TET->getUnderlyingExpr()->getType();
2797 }
2798
Jordan Rose448ac3e2012-12-05 18:44:40 +00002799 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose614a8652012-09-05 22:56:19 +00002800 return true;
Jordan Roseee0259d2012-06-04 22:48:57 +00002801
Jordan Rose614a8652012-09-05 22:56:19 +00002802 // Look through argument promotions for our error message's reported type.
2803 // This includes the integral and floating promotions, but excludes array
2804 // and function pointer decay; seeing that an argument intended to be a
2805 // string has type 'char [6]' is probably more confusing than 'char *'.
2806 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2807 if (ICE->getCastKind() == CK_IntegralCast ||
2808 ICE->getCastKind() == CK_FloatingCast) {
2809 E = ICE->getSubExpr();
Jordan Rose448ac3e2012-12-05 18:44:40 +00002810 ExprTy = E->getType();
Jordan Rose614a8652012-09-05 22:56:19 +00002811
2812 // Check if we didn't match because of an implicit cast from a 'char'
2813 // or 'short' to an 'int'. This is done because printf is a varargs
2814 // function.
2815 if (ICE->getType() == S.Context.IntTy ||
2816 ICE->getType() == S.Context.UnsignedIntTy) {
2817 // All further checking is done on the subexpression.
Jordan Rose448ac3e2012-12-05 18:44:40 +00002818 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose614a8652012-09-05 22:56:19 +00002819 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00002820 }
Jordan Roseee0259d2012-06-04 22:48:57 +00002821 }
Jordan Rose448ac3e2012-12-05 18:44:40 +00002822 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
2823 // Special case for 'a', which has type 'int' in C.
2824 // Note, however, that we do /not/ want to treat multibyte constants like
2825 // 'MooV' as characters! This form is deprecated but still exists.
2826 if (ExprTy == S.Context.IntTy)
2827 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
2828 ExprTy = S.Context.CharTy;
Jordan Rose614a8652012-09-05 22:56:19 +00002829 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002830
Jordan Rose2cd34402012-12-05 18:44:49 +00002831 // %C in an Objective-C context prints a unichar, not a wchar_t.
2832 // If the argument is an integer of some kind, believe the %C and suggest
2833 // a cast instead of changing the conversion specifier.
Jordan Rose448ac3e2012-12-05 18:44:40 +00002834 QualType IntendedTy = ExprTy;
Jordan Rose2cd34402012-12-05 18:44:49 +00002835 if (ObjCContext &&
2836 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
2837 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
2838 !ExprTy->isCharType()) {
2839 // 'unichar' is defined as a typedef of unsigned short, but we should
2840 // prefer using the typedef if it is visible.
2841 IntendedTy = S.Context.UnsignedShortTy;
2842
2843 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
2844 Sema::LookupOrdinaryName);
2845 if (S.LookupName(Result, S.getCurScope())) {
2846 NamedDecl *ND = Result.getFoundDecl();
2847 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
2848 if (TD->getUnderlyingType() == IntendedTy)
2849 IntendedTy = S.Context.getTypedefType(TD);
2850 }
2851 }
2852 }
2853
2854 // Special-case some of Darwin's platform-independence types by suggesting
2855 // casts to primitive types that are known to be large enough.
2856 bool ShouldNotPrintDirectly = false;
Jordan Roseec087352012-09-05 22:56:26 +00002857 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Ted Kremenek6edb0292013-03-25 22:28:37 +00002858 // Use a 'while' to peel off layers of typedefs.
2859 QualType TyTy = IntendedTy;
2860 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
Jordan Roseec087352012-09-05 22:56:26 +00002861 StringRef Name = UserTy->getDecl()->getName();
Jordan Rose2cd34402012-12-05 18:44:49 +00002862 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Jordan Roseec087352012-09-05 22:56:26 +00002863 .Case("NSInteger", S.Context.LongTy)
2864 .Case("NSUInteger", S.Context.UnsignedLongTy)
2865 .Case("SInt32", S.Context.IntTy)
2866 .Case("UInt32", S.Context.UnsignedIntTy)
Jordan Rose2cd34402012-12-05 18:44:49 +00002867 .Default(QualType());
2868
2869 if (!CastTy.isNull()) {
2870 ShouldNotPrintDirectly = true;
2871 IntendedTy = CastTy;
Ted Kremenek6edb0292013-03-25 22:28:37 +00002872 break;
Jordan Rose2cd34402012-12-05 18:44:49 +00002873 }
Ted Kremenek6edb0292013-03-25 22:28:37 +00002874 TyTy = UserTy->desugar();
Jordan Roseec087352012-09-05 22:56:26 +00002875 }
2876 }
2877
Jordan Rose614a8652012-09-05 22:56:19 +00002878 // We may be able to offer a FixItHint if it is a supported type.
2879 PrintfSpecifier fixedFS = FS;
Jordan Roseec087352012-09-05 22:56:26 +00002880 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose614a8652012-09-05 22:56:19 +00002881 S.Context, ObjCContext);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002882
Jordan Rose614a8652012-09-05 22:56:19 +00002883 if (success) {
2884 // Get the fix string from the fixed format specifier
2885 SmallString<16> buf;
2886 llvm::raw_svector_ostream os(buf);
2887 fixedFS.toString(os);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002888
Jordan Roseec087352012-09-05 22:56:26 +00002889 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
2890
Jordan Rose2cd34402012-12-05 18:44:49 +00002891 if (IntendedTy == ExprTy) {
2892 // In this case, the specifier is wrong and should be changed to match
2893 // the argument.
2894 EmitFormatDiagnostic(
2895 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2896 << AT.getRepresentativeTypeName(S.Context) << IntendedTy
2897 << E->getSourceRange(),
2898 E->getLocStart(),
2899 /*IsStringLocation*/false,
2900 SpecRange,
2901 FixItHint::CreateReplacement(SpecRange, os.str()));
2902
2903 } else {
Jordan Roseec087352012-09-05 22:56:26 +00002904 // The canonical type for formatting this value is different from the
2905 // actual type of the expression. (This occurs, for example, with Darwin's
2906 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
2907 // should be printed as 'long' for 64-bit compatibility.)
2908 // Rather than emitting a normal format/argument mismatch, we want to
2909 // add a cast to the recommended type (and correct the format string
2910 // if necessary).
2911 SmallString<16> CastBuf;
2912 llvm::raw_svector_ostream CastFix(CastBuf);
2913 CastFix << "(";
2914 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
2915 CastFix << ")";
2916
2917 SmallVector<FixItHint,4> Hints;
2918 if (!AT.matchesType(S.Context, IntendedTy))
2919 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
2920
2921 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
2922 // If there's already a cast present, just replace it.
2923 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
2924 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
2925
2926 } else if (!requiresParensToAddCast(E)) {
2927 // If the expression has high enough precedence,
2928 // just write the C-style cast.
2929 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
2930 CastFix.str()));
2931 } else {
2932 // Otherwise, add parens around the expression as well as the cast.
2933 CastFix << "(";
2934 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
2935 CastFix.str()));
2936
2937 SourceLocation After = S.PP.getLocForEndOfToken(E->getLocEnd());
2938 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
2939 }
2940
Jordan Rose2cd34402012-12-05 18:44:49 +00002941 if (ShouldNotPrintDirectly) {
2942 // The expression has a type that should not be printed directly.
2943 // We extract the name from the typedef because we don't want to show
2944 // the underlying type in the diagnostic.
2945 StringRef Name = cast<TypedefType>(ExprTy)->getDecl()->getName();
Jordan Roseec087352012-09-05 22:56:26 +00002946
Jordan Rose2cd34402012-12-05 18:44:49 +00002947 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
2948 << Name << IntendedTy
2949 << E->getSourceRange(),
2950 E->getLocStart(), /*IsStringLocation=*/false,
2951 SpecRange, Hints);
2952 } else {
2953 // In this case, the expression could be printed using a different
2954 // specifier, but we've decided that the specifier is probably correct
2955 // and we should cast instead. Just use the normal warning message.
2956 EmitFormatDiagnostic(
2957 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2958 << AT.getRepresentativeTypeName(S.Context) << ExprTy
2959 << E->getSourceRange(),
2960 E->getLocStart(), /*IsStringLocation*/false,
2961 SpecRange, Hints);
2962 }
Jordan Roseec087352012-09-05 22:56:26 +00002963 }
Jordan Rose614a8652012-09-05 22:56:19 +00002964 } else {
2965 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
2966 SpecifierLen);
2967 // Since the warning for passing non-POD types to variadic functions
2968 // was deferred until now, we emit a warning for non-POD
2969 // arguments here.
Jordan Rose448ac3e2012-12-05 18:44:40 +00002970 if (S.isValidVarArgType(ExprTy) == Sema::VAK_Invalid) {
Jordan Rose614a8652012-09-05 22:56:19 +00002971 unsigned DiagKind;
Jordan Rose448ac3e2012-12-05 18:44:40 +00002972 if (ExprTy->isObjCObjectType())
Jordan Rose614a8652012-09-05 22:56:19 +00002973 DiagKind = diag::err_cannot_pass_objc_interface_to_vararg_format;
2974 else
2975 DiagKind = diag::warn_non_pod_vararg_with_format_string;
2976
2977 EmitFormatDiagnostic(
2978 S.PDiag(DiagKind)
Richard Smith80ad52f2013-01-02 11:42:31 +00002979 << S.getLangOpts().CPlusPlus11
Jordan Rose448ac3e2012-12-05 18:44:40 +00002980 << ExprTy
Jordan Rose614a8652012-09-05 22:56:19 +00002981 << CallType
2982 << AT.getRepresentativeTypeName(S.Context)
2983 << CSR
2984 << E->getSourceRange(),
2985 E->getLocStart(), /*IsStringLocation*/false, CSR);
2986
2987 checkForCStrMembers(AT, E, CSR);
2988 } else
Richard Trieu55733de2011-10-28 00:41:25 +00002989 EmitFormatDiagnostic(
2990 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Jordan Rose448ac3e2012-12-05 18:44:40 +00002991 << AT.getRepresentativeTypeName(S.Context) << ExprTy
Jordan Rose614a8652012-09-05 22:56:19 +00002992 << CSR
Richard Smith831421f2012-06-25 20:30:08 +00002993 << E->getSourceRange(),
Jordan Rose614a8652012-09-05 22:56:19 +00002994 E->getLocStart(), /*IsStringLocation*/false, CSR);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002995 }
2996
Ted Kremeneke0e53132010-01-28 23:39:18 +00002997 return true;
2998}
2999
Ted Kremenek826a3452010-07-16 02:11:22 +00003000//===--- CHECK: Scanf format string checking ------------------------------===//
3001
3002namespace {
3003class CheckScanfHandler : public CheckFormatHandler {
3004public:
3005 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3006 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00003007 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003008 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003009 unsigned formatIdx, bool inFunctionCall,
3010 Sema::VariadicCallType CallType)
Ted Kremenek826a3452010-07-16 02:11:22 +00003011 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00003012 numDataArgs, beg, hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003013 Args, formatIdx, inFunctionCall, CallType)
Jordan Roseddcfbc92012-07-19 18:10:23 +00003014 {}
Ted Kremenek826a3452010-07-16 02:11:22 +00003015
3016 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3017 const char *startSpecifier,
3018 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003019
3020 bool HandleInvalidScanfConversionSpecifier(
3021 const analyze_scanf::ScanfSpecifier &FS,
3022 const char *startSpecifier,
3023 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00003024
3025 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00003026};
Ted Kremenek07d161f2010-01-29 01:50:07 +00003027}
Ted Kremeneke0e53132010-01-28 23:39:18 +00003028
Ted Kremenekb7c21012010-07-16 18:28:03 +00003029void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3030 const char *end) {
Richard Trieu55733de2011-10-28 00:41:25 +00003031 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3032 getLocationOfByte(end), /*IsStringLocation*/true,
3033 getSpecifierRange(start, end - start));
Ted Kremenekb7c21012010-07-16 18:28:03 +00003034}
3035
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003036bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3037 const analyze_scanf::ScanfSpecifier &FS,
3038 const char *startSpecifier,
3039 unsigned specifierLen) {
3040
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003041 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003042 FS.getConversionSpecifier();
3043
3044 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3045 getLocationOfByte(CS.getStart()),
3046 startSpecifier, specifierLen,
3047 CS.getStart(), CS.getLength());
3048}
3049
Ted Kremenek826a3452010-07-16 02:11:22 +00003050bool CheckScanfHandler::HandleScanfSpecifier(
3051 const analyze_scanf::ScanfSpecifier &FS,
3052 const char *startSpecifier,
3053 unsigned specifierLen) {
3054
3055 using namespace analyze_scanf;
3056 using namespace analyze_format_string;
3057
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003058 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00003059
Ted Kremenekbaa40062010-07-19 22:01:06 +00003060 // Handle case where '%' and '*' don't consume an argument. These shouldn't
3061 // be used to decide if we are using positional arguments consistently.
3062 if (FS.consumesDataArgument()) {
3063 if (atFirstArg) {
3064 atFirstArg = false;
3065 usesPositionalArgs = FS.usesPositionalArg();
3066 }
3067 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00003068 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3069 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00003070 return false;
3071 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003072 }
3073
3074 // Check if the field with is non-zero.
3075 const OptionalAmount &Amt = FS.getFieldWidth();
3076 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3077 if (Amt.getConstantAmount() == 0) {
3078 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3079 Amt.getConstantLength());
Richard Trieu55733de2011-10-28 00:41:25 +00003080 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3081 getLocationOfByte(Amt.getStart()),
3082 /*IsStringLocation*/true, R,
3083 FixItHint::CreateRemoval(R));
Ted Kremenek826a3452010-07-16 02:11:22 +00003084 }
3085 }
3086
3087 if (!FS.consumesDataArgument()) {
3088 // FIXME: Technically specifying a precision or field width here
3089 // makes no sense. Worth issuing a warning at some point.
3090 return true;
3091 }
3092
3093 // Consume the argument.
3094 unsigned argIndex = FS.getArgIndex();
3095 if (argIndex < NumDataArgs) {
3096 // The check to see if the argIndex is valid will come later.
3097 // We set the bit here because we may exit early from this
3098 // function if we encounter some other error.
3099 CoveredArgs.set(argIndex);
3100 }
3101
Ted Kremenek1e51c202010-07-20 20:04:47 +00003102 // Check the length modifier is valid with the given conversion specifier.
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003103 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose8be066e2012-09-08 04:00:12 +00003104 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3105 diag::warn_format_nonsensical_length);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003106 else if (!FS.hasStandardLengthModifier())
Jordan Rose8be066e2012-09-08 04:00:12 +00003107 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003108 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose8be066e2012-09-08 04:00:12 +00003109 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3110 diag::warn_format_non_standard_conversion_spec);
Hans Wennborg76517422012-02-22 10:17:01 +00003111
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003112 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3113 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3114
Ted Kremenek826a3452010-07-16 02:11:22 +00003115 // The remaining checks depend on the data arguments.
3116 if (HasVAListArg)
3117 return true;
3118
Ted Kremenek666a1972010-07-26 19:45:42 +00003119 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00003120 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00003121
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003122 // Check that the argument type matches the format specifier.
3123 const Expr *Ex = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00003124 if (!Ex)
3125 return true;
3126
Hans Wennborg58e1e542012-08-07 08:59:46 +00003127 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3128 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003129 ScanfSpecifier fixedFS = FS;
David Blaikie4e4d0842012-03-11 07:00:24 +00003130 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
Hans Wennborgbe6126a2012-02-15 09:59:46 +00003131 S.Context);
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003132
3133 if (success) {
3134 // Get the fix string from the fixed format specifier.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003135 SmallString<128> buf;
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003136 llvm::raw_svector_ostream os(buf);
3137 fixedFS.toString(os);
3138
3139 EmitFormatDiagnostic(
3140 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg58e1e542012-08-07 08:59:46 +00003141 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003142 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00003143 Ex->getLocStart(),
3144 /*IsStringLocation*/false,
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003145 getSpecifierRange(startSpecifier, specifierLen),
3146 FixItHint::CreateReplacement(
3147 getSpecifierRange(startSpecifier, specifierLen),
3148 os.str()));
3149 } else {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003150 EmitFormatDiagnostic(
3151 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg58e1e542012-08-07 08:59:46 +00003152 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003153 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00003154 Ex->getLocStart(),
3155 /*IsStringLocation*/false,
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003156 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003157 }
3158 }
3159
Ted Kremenek826a3452010-07-16 02:11:22 +00003160 return true;
3161}
3162
3163void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00003164 const Expr *OrigFormatExpr,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003165 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003166 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003167 unsigned firstDataArg, FormatStringType Type,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003168 bool inFunctionCall, VariadicCallType CallType) {
Ted Kremenek826a3452010-07-16 02:11:22 +00003169
Ted Kremeneke0e53132010-01-28 23:39:18 +00003170 // CHECK: is the format string a wide literal?
Richard Smithdf9ef1b2012-06-13 05:37:23 +00003171 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu55733de2011-10-28 00:41:25 +00003172 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003173 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00003174 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3175 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00003176 return;
3177 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003178
Ted Kremeneke0e53132010-01-28 23:39:18 +00003179 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner5f9e2722011-07-23 10:55:15 +00003180 StringRef StrRef = FExpr->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00003181 const char *Str = StrRef.data();
3182 unsigned StrLen = StrRef.size();
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003183 const unsigned numDataArgs = Args.size() - firstDataArg;
Ted Kremenek826a3452010-07-16 02:11:22 +00003184
Ted Kremeneke0e53132010-01-28 23:39:18 +00003185 // CHECK: empty format string?
Ted Kremenek4cd57912011-09-29 05:52:16 +00003186 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu55733de2011-10-28 00:41:25 +00003187 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003188 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00003189 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3190 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00003191 return;
3192 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003193
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003194 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek826a3452010-07-16 02:11:22 +00003195 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00003196 numDataArgs, (Type == FST_NSString),
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003197 Str, HasVAListArg, Args, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003198 inFunctionCall, CallType);
Ted Kremenek826a3452010-07-16 02:11:22 +00003199
Hans Wennborgd02deeb2011-12-15 10:25:47 +00003200 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose275b6f52012-09-13 02:11:03 +00003201 getLangOpts(),
3202 Context.getTargetInfo()))
Ted Kremenek826a3452010-07-16 02:11:22 +00003203 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003204 } else if (Type == FST_Scanf) {
Jordan Rose50687312012-06-04 23:52:23 +00003205 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003206 Str, HasVAListArg, Args, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003207 inFunctionCall, CallType);
Ted Kremenek826a3452010-07-16 02:11:22 +00003208
Hans Wennborgd02deeb2011-12-15 10:25:47 +00003209 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose275b6f52012-09-13 02:11:03 +00003210 getLangOpts(),
3211 Context.getTargetInfo()))
Ted Kremenek826a3452010-07-16 02:11:22 +00003212 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003213 } // TODO: handle other formats
Ted Kremenekce7024e2010-01-28 01:18:22 +00003214}
3215
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003216//===--- CHECK: Standard memory functions ---------------------------------===//
3217
Douglas Gregor2a053a32011-05-03 20:05:22 +00003218/// \brief Determine whether the given type is a dynamic class type (e.g.,
3219/// whether it has a vtable).
3220static bool isDynamicClassType(QualType T) {
3221 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3222 if (CXXRecordDecl *Definition = Record->getDefinition())
3223 if (Definition->isDynamicClass())
3224 return true;
3225
3226 return false;
3227}
3228
Chandler Carrutha72a12f2011-06-21 23:04:20 +00003229/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth000d4282011-06-16 09:09:40 +00003230/// otherwise returns NULL.
3231static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Webere4a1c642011-06-14 16:14:58 +00003232 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth000d4282011-06-16 09:09:40 +00003233 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3234 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
3235 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00003236
Chandler Carruth000d4282011-06-16 09:09:40 +00003237 return 0;
3238}
3239
Chandler Carrutha72a12f2011-06-21 23:04:20 +00003240/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth000d4282011-06-16 09:09:40 +00003241static QualType getSizeOfArgType(const Expr* E) {
3242 if (const UnaryExprOrTypeTraitExpr *SizeOf =
3243 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3244 if (SizeOf->getKind() == clang::UETT_SizeOf)
3245 return SizeOf->getTypeOfArgument();
3246
3247 return QualType();
Nico Webere4a1c642011-06-14 16:14:58 +00003248}
3249
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003250/// \brief Check for dangerous or invalid arguments to memset().
3251///
Chandler Carruth929f0132011-06-03 06:23:57 +00003252/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003253/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
3254/// function calls.
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003255///
3256/// \param Call The call expression to diagnose.
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003257void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks0a151a12012-01-17 00:37:07 +00003258 unsigned BId,
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003259 IdentifierInfo *FnName) {
Anna Zaks0a151a12012-01-17 00:37:07 +00003260 assert(BId != 0);
3261
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00003262 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor707a23e2011-06-16 17:56:04 +00003263 // we have enough arguments, and if not, abort further checking.
Anna Zaks0a151a12012-01-17 00:37:07 +00003264 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Webercda57822011-10-13 22:30:23 +00003265 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00003266 return;
3267
Anna Zaks0a151a12012-01-17 00:37:07 +00003268 unsigned LastArg = (BId == Builtin::BImemset ||
3269 BId == Builtin::BIstrndup ? 1 : 2);
3270 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Webercda57822011-10-13 22:30:23 +00003271 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth000d4282011-06-16 09:09:40 +00003272
3273 // We have special checking when the length is a sizeof expression.
3274 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
3275 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
3276 llvm::FoldingSetNodeID SizeOfArgID;
3277
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003278 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
3279 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00003280 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003281
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003282 QualType DestTy = Dest->getType();
3283 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
3284 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00003285
Chandler Carruth000d4282011-06-16 09:09:40 +00003286 // Never warn about void type pointers. This can be used to suppress
3287 // false positives.
3288 if (PointeeTy->isVoidType())
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003289 continue;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003290
Chandler Carruth000d4282011-06-16 09:09:40 +00003291 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
3292 // actually comparing the expressions for equality. Because computing the
3293 // expression IDs can be expensive, we only do this if the diagnostic is
3294 // enabled.
3295 if (SizeOfArg &&
3296 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
3297 SizeOfArg->getExprLoc())) {
3298 // We only compute IDs for expressions if the warning is enabled, and
3299 // cache the sizeof arg's ID.
3300 if (SizeOfArgID == llvm::FoldingSetNodeID())
3301 SizeOfArg->Profile(SizeOfArgID, Context, true);
3302 llvm::FoldingSetNodeID DestID;
3303 Dest->Profile(DestID, Context, true);
3304 if (DestID == SizeOfArgID) {
Nico Webercda57822011-10-13 22:30:23 +00003305 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
3306 // over sizeof(src) as well.
Chandler Carruth000d4282011-06-16 09:09:40 +00003307 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks6fcb3722012-05-30 00:34:21 +00003308 StringRef ReadableName = FnName->getName();
3309
Chandler Carruth000d4282011-06-16 09:09:40 +00003310 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaks90c78322012-05-30 23:14:52 +00003311 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth000d4282011-06-16 09:09:40 +00003312 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian7adf4172013-01-30 01:12:44 +00003313 if (!PointeeTy->isIncompleteType() &&
3314 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth000d4282011-06-16 09:09:40 +00003315 ActionIdx = 2; // If the pointee's size is sizeof(char),
3316 // suggest an explicit length.
Anna Zaks6fcb3722012-05-30 00:34:21 +00003317
3318 // If the function is defined as a builtin macro, do not show macro
3319 // expansion.
3320 SourceLocation SL = SizeOfArg->getExprLoc();
3321 SourceRange DSR = Dest->getSourceRange();
3322 SourceRange SSR = SizeOfArg->getSourceRange();
3323 SourceManager &SM = PP.getSourceManager();
3324
3325 if (SM.isMacroArgExpansion(SL)) {
3326 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
3327 SL = SM.getSpellingLoc(SL);
3328 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
3329 SM.getSpellingLoc(DSR.getEnd()));
3330 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
3331 SM.getSpellingLoc(SSR.getEnd()));
3332 }
3333
Anna Zaks90c78322012-05-30 23:14:52 +00003334 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth000d4282011-06-16 09:09:40 +00003335 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks6fcb3722012-05-30 00:34:21 +00003336 << ReadableName
Anna Zaks90c78322012-05-30 23:14:52 +00003337 << PointeeTy
3338 << DestTy
Anna Zaks6fcb3722012-05-30 00:34:21 +00003339 << DSR
Anna Zaks90c78322012-05-30 23:14:52 +00003340 << SSR);
3341 DiagRuntimeBehavior(SL, SizeOfArg,
3342 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
3343 << ActionIdx
3344 << SSR);
3345
Chandler Carruth000d4282011-06-16 09:09:40 +00003346 break;
3347 }
3348 }
3349
3350 // Also check for cases where the sizeof argument is the exact same
3351 // type as the memory argument, and where it points to a user-defined
3352 // record type.
3353 if (SizeOfArgTy != QualType()) {
3354 if (PointeeTy->isRecordType() &&
3355 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
3356 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
3357 PDiag(diag::warn_sizeof_pointer_type_memaccess)
3358 << FnName << SizeOfArgTy << ArgIdx
3359 << PointeeTy << Dest->getSourceRange()
3360 << LenExpr->getSourceRange());
3361 break;
3362 }
Nico Webere4a1c642011-06-14 16:14:58 +00003363 }
3364
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003365 // Always complain about dynamic classes.
Anna Zaks0a151a12012-01-17 00:37:07 +00003366 if (isDynamicClassType(PointeeTy)) {
3367
3368 unsigned OperationType = 0;
3369 // "overwritten" if we're warning about the destination for any call
3370 // but memcmp; otherwise a verb appropriate to the call.
3371 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
3372 if (BId == Builtin::BImemcpy)
3373 OperationType = 1;
3374 else if(BId == Builtin::BImemmove)
3375 OperationType = 2;
3376 else if (BId == Builtin::BImemcmp)
3377 OperationType = 3;
3378 }
3379
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003380 DiagRuntimeBehavior(
3381 Dest->getExprLoc(), Dest,
3382 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks0a151a12012-01-17 00:37:07 +00003383 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Anna Zaksd9b859a2012-01-13 21:52:01 +00003384 << FnName << PointeeTy
Anna Zaks0a151a12012-01-17 00:37:07 +00003385 << OperationType
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003386 << Call->getCallee()->getSourceRange());
Anna Zaks0a151a12012-01-17 00:37:07 +00003387 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
3388 BId != Builtin::BImemset)
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003389 DiagRuntimeBehavior(
3390 Dest->getExprLoc(), Dest,
3391 PDiag(diag::warn_arc_object_memaccess)
3392 << ArgIdx << FnName << PointeeTy
3393 << Call->getCallee()->getSourceRange());
John McCallf85e1932011-06-15 23:02:42 +00003394 else
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003395 continue;
John McCallf85e1932011-06-15 23:02:42 +00003396
3397 DiagRuntimeBehavior(
3398 Dest->getExprLoc(), Dest,
Chandler Carruth929f0132011-06-03 06:23:57 +00003399 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003400 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
3401 break;
3402 }
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003403 }
3404}
3405
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003406// A little helper routine: ignore addition and subtraction of integer literals.
3407// This intentionally does not ignore all integer constant expressions because
3408// we don't want to remove sizeof().
3409static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
3410 Ex = Ex->IgnoreParenCasts();
3411
3412 for (;;) {
3413 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
3414 if (!BO || !BO->isAdditiveOp())
3415 break;
3416
3417 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
3418 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
3419
3420 if (isa<IntegerLiteral>(RHS))
3421 Ex = LHS;
3422 else if (isa<IntegerLiteral>(LHS))
3423 Ex = RHS;
3424 else
3425 break;
3426 }
3427
3428 return Ex;
3429}
3430
Anna Zaks0f38ace2012-08-08 21:42:23 +00003431static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
3432 ASTContext &Context) {
3433 // Only handle constant-sized or VLAs, but not flexible members.
3434 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
3435 // Only issue the FIXIT for arrays of size > 1.
3436 if (CAT->getSize().getSExtValue() <= 1)
3437 return false;
3438 } else if (!Ty->isVariableArrayType()) {
3439 return false;
3440 }
3441 return true;
3442}
3443
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003444// Warn if the user has made the 'size' argument to strlcpy or strlcat
3445// be the size of the source, instead of the destination.
3446void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
3447 IdentifierInfo *FnName) {
3448
3449 // Don't crash if the user has the wrong number of arguments
3450 if (Call->getNumArgs() != 3)
3451 return;
3452
3453 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
3454 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
3455 const Expr *CompareWithSrc = NULL;
3456
3457 // Look for 'strlcpy(dst, x, sizeof(x))'
3458 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
3459 CompareWithSrc = Ex;
3460 else {
3461 // Look for 'strlcpy(dst, x, strlen(x))'
3462 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Richard Smith180f4792011-11-10 06:34:14 +00003463 if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003464 && SizeCall->getNumArgs() == 1)
3465 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
3466 }
3467 }
3468
3469 if (!CompareWithSrc)
3470 return;
3471
3472 // Determine if the argument to sizeof/strlen is equal to the source
3473 // argument. In principle there's all kinds of things you could do
3474 // here, for instance creating an == expression and evaluating it with
3475 // EvaluateAsBooleanCondition, but this uses a more direct technique:
3476 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
3477 if (!SrcArgDRE)
3478 return;
3479
3480 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
3481 if (!CompareWithSrcDRE ||
3482 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
3483 return;
3484
3485 const Expr *OriginalSizeArg = Call->getArg(2);
3486 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
3487 << OriginalSizeArg->getSourceRange() << FnName;
3488
3489 // Output a FIXIT hint if the destination is an array (rather than a
3490 // pointer to an array). This could be enhanced to handle some
3491 // pointers if we know the actual size, like if DstArg is 'array+2'
3492 // we could say 'sizeof(array)-2'.
3493 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks0f38ace2012-08-08 21:42:23 +00003494 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek8f746222011-08-18 22:48:41 +00003495 return;
Ted Kremenek8f746222011-08-18 22:48:41 +00003496
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003497 SmallString<128> sizeString;
Ted Kremenek8f746222011-08-18 22:48:41 +00003498 llvm::raw_svector_ostream OS(sizeString);
3499 OS << "sizeof(";
Richard Smithd1420c62012-08-16 03:56:14 +00003500 DstArg->printPretty(OS, 0, getPrintingPolicy());
Ted Kremenek8f746222011-08-18 22:48:41 +00003501 OS << ")";
3502
3503 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
3504 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
3505 OS.str());
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003506}
3507
Anna Zaksc36bedc2012-02-01 19:08:57 +00003508/// Check if two expressions refer to the same declaration.
3509static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
3510 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
3511 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
3512 return D1->getDecl() == D2->getDecl();
3513 return false;
3514}
3515
3516static const Expr *getStrlenExprArg(const Expr *E) {
3517 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
3518 const FunctionDecl *FD = CE->getDirectCallee();
3519 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
3520 return 0;
3521 return CE->getArg(0)->IgnoreParenCasts();
3522 }
3523 return 0;
3524}
3525
3526// Warn on anti-patterns as the 'size' argument to strncat.
3527// The correct size argument should look like following:
3528// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
3529void Sema::CheckStrncatArguments(const CallExpr *CE,
3530 IdentifierInfo *FnName) {
3531 // Don't crash if the user has the wrong number of arguments.
3532 if (CE->getNumArgs() < 3)
3533 return;
3534 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
3535 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
3536 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
3537
3538 // Identify common expressions, which are wrongly used as the size argument
3539 // to strncat and may lead to buffer overflows.
3540 unsigned PatternType = 0;
3541 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
3542 // - sizeof(dst)
3543 if (referToTheSameDecl(SizeOfArg, DstArg))
3544 PatternType = 1;
3545 // - sizeof(src)
3546 else if (referToTheSameDecl(SizeOfArg, SrcArg))
3547 PatternType = 2;
3548 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
3549 if (BE->getOpcode() == BO_Sub) {
3550 const Expr *L = BE->getLHS()->IgnoreParenCasts();
3551 const Expr *R = BE->getRHS()->IgnoreParenCasts();
3552 // - sizeof(dst) - strlen(dst)
3553 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
3554 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
3555 PatternType = 1;
3556 // - sizeof(src) - (anything)
3557 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
3558 PatternType = 2;
3559 }
3560 }
3561
3562 if (PatternType == 0)
3563 return;
3564
Anna Zaksafdb0412012-02-03 01:27:37 +00003565 // Generate the diagnostic.
3566 SourceLocation SL = LenArg->getLocStart();
3567 SourceRange SR = LenArg->getSourceRange();
3568 SourceManager &SM = PP.getSourceManager();
3569
3570 // If the function is defined as a builtin macro, do not show macro expansion.
3571 if (SM.isMacroArgExpansion(SL)) {
3572 SL = SM.getSpellingLoc(SL);
3573 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
3574 SM.getSpellingLoc(SR.getEnd()));
3575 }
3576
Anna Zaks0f38ace2012-08-08 21:42:23 +00003577 // Check if the destination is an array (rather than a pointer to an array).
3578 QualType DstTy = DstArg->getType();
3579 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
3580 Context);
3581 if (!isKnownSizeArray) {
3582 if (PatternType == 1)
3583 Diag(SL, diag::warn_strncat_wrong_size) << SR;
3584 else
3585 Diag(SL, diag::warn_strncat_src_size) << SR;
3586 return;
3587 }
3588
Anna Zaksc36bedc2012-02-01 19:08:57 +00003589 if (PatternType == 1)
Anna Zaksafdb0412012-02-03 01:27:37 +00003590 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003591 else
Anna Zaksafdb0412012-02-03 01:27:37 +00003592 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003593
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003594 SmallString<128> sizeString;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003595 llvm::raw_svector_ostream OS(sizeString);
3596 OS << "sizeof(";
Richard Smithd1420c62012-08-16 03:56:14 +00003597 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003598 OS << ") - ";
3599 OS << "strlen(";
Richard Smithd1420c62012-08-16 03:56:14 +00003600 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003601 OS << ") - 1";
3602
Anna Zaksafdb0412012-02-03 01:27:37 +00003603 Diag(SL, diag::note_strncat_wrong_size)
3604 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003605}
3606
Ted Kremenek06de2762007-08-17 16:46:58 +00003607//===--- CHECK: Return Address of Stack Variable --------------------------===//
3608
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003609static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3610 Decl *ParentDecl);
3611static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
3612 Decl *ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003613
3614/// CheckReturnStackAddr - Check if a return statement returns the address
3615/// of a stack variable.
3616void
3617Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
3618 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00003619
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003620 Expr *stackE = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003621 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003622
3623 // Perform checking for returned stack addresses, local blocks,
3624 // label addresses or references to temporaries.
John McCallf85e1932011-06-15 23:02:42 +00003625 if (lhsType->isPointerType() ||
David Blaikie4e4d0842012-03-11 07:00:24 +00003626 (!getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003627 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003628 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003629 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003630 }
3631
3632 if (stackE == 0)
3633 return; // Nothing suspicious was found.
3634
3635 SourceLocation diagLoc;
3636 SourceRange diagRange;
3637 if (refVars.empty()) {
3638 diagLoc = stackE->getLocStart();
3639 diagRange = stackE->getSourceRange();
3640 } else {
3641 // We followed through a reference variable. 'stackE' contains the
3642 // problematic expression but we will warn at the return statement pointing
3643 // at the reference variable. We will later display the "trail" of
3644 // reference variables using notes.
3645 diagLoc = refVars[0]->getLocStart();
3646 diagRange = refVars[0]->getSourceRange();
3647 }
3648
3649 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
3650 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
3651 : diag::warn_ret_stack_addr)
3652 << DR->getDecl()->getDeclName() << diagRange;
3653 } else if (isa<BlockExpr>(stackE)) { // local block.
3654 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
3655 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
3656 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
3657 } else { // local temporary.
3658 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
3659 : diag::warn_ret_local_temp_addr)
3660 << diagRange;
3661 }
3662
3663 // Display the "trail" of reference variables that we followed until we
3664 // found the problematic expression using notes.
3665 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
3666 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
3667 // If this var binds to another reference var, show the range of the next
3668 // var, otherwise the var binds to the problematic expression, in which case
3669 // show the range of the expression.
3670 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
3671 : stackE->getSourceRange();
3672 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
3673 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00003674 }
3675}
3676
3677/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
3678/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003679/// to a location on the stack, a local block, an address of a label, or a
3680/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00003681/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003682/// encounter a subexpression that (1) clearly does not lead to one of the
3683/// above problematic expressions (2) is something we cannot determine leads to
3684/// a problematic expression based on such local checking.
3685///
3686/// Both EvalAddr and EvalVal follow through reference variables to evaluate
3687/// the expression that they point to. Such variables are added to the
3688/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00003689///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00003690/// EvalAddr processes expressions that are pointers that are used as
3691/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003692/// At the base case of the recursion is a check for the above problematic
3693/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00003694///
3695/// This implementation handles:
3696///
3697/// * pointer-to-pointer casts
3698/// * implicit conversions from array references to pointers
3699/// * taking the address of fields
3700/// * arbitrary interplay between "&" and "*" operators
3701/// * pointer arithmetic from an address of a stack variable
3702/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003703static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3704 Decl *ParentDecl) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003705 if (E->isTypeDependent())
3706 return NULL;
3707
Ted Kremenek06de2762007-08-17 16:46:58 +00003708 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00003709 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00003710 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003711 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003712 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00003713
Peter Collingbournef111d932011-04-15 00:35:48 +00003714 E = E->IgnoreParens();
3715
Ted Kremenek06de2762007-08-17 16:46:58 +00003716 // Our "symbolic interpreter" is just a dispatch off the currently
3717 // viewed AST node. We then recursively traverse the AST by calling
3718 // EvalAddr and EvalVal appropriately.
3719 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003720 case Stmt::DeclRefExprClass: {
3721 DeclRefExpr *DR = cast<DeclRefExpr>(E);
3722
3723 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
3724 // If this is a reference variable, follow through to the expression that
3725 // it points to.
3726 if (V->hasLocalStorage() &&
3727 V->getType()->isReferenceType() && V->hasInit()) {
3728 // Add the reference variable to the "trail".
3729 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003730 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003731 }
3732
3733 return NULL;
3734 }
Ted Kremenek06de2762007-08-17 16:46:58 +00003735
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003736 case Stmt::UnaryOperatorClass: {
3737 // The only unary operator that make sense to handle here
3738 // is AddrOf. All others don't make sense as pointers.
3739 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003740
John McCall2de56d12010-08-25 11:45:40 +00003741 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003742 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003743 else
Ted Kremenek06de2762007-08-17 16:46:58 +00003744 return NULL;
3745 }
Mike Stump1eb44332009-09-09 15:08:12 +00003746
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003747 case Stmt::BinaryOperatorClass: {
3748 // Handle pointer arithmetic. All other binary operators are not valid
3749 // in this context.
3750 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00003751 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00003752
John McCall2de56d12010-08-25 11:45:40 +00003753 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003754 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00003755
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003756 Expr *Base = B->getLHS();
3757
3758 // Determine which argument is the real pointer base. It could be
3759 // the RHS argument instead of the LHS.
3760 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00003761
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003762 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003763 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003764 }
Steve Naroff61f40a22008-09-10 19:17:48 +00003765
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003766 // For conditional operators we need to see if either the LHS or RHS are
3767 // valid DeclRefExpr*s. If one of them is valid, we return it.
3768 case Stmt::ConditionalOperatorClass: {
3769 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003770
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003771 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003772 if (Expr *lhsExpr = C->getLHS()) {
3773 // In C++, we can have a throw-expression, which has 'void' type.
3774 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003775 if (Expr* LHS = EvalAddr(lhsExpr, refVars, ParentDecl))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003776 return LHS;
3777 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003778
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003779 // In C++, we can have a throw-expression, which has 'void' type.
3780 if (C->getRHS()->getType()->isVoidType())
3781 return NULL;
3782
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003783 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003784 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003785
3786 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00003787 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003788 return E; // local block.
3789 return NULL;
3790
3791 case Stmt::AddrLabelExprClass:
3792 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00003793
John McCall80ee6e82011-11-10 05:35:25 +00003794 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003795 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
3796 ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00003797
Ted Kremenek54b52742008-08-07 00:49:01 +00003798 // For casts, we need to handle conversions from arrays to
3799 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00003800 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00003801 case Stmt::CStyleCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00003802 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8b9414e2012-02-23 23:04:32 +00003803 case Stmt::ObjCBridgedCastExprClass:
Mike Stump1eb44332009-09-09 15:08:12 +00003804 case Stmt::CXXStaticCastExprClass:
3805 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00003806 case Stmt::CXXConstCastExprClass:
3807 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8b9414e2012-02-23 23:04:32 +00003808 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
3809 switch (cast<CastExpr>(E)->getCastKind()) {
3810 case CK_BitCast:
3811 case CK_LValueToRValue:
3812 case CK_NoOp:
3813 case CK_BaseToDerived:
3814 case CK_DerivedToBase:
3815 case CK_UncheckedDerivedToBase:
3816 case CK_Dynamic:
3817 case CK_CPointerToObjCPointerCast:
3818 case CK_BlockPointerToObjCPointerCast:
3819 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003820 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00003821
3822 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003823 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00003824
3825 default:
3826 return 0;
3827 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003828 }
Mike Stump1eb44332009-09-09 15:08:12 +00003829
Douglas Gregor03e80032011-06-21 17:03:29 +00003830 case Stmt::MaterializeTemporaryExprClass:
3831 if (Expr *Result = EvalAddr(
3832 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003833 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00003834 return Result;
3835
3836 return E;
3837
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003838 // Everything else: we simply don't reason about them.
3839 default:
3840 return NULL;
3841 }
Ted Kremenek06de2762007-08-17 16:46:58 +00003842}
Mike Stump1eb44332009-09-09 15:08:12 +00003843
Ted Kremenek06de2762007-08-17 16:46:58 +00003844
3845/// EvalVal - This function is complements EvalAddr in the mutual recursion.
3846/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003847static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3848 Decl *ParentDecl) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003849do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00003850 // We should only be called for evaluating non-pointer expressions, or
3851 // expressions with a pointer type that are not used as references but instead
3852 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00003853
Ted Kremenek06de2762007-08-17 16:46:58 +00003854 // Our "symbolic interpreter" is just a dispatch off the currently
3855 // viewed AST node. We then recursively traverse the AST by calling
3856 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00003857
3858 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00003859 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003860 case Stmt::ImplicitCastExprClass: {
3861 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00003862 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003863 E = IE->getSubExpr();
3864 continue;
3865 }
3866 return NULL;
3867 }
3868
John McCall80ee6e82011-11-10 05:35:25 +00003869 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003870 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00003871
Douglas Gregora2813ce2009-10-23 18:54:35 +00003872 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003873 // When we hit a DeclRefExpr we are looking at code that refers to a
3874 // variable's name. If it's not a reference variable we check if it has
3875 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00003876 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003877
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003878 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
3879 // Check if it refers to itself, e.g. "int& i = i;".
3880 if (V == ParentDecl)
3881 return DR;
3882
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003883 if (V->hasLocalStorage()) {
3884 if (!V->getType()->isReferenceType())
3885 return DR;
3886
3887 // Reference variable, follow through to the expression that
3888 // it points to.
3889 if (V->hasInit()) {
3890 // Add the reference variable to the "trail".
3891 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003892 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003893 }
3894 }
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003895 }
Mike Stump1eb44332009-09-09 15:08:12 +00003896
Ted Kremenek06de2762007-08-17 16:46:58 +00003897 return NULL;
3898 }
Mike Stump1eb44332009-09-09 15:08:12 +00003899
Ted Kremenek06de2762007-08-17 16:46:58 +00003900 case Stmt::UnaryOperatorClass: {
3901 // The only unary operator that make sense to handle here
3902 // is Deref. All others don't resolve to a "name." This includes
3903 // handling all sorts of rvalues passed to a unary operator.
3904 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003905
John McCall2de56d12010-08-25 11:45:40 +00003906 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003907 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003908
3909 return NULL;
3910 }
Mike Stump1eb44332009-09-09 15:08:12 +00003911
Ted Kremenek06de2762007-08-17 16:46:58 +00003912 case Stmt::ArraySubscriptExprClass: {
3913 // Array subscripts are potential references to data on the stack. We
3914 // retrieve the DeclRefExpr* for the array variable if it indeed
3915 // has local storage.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003916 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003917 }
Mike Stump1eb44332009-09-09 15:08:12 +00003918
Ted Kremenek06de2762007-08-17 16:46:58 +00003919 case Stmt::ConditionalOperatorClass: {
3920 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003921 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00003922 ConditionalOperator *C = cast<ConditionalOperator>(E);
3923
Anders Carlsson39073232007-11-30 19:04:31 +00003924 // Handle the GNU extension for missing LHS.
3925 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003926 if (Expr *LHS = EvalVal(lhsExpr, refVars, ParentDecl))
Anders Carlsson39073232007-11-30 19:04:31 +00003927 return LHS;
3928
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003929 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003930 }
Mike Stump1eb44332009-09-09 15:08:12 +00003931
Ted Kremenek06de2762007-08-17 16:46:58 +00003932 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00003933 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00003934 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003935
Ted Kremenek06de2762007-08-17 16:46:58 +00003936 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00003937 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00003938 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00003939
3940 // Check whether the member type is itself a reference, in which case
3941 // we're not going to refer to the member, but to what the member refers to.
3942 if (M->getMemberDecl()->getType()->isReferenceType())
3943 return NULL;
3944
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003945 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003946 }
Mike Stump1eb44332009-09-09 15:08:12 +00003947
Douglas Gregor03e80032011-06-21 17:03:29 +00003948 case Stmt::MaterializeTemporaryExprClass:
3949 if (Expr *Result = EvalVal(
3950 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003951 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00003952 return Result;
3953
3954 return E;
3955
Ted Kremenek06de2762007-08-17 16:46:58 +00003956 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003957 // Check that we don't return or take the address of a reference to a
3958 // temporary. This is only useful in C++.
3959 if (!E->isTypeDependent() && E->isRValue())
3960 return E;
3961
3962 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00003963 return NULL;
3964 }
Ted Kremenek68957a92010-08-04 20:01:07 +00003965} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00003966}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003967
3968//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
3969
3970/// Check for comparisons of floating point operands using != and ==.
3971/// Issue a warning if these are no self-comparisons, as they are not likely
3972/// to do what the programmer intended.
Richard Trieudd225092011-09-15 21:56:47 +00003973void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieudd225092011-09-15 21:56:47 +00003974 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
3975 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003976
3977 // Special case: check for x == x (which is OK).
3978 // Do not emit warnings for such cases.
3979 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
3980 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
3981 if (DRL->getDecl() == DRR->getDecl())
David Blaikie980343b2012-07-16 20:47:22 +00003982 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003983
3984
Ted Kremenek1b500bb2007-11-29 00:59:04 +00003985 // Special case: check for comparisons against literals that can be exactly
3986 // represented by APFloat. In such cases, do not emit a warning. This
3987 // is a heuristic: often comparison against such literals are used to
3988 // detect if a value in a variable has not changed. This clearly can
3989 // lead to false negatives.
David Blaikie980343b2012-07-16 20:47:22 +00003990 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
3991 if (FLL->isExact())
3992 return;
3993 } else
3994 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
3995 if (FLR->isExact())
3996 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003997
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003998 // Check for comparisons with builtin types.
David Blaikie980343b2012-07-16 20:47:22 +00003999 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
4000 if (CL->isBuiltinCall())
4001 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004002
David Blaikie980343b2012-07-16 20:47:22 +00004003 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
4004 if (CR->isBuiltinCall())
4005 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004006
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004007 // Emit the diagnostic.
David Blaikie980343b2012-07-16 20:47:22 +00004008 Diag(Loc, diag::warn_floatingpoint_eq)
4009 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004010}
John McCallba26e582010-01-04 23:21:16 +00004011
John McCallf2370c92010-01-06 05:24:50 +00004012//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
4013//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00004014
John McCallf2370c92010-01-06 05:24:50 +00004015namespace {
John McCallba26e582010-01-04 23:21:16 +00004016
John McCallf2370c92010-01-06 05:24:50 +00004017/// Structure recording the 'active' range of an integer-valued
4018/// expression.
4019struct IntRange {
4020 /// The number of bits active in the int.
4021 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00004022
John McCallf2370c92010-01-06 05:24:50 +00004023 /// True if the int is known not to have negative values.
4024 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00004025
John McCallf2370c92010-01-06 05:24:50 +00004026 IntRange(unsigned Width, bool NonNegative)
4027 : Width(Width), NonNegative(NonNegative)
4028 {}
John McCallba26e582010-01-04 23:21:16 +00004029
John McCall1844a6e2010-11-10 23:38:19 +00004030 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00004031 static IntRange forBoolType() {
4032 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00004033 }
4034
John McCall1844a6e2010-11-10 23:38:19 +00004035 /// Returns the range of an opaque value of the given integral type.
4036 static IntRange forValueOfType(ASTContext &C, QualType T) {
4037 return forValueOfCanonicalType(C,
4038 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00004039 }
4040
John McCall1844a6e2010-11-10 23:38:19 +00004041 /// Returns the range of an opaque value of a canonical integral type.
4042 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00004043 assert(T->isCanonicalUnqualified());
4044
4045 if (const VectorType *VT = dyn_cast<VectorType>(T))
4046 T = VT->getElementType().getTypePtr();
4047 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4048 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00004049
David Majnemerf9eaf982013-06-07 22:07:20 +00004050 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00004051 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemerf9eaf982013-06-07 22:07:20 +00004052 EnumDecl *Enum = ET->getDecl();
4053 if (!Enum->isCompleteDefinition())
4054 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall091f23f2010-11-09 22:22:12 +00004055
David Majnemerf9eaf982013-06-07 22:07:20 +00004056 unsigned NumPositive = Enum->getNumPositiveBits();
4057 unsigned NumNegative = Enum->getNumNegativeBits();
John McCall323ed742010-05-06 08:58:33 +00004058
David Majnemerf9eaf982013-06-07 22:07:20 +00004059 if (NumNegative == 0)
4060 return IntRange(NumPositive, true/*NonNegative*/);
4061 else
4062 return IntRange(std::max(NumPositive + 1, NumNegative),
4063 false/*NonNegative*/);
John McCall323ed742010-05-06 08:58:33 +00004064 }
John McCallf2370c92010-01-06 05:24:50 +00004065
4066 const BuiltinType *BT = cast<BuiltinType>(T);
4067 assert(BT->isInteger());
4068
4069 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4070 }
4071
John McCall1844a6e2010-11-10 23:38:19 +00004072 /// Returns the "target" range of a canonical integral type, i.e.
4073 /// the range of values expressible in the type.
4074 ///
4075 /// This matches forValueOfCanonicalType except that enums have the
4076 /// full range of their type, not the range of their enumerators.
4077 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
4078 assert(T->isCanonicalUnqualified());
4079
4080 if (const VectorType *VT = dyn_cast<VectorType>(T))
4081 T = VT->getElementType().getTypePtr();
4082 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4083 T = CT->getElementType().getTypePtr();
4084 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor69ff26b2011-09-08 23:29:05 +00004085 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall1844a6e2010-11-10 23:38:19 +00004086
4087 const BuiltinType *BT = cast<BuiltinType>(T);
4088 assert(BT->isInteger());
4089
4090 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4091 }
4092
4093 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00004094 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00004095 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00004096 L.NonNegative && R.NonNegative);
4097 }
4098
John McCall1844a6e2010-11-10 23:38:19 +00004099 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00004100 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00004101 return IntRange(std::min(L.Width, R.Width),
4102 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00004103 }
4104};
4105
Ted Kremenek0692a192012-01-31 05:37:37 +00004106static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
4107 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004108 if (value.isSigned() && value.isNegative())
4109 return IntRange(value.getMinSignedBits(), false);
4110
4111 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00004112 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00004113
4114 // isNonNegative() just checks the sign bit without considering
4115 // signedness.
4116 return IntRange(value.getActiveBits(), true);
4117}
4118
Ted Kremenek0692a192012-01-31 05:37:37 +00004119static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
4120 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004121 if (result.isInt())
4122 return GetValueRange(C, result.getInt(), MaxWidth);
4123
4124 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00004125 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
4126 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
4127 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
4128 R = IntRange::join(R, El);
4129 }
John McCallf2370c92010-01-06 05:24:50 +00004130 return R;
4131 }
4132
4133 if (result.isComplexInt()) {
4134 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
4135 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
4136 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00004137 }
4138
4139 // This can happen with lossless casts to intptr_t of "based" lvalues.
4140 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00004141 // FIXME: The only reason we need to pass the type in here is to get
4142 // the sign right on this one case. It would be nice if APValue
4143 // preserved this.
Eli Friedman65639282012-01-04 23:13:47 +00004144 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00004145 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall51313c32010-01-04 23:31:57 +00004146}
John McCallf2370c92010-01-06 05:24:50 +00004147
4148/// Pseudo-evaluate the given integer expression, estimating the
4149/// range of values it might take.
4150///
4151/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek0692a192012-01-31 05:37:37 +00004152static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004153 E = E->IgnoreParens();
4154
4155 // Try a full evaluation first.
4156 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00004157 if (E->EvaluateAsRValue(result, C))
John McCall0acc3112010-01-06 22:57:21 +00004158 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00004159
4160 // I think we only want to look through implicit casts here; if the
4161 // user has an explicit widening cast, we should treat the value as
4162 // being of the new, wider type.
4163 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedmanb17ee5b2011-12-15 02:41:52 +00004164 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCallf2370c92010-01-06 05:24:50 +00004165 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
4166
John McCall1844a6e2010-11-10 23:38:19 +00004167 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCallf2370c92010-01-06 05:24:50 +00004168
John McCall2de56d12010-08-25 11:45:40 +00004169 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00004170
John McCallf2370c92010-01-06 05:24:50 +00004171 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00004172 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00004173 return OutputTypeRange;
4174
4175 IntRange SubRange
4176 = GetExprRange(C, CE->getSubExpr(),
4177 std::min(MaxWidth, OutputTypeRange.Width));
4178
4179 // Bail out if the subexpr's range is as wide as the cast type.
4180 if (SubRange.Width >= OutputTypeRange.Width)
4181 return OutputTypeRange;
4182
4183 // Otherwise, we take the smaller width, and we're non-negative if
4184 // either the output type or the subexpr is.
4185 return IntRange(SubRange.Width,
4186 SubRange.NonNegative || OutputTypeRange.NonNegative);
4187 }
4188
4189 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4190 // If we can fold the condition, just take that operand.
4191 bool CondResult;
4192 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
4193 return GetExprRange(C, CondResult ? CO->getTrueExpr()
4194 : CO->getFalseExpr(),
4195 MaxWidth);
4196
4197 // Otherwise, conservatively merge.
4198 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
4199 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
4200 return IntRange::join(L, R);
4201 }
4202
4203 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4204 switch (BO->getOpcode()) {
4205
4206 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00004207 case BO_LAnd:
4208 case BO_LOr:
4209 case BO_LT:
4210 case BO_GT:
4211 case BO_LE:
4212 case BO_GE:
4213 case BO_EQ:
4214 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00004215 return IntRange::forBoolType();
4216
John McCall862ff872011-07-13 06:35:24 +00004217 // The type of the assignments is the type of the LHS, so the RHS
4218 // is not necessarily the same type.
John McCall2de56d12010-08-25 11:45:40 +00004219 case BO_MulAssign:
4220 case BO_DivAssign:
4221 case BO_RemAssign:
4222 case BO_AddAssign:
4223 case BO_SubAssign:
John McCall862ff872011-07-13 06:35:24 +00004224 case BO_XorAssign:
4225 case BO_OrAssign:
4226 // TODO: bitfields?
John McCall1844a6e2010-11-10 23:38:19 +00004227 return IntRange::forValueOfType(C, E->getType());
John McCallc0cd21d2010-02-23 19:22:29 +00004228
John McCall862ff872011-07-13 06:35:24 +00004229 // Simple assignments just pass through the RHS, which will have
4230 // been coerced to the LHS type.
4231 case BO_Assign:
4232 // TODO: bitfields?
4233 return GetExprRange(C, BO->getRHS(), MaxWidth);
4234
John McCallf2370c92010-01-06 05:24:50 +00004235 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00004236 case BO_PtrMemD:
4237 case BO_PtrMemI:
John McCall1844a6e2010-11-10 23:38:19 +00004238 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00004239
John McCall60fad452010-01-06 22:07:33 +00004240 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00004241 case BO_And:
4242 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00004243 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
4244 GetExprRange(C, BO->getRHS(), MaxWidth));
4245
John McCallf2370c92010-01-06 05:24:50 +00004246 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00004247 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00004248 // ...except that we want to treat '1 << (blah)' as logically
4249 // positive. It's an important idiom.
4250 if (IntegerLiteral *I
4251 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
4252 if (I->getValue() == 1) {
John McCall1844a6e2010-11-10 23:38:19 +00004253 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall3aae6092010-04-07 01:14:35 +00004254 return IntRange(R.Width, /*NonNegative*/ true);
4255 }
4256 }
4257 // fallthrough
4258
John McCall2de56d12010-08-25 11:45:40 +00004259 case BO_ShlAssign:
John McCall1844a6e2010-11-10 23:38:19 +00004260 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00004261
John McCall60fad452010-01-06 22:07:33 +00004262 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00004263 case BO_Shr:
4264 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00004265 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4266
4267 // If the shift amount is a positive constant, drop the width by
4268 // that much.
4269 llvm::APSInt shift;
4270 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
4271 shift.isNonNegative()) {
4272 unsigned zext = shift.getZExtValue();
4273 if (zext >= L.Width)
4274 L.Width = (L.NonNegative ? 0 : 1);
4275 else
4276 L.Width -= zext;
4277 }
4278
4279 return L;
4280 }
4281
4282 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00004283 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00004284 return GetExprRange(C, BO->getRHS(), MaxWidth);
4285
John McCall60fad452010-01-06 22:07:33 +00004286 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00004287 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00004288 if (BO->getLHS()->getType()->isPointerType())
John McCall1844a6e2010-11-10 23:38:19 +00004289 return IntRange::forValueOfType(C, E->getType());
John McCall00fe7612011-07-14 22:39:48 +00004290 break;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00004291
John McCall00fe7612011-07-14 22:39:48 +00004292 // The width of a division result is mostly determined by the size
4293 // of the LHS.
4294 case BO_Div: {
4295 // Don't 'pre-truncate' the operands.
4296 unsigned opWidth = C.getIntWidth(E->getType());
4297 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4298
4299 // If the divisor is constant, use that.
4300 llvm::APSInt divisor;
4301 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
4302 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
4303 if (log2 >= L.Width)
4304 L.Width = (L.NonNegative ? 0 : 1);
4305 else
4306 L.Width = std::min(L.Width - log2, MaxWidth);
4307 return L;
4308 }
4309
4310 // Otherwise, just use the LHS's width.
4311 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4312 return IntRange(L.Width, L.NonNegative && R.NonNegative);
4313 }
4314
4315 // The result of a remainder can't be larger than the result of
4316 // either side.
4317 case BO_Rem: {
4318 // Don't 'pre-truncate' the operands.
4319 unsigned opWidth = C.getIntWidth(E->getType());
4320 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4321 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4322
4323 IntRange meet = IntRange::meet(L, R);
4324 meet.Width = std::min(meet.Width, MaxWidth);
4325 return meet;
4326 }
4327
4328 // The default behavior is okay for these.
4329 case BO_Mul:
4330 case BO_Add:
4331 case BO_Xor:
4332 case BO_Or:
John McCallf2370c92010-01-06 05:24:50 +00004333 break;
4334 }
4335
John McCall00fe7612011-07-14 22:39:48 +00004336 // The default case is to treat the operation as if it were closed
4337 // on the narrowest type that encompasses both operands.
John McCallf2370c92010-01-06 05:24:50 +00004338 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4339 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
4340 return IntRange::join(L, R);
4341 }
4342
4343 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
4344 switch (UO->getOpcode()) {
4345 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00004346 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00004347 return IntRange::forBoolType();
4348
4349 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00004350 case UO_Deref:
4351 case UO_AddrOf: // should be impossible
John McCall1844a6e2010-11-10 23:38:19 +00004352 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00004353
4354 default:
4355 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
4356 }
4357 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004358
4359 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall1844a6e2010-11-10 23:38:19 +00004360 IntRange::forValueOfType(C, E->getType());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004361 }
John McCallf2370c92010-01-06 05:24:50 +00004362
John McCall993f43f2013-05-06 21:39:12 +00004363 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004364 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00004365 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00004366
John McCall1844a6e2010-11-10 23:38:19 +00004367 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00004368}
John McCall51313c32010-01-04 23:31:57 +00004369
Ted Kremenek0692a192012-01-31 05:37:37 +00004370static IntRange GetExprRange(ASTContext &C, Expr *E) {
John McCall323ed742010-05-06 08:58:33 +00004371 return GetExprRange(C, E, C.getIntWidth(E->getType()));
4372}
4373
John McCall51313c32010-01-04 23:31:57 +00004374/// Checks whether the given value, which currently has the given
4375/// source semantics, has the same value when coerced through the
4376/// target semantics.
Ted Kremenek0692a192012-01-31 05:37:37 +00004377static bool IsSameFloatAfterCast(const llvm::APFloat &value,
4378 const llvm::fltSemantics &Src,
4379 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00004380 llvm::APFloat truncated = value;
4381
4382 bool ignored;
4383 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
4384 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
4385
4386 return truncated.bitwiseIsEqual(value);
4387}
4388
4389/// Checks whether the given value, which currently has the given
4390/// source semantics, has the same value when coerced through the
4391/// target semantics.
4392///
4393/// The value might be a vector of floats (or a complex number).
Ted Kremenek0692a192012-01-31 05:37:37 +00004394static bool IsSameFloatAfterCast(const APValue &value,
4395 const llvm::fltSemantics &Src,
4396 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00004397 if (value.isFloat())
4398 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
4399
4400 if (value.isVector()) {
4401 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
4402 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
4403 return false;
4404 return true;
4405 }
4406
4407 assert(value.isComplexFloat());
4408 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
4409 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
4410}
4411
Ted Kremenek0692a192012-01-31 05:37:37 +00004412static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00004413
Ted Kremeneke3b159c2010-09-23 21:43:44 +00004414static bool IsZero(Sema &S, Expr *E) {
4415 // Suppress cases where we are comparing against an enum constant.
4416 if (const DeclRefExpr *DR =
4417 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
4418 if (isa<EnumConstantDecl>(DR->getDecl()))
4419 return false;
4420
4421 // Suppress cases where the '0' value is expanded from a macro.
4422 if (E->getLocStart().isMacroID())
4423 return false;
4424
John McCall323ed742010-05-06 08:58:33 +00004425 llvm::APSInt Value;
4426 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
4427}
4428
John McCall372e1032010-10-06 00:25:24 +00004429static bool HasEnumType(Expr *E) {
4430 // Strip off implicit integral promotions.
4431 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00004432 if (ICE->getCastKind() != CK_IntegralCast &&
4433 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00004434 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00004435 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00004436 }
4437
4438 return E->getType()->isEnumeralType();
4439}
4440
Ted Kremenek0692a192012-01-31 05:37:37 +00004441static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00004442 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00004443 if (E->isValueDependent())
4444 return;
4445
John McCall2de56d12010-08-25 11:45:40 +00004446 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00004447 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004448 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00004449 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004450 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00004451 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004452 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00004453 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004454 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00004455 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004456 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00004457 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004458 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00004459 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004460 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00004461 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4462 }
4463}
4464
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004465static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004466 Expr *Constant, Expr *Other,
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004467 llvm::APSInt Value,
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004468 bool RhsConstant) {
Richard Trieu526e6272012-11-14 22:50:24 +00004469 // 0 values are handled later by CheckTrivialUnsignedComparison().
4470 if (Value == 0)
4471 return;
4472
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004473 BinaryOperatorKind op = E->getOpcode();
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004474 QualType OtherT = Other->getType();
4475 QualType ConstantT = Constant->getType();
Richard Trieu526e6272012-11-14 22:50:24 +00004476 QualType CommonT = E->getLHS()->getType();
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004477 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004478 return;
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004479 assert((OtherT->isIntegerType() && ConstantT->isIntegerType())
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004480 && "comparison with non-integer type");
Richard Trieu526e6272012-11-14 22:50:24 +00004481
4482 bool ConstantSigned = ConstantT->isSignedIntegerType();
Richard Trieu526e6272012-11-14 22:50:24 +00004483 bool CommonSigned = CommonT->isSignedIntegerType();
4484
4485 bool EqualityOnly = false;
4486
4487 // TODO: Investigate using GetExprRange() to get tighter bounds on
4488 // on the bit ranges.
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004489 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
Richard Trieu526e6272012-11-14 22:50:24 +00004490 unsigned OtherWidth = OtherRange.Width;
4491
4492 if (CommonSigned) {
4493 // The common type is signed, therefore no signed to unsigned conversion.
Eli Friedmand87de7b2012-11-30 23:09:29 +00004494 if (!OtherRange.NonNegative) {
Richard Trieu526e6272012-11-14 22:50:24 +00004495 // Check that the constant is representable in type OtherT.
4496 if (ConstantSigned) {
4497 if (OtherWidth >= Value.getMinSignedBits())
4498 return;
4499 } else { // !ConstantSigned
4500 if (OtherWidth >= Value.getActiveBits() + 1)
4501 return;
4502 }
4503 } else { // !OtherSigned
4504 // Check that the constant is representable in type OtherT.
4505 // Negative values are out of range.
4506 if (ConstantSigned) {
4507 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
4508 return;
4509 } else { // !ConstantSigned
4510 if (OtherWidth >= Value.getActiveBits())
4511 return;
4512 }
4513 }
4514 } else { // !CommonSigned
Eli Friedmand87de7b2012-11-30 23:09:29 +00004515 if (OtherRange.NonNegative) {
Richard Trieu526e6272012-11-14 22:50:24 +00004516 if (OtherWidth >= Value.getActiveBits())
4517 return;
Eli Friedmand87de7b2012-11-30 23:09:29 +00004518 } else if (!OtherRange.NonNegative && !ConstantSigned) {
Richard Trieu526e6272012-11-14 22:50:24 +00004519 // Check to see if the constant is representable in OtherT.
4520 if (OtherWidth > Value.getActiveBits())
4521 return;
4522 // Check to see if the constant is equivalent to a negative value
4523 // cast to CommonT.
4524 if (S.Context.getIntWidth(ConstantT) == S.Context.getIntWidth(CommonT) &&
Richard Trieu5d1cf4f2012-11-15 03:43:50 +00004525 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
Richard Trieu526e6272012-11-14 22:50:24 +00004526 return;
4527 // The constant value rests between values that OtherT can represent after
4528 // conversion. Relational comparison still works, but equality
4529 // comparisons will be tautological.
4530 EqualityOnly = true;
4531 } else { // OtherSigned && ConstantSigned
4532 assert(0 && "Two signed types converted to unsigned types.");
4533 }
4534 }
4535
4536 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
4537
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004538 bool IsTrue = true;
Richard Trieu526e6272012-11-14 22:50:24 +00004539 if (op == BO_EQ || op == BO_NE) {
4540 IsTrue = op == BO_NE;
4541 } else if (EqualityOnly) {
4542 return;
4543 } else if (RhsConstant) {
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004544 if (op == BO_GT || op == BO_GE)
Richard Trieu526e6272012-11-14 22:50:24 +00004545 IsTrue = !PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004546 else // op == BO_LT || op == BO_LE
Richard Trieu526e6272012-11-14 22:50:24 +00004547 IsTrue = PositiveConstant;
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004548 } else {
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004549 if (op == BO_LT || op == BO_LE)
Richard Trieu526e6272012-11-14 22:50:24 +00004550 IsTrue = !PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004551 else // op == BO_GT || op == BO_GE
Richard Trieu526e6272012-11-14 22:50:24 +00004552 IsTrue = PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004553 }
Ted Kremenek7adf3a92013-03-15 21:50:10 +00004554
4555 // If this is a comparison to an enum constant, include that
4556 // constant in the diagnostic.
4557 const EnumConstantDecl *ED = 0;
4558 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
4559 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
4560
4561 SmallString<64> PrettySourceValue;
4562 llvm::raw_svector_ostream OS(PrettySourceValue);
4563 if (ED)
Ted Kremenek9de50942013-03-15 22:02:46 +00004564 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenek7adf3a92013-03-15 21:50:10 +00004565 else
4566 OS << Value;
4567
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004568 S.Diag(E->getOperatorLoc(), diag::warn_out_of_range_compare)
Ted Kremenek7adf3a92013-03-15 21:50:10 +00004569 << OS.str() << OtherT << IsTrue
Richard Trieu526e6272012-11-14 22:50:24 +00004570 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004571}
4572
John McCall323ed742010-05-06 08:58:33 +00004573/// Analyze the operands of the given comparison. Implements the
4574/// fallback case from AnalyzeComparison.
Ted Kremenek0692a192012-01-31 05:37:37 +00004575static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00004576 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4577 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00004578}
John McCall51313c32010-01-04 23:31:57 +00004579
John McCallba26e582010-01-04 23:21:16 +00004580/// \brief Implements -Wsign-compare.
4581///
Richard Trieudd225092011-09-15 21:56:47 +00004582/// \param E the binary operator to check for warnings
Ted Kremenek0692a192012-01-31 05:37:37 +00004583static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCall323ed742010-05-06 08:58:33 +00004584 // The type the comparison is being performed in.
4585 QualType T = E->getLHS()->getType();
4586 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
4587 && "comparison with mismatched types");
Fariborz Jahanianab4702f2012-09-18 17:46:26 +00004588 if (E->isValueDependent())
4589 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004590
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004591 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
4592 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004593
4594 bool IsComparisonConstant = false;
4595
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004596 // Check whether an integer constant comparison results in a value
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004597 // of 'true' or 'false'.
4598 if (T->isIntegralType(S.Context)) {
4599 llvm::APSInt RHSValue;
4600 bool IsRHSIntegralLiteral =
4601 RHS->isIntegerConstantExpr(RHSValue, S.Context);
4602 llvm::APSInt LHSValue;
4603 bool IsLHSIntegralLiteral =
4604 LHS->isIntegerConstantExpr(LHSValue, S.Context);
4605 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
4606 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
4607 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
4608 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
4609 else
4610 IsComparisonConstant =
4611 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004612 } else if (!T->hasUnsignedIntegerRepresentation())
4613 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004614
John McCall323ed742010-05-06 08:58:33 +00004615 // We don't do anything special if this isn't an unsigned integral
4616 // comparison: we're only interested in integral comparisons, and
4617 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00004618 //
4619 // We also don't care about value-dependent expressions or expressions
4620 // whose result is a constant.
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004621 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCall323ed742010-05-06 08:58:33 +00004622 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004623
John McCall323ed742010-05-06 08:58:33 +00004624 // Check to see if one of the (unmodified) operands is of different
4625 // signedness.
4626 Expr *signedOperand, *unsignedOperand;
Richard Trieudd225092011-09-15 21:56:47 +00004627 if (LHS->getType()->hasSignedIntegerRepresentation()) {
4628 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00004629 "unsigned comparison between two signed integer expressions?");
Richard Trieudd225092011-09-15 21:56:47 +00004630 signedOperand = LHS;
4631 unsignedOperand = RHS;
4632 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
4633 signedOperand = RHS;
4634 unsignedOperand = LHS;
John McCallba26e582010-01-04 23:21:16 +00004635 } else {
John McCall323ed742010-05-06 08:58:33 +00004636 CheckTrivialUnsignedComparison(S, E);
4637 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004638 }
4639
John McCall323ed742010-05-06 08:58:33 +00004640 // Otherwise, calculate the effective range of the signed operand.
4641 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00004642
John McCall323ed742010-05-06 08:58:33 +00004643 // Go ahead and analyze implicit conversions in the operands. Note
4644 // that we skip the implicit conversions on both sides.
Richard Trieudd225092011-09-15 21:56:47 +00004645 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
4646 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00004647
John McCall323ed742010-05-06 08:58:33 +00004648 // If the signed range is non-negative, -Wsign-compare won't fire,
4649 // but we should still check for comparisons which are always true
4650 // or false.
4651 if (signedRange.NonNegative)
4652 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004653
4654 // For (in)equality comparisons, if the unsigned operand is a
4655 // constant which cannot collide with a overflowed signed operand,
4656 // then reinterpreting the signed operand as unsigned will not
4657 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00004658 if (E->isEqualityOp()) {
4659 unsigned comparisonWidth = S.Context.getIntWidth(T);
4660 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00004661
John McCall323ed742010-05-06 08:58:33 +00004662 // We should never be unable to prove that the unsigned operand is
4663 // non-negative.
4664 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
4665
4666 if (unsignedRange.Width < comparisonWidth)
4667 return;
4668 }
4669
Douglas Gregor6d3b93d2012-05-01 01:53:49 +00004670 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
4671 S.PDiag(diag::warn_mixed_sign_comparison)
4672 << LHS->getType() << RHS->getType()
4673 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallba26e582010-01-04 23:21:16 +00004674}
4675
John McCall15d7d122010-11-11 03:21:53 +00004676/// Analyzes an attempt to assign the given value to a bitfield.
4677///
4678/// Returns true if there was something fishy about the attempt.
Ted Kremenek0692a192012-01-31 05:37:37 +00004679static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
4680 SourceLocation InitLoc) {
John McCall15d7d122010-11-11 03:21:53 +00004681 assert(Bitfield->isBitField());
4682 if (Bitfield->isInvalidDecl())
4683 return false;
4684
John McCall91b60142010-11-11 05:33:51 +00004685 // White-list bool bitfields.
4686 if (Bitfield->getType()->isBooleanType())
4687 return false;
4688
Douglas Gregor46ff3032011-02-04 13:09:01 +00004689 // Ignore value- or type-dependent expressions.
4690 if (Bitfield->getBitWidth()->isValueDependent() ||
4691 Bitfield->getBitWidth()->isTypeDependent() ||
4692 Init->isValueDependent() ||
4693 Init->isTypeDependent())
4694 return false;
4695
John McCall15d7d122010-11-11 03:21:53 +00004696 Expr *OriginalInit = Init->IgnoreParenImpCasts();
4697
Richard Smith80d4b552011-12-28 19:48:30 +00004698 llvm::APSInt Value;
4699 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall15d7d122010-11-11 03:21:53 +00004700 return false;
4701
John McCall15d7d122010-11-11 03:21:53 +00004702 unsigned OriginalWidth = Value.getBitWidth();
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004703 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall15d7d122010-11-11 03:21:53 +00004704
4705 if (OriginalWidth <= FieldWidth)
4706 return false;
4707
Eli Friedman3a643af2012-01-26 23:11:39 +00004708 // Compute the value which the bitfield will contain.
Jay Foad9f71a8f2010-12-07 08:25:34 +00004709 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedman3a643af2012-01-26 23:11:39 +00004710 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall15d7d122010-11-11 03:21:53 +00004711
Eli Friedman3a643af2012-01-26 23:11:39 +00004712 // Check whether the stored value is equal to the original value.
4713 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieue1ecdc12012-07-23 20:21:35 +00004714 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall15d7d122010-11-11 03:21:53 +00004715 return false;
4716
Eli Friedman3a643af2012-01-26 23:11:39 +00004717 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedman34ff0622012-02-02 00:40:20 +00004718 // therefore don't strictly fit into a signed bitfield of width 1.
4719 if (FieldWidth == 1 && Value == 1)
Eli Friedman3a643af2012-01-26 23:11:39 +00004720 return false;
4721
John McCall15d7d122010-11-11 03:21:53 +00004722 std::string PrettyValue = Value.toString(10);
4723 std::string PrettyTrunc = TruncatedValue.toString(10);
4724
4725 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
4726 << PrettyValue << PrettyTrunc << OriginalInit->getType()
4727 << Init->getSourceRange();
4728
4729 return true;
4730}
4731
John McCallbeb22aa2010-11-09 23:24:47 +00004732/// Analyze the given simple or compound assignment for warning-worthy
4733/// operations.
Ted Kremenek0692a192012-01-31 05:37:37 +00004734static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCallbeb22aa2010-11-09 23:24:47 +00004735 // Just recurse on the LHS.
4736 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4737
4738 // We want to recurse on the RHS as normal unless we're assigning to
4739 // a bitfield.
John McCall993f43f2013-05-06 21:39:12 +00004740 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00004741 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall15d7d122010-11-11 03:21:53 +00004742 E->getOperatorLoc())) {
4743 // Recurse, ignoring any implicit conversions on the RHS.
4744 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
4745 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00004746 }
4747 }
4748
4749 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
4750}
4751
John McCall51313c32010-01-04 23:31:57 +00004752/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00004753static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00004754 SourceLocation CContext, unsigned diag,
4755 bool pruneControlFlow = false) {
4756 if (pruneControlFlow) {
4757 S.DiagRuntimeBehavior(E->getExprLoc(), E,
4758 S.PDiag(diag)
4759 << SourceType << T << E->getSourceRange()
4760 << SourceRange(CContext));
4761 return;
4762 }
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004763 S.Diag(E->getExprLoc(), diag)
4764 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
4765}
4766
Chandler Carruthe1b02e02011-04-05 06:47:57 +00004767/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00004768static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00004769 SourceLocation CContext, unsigned diag,
4770 bool pruneControlFlow = false) {
4771 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruthe1b02e02011-04-05 06:47:57 +00004772}
4773
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004774/// Diagnose an implicit cast from a literal expression. Does not warn when the
4775/// cast wouldn't lose information.
Chandler Carruthf65076e2011-04-10 08:36:24 +00004776void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
4777 SourceLocation CContext) {
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004778 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruthf65076e2011-04-10 08:36:24 +00004779 bool isExact = false;
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004780 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00004781 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
4782 T->hasUnsignedIntegerRepresentation());
4783 if (Value.convertToInteger(IntegerValue,
Chandler Carruthf65076e2011-04-10 08:36:24 +00004784 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004785 == llvm::APFloat::opOK && isExact)
Chandler Carruthf65076e2011-04-10 08:36:24 +00004786 return;
4787
David Blaikiebe0ee872012-05-15 16:56:36 +00004788 SmallString<16> PrettySourceValue;
4789 Value.toString(PrettySourceValue);
David Blaikiede7e7b82012-05-15 17:18:27 +00004790 SmallString<16> PrettyTargetValue;
David Blaikiebe0ee872012-05-15 16:56:36 +00004791 if (T->isSpecificBuiltinType(BuiltinType::Bool))
4792 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
4793 else
David Blaikiede7e7b82012-05-15 17:18:27 +00004794 IntegerValue.toString(PrettyTargetValue);
David Blaikiebe0ee872012-05-15 16:56:36 +00004795
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004796 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikiebe0ee872012-05-15 16:56:36 +00004797 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
4798 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruthf65076e2011-04-10 08:36:24 +00004799}
4800
John McCall091f23f2010-11-09 22:22:12 +00004801std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
4802 if (!Range.Width) return "0";
4803
4804 llvm::APSInt ValueInRange = Value;
4805 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00004806 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00004807 return ValueInRange.toString(10);
4808}
4809
Hans Wennborg88617a22012-08-28 15:44:30 +00004810static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
4811 if (!isa<ImplicitCastExpr>(Ex))
4812 return false;
4813
4814 Expr *InnerE = Ex->IgnoreParenImpCasts();
4815 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
4816 const Type *Source =
4817 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
4818 if (Target->isDependentType())
4819 return false;
4820
4821 const BuiltinType *FloatCandidateBT =
4822 dyn_cast<BuiltinType>(ToBool ? Source : Target);
4823 const Type *BoolCandidateType = ToBool ? Target : Source;
4824
4825 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
4826 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
4827}
4828
4829void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
4830 SourceLocation CC) {
4831 unsigned NumArgs = TheCall->getNumArgs();
4832 for (unsigned i = 0; i < NumArgs; ++i) {
4833 Expr *CurrA = TheCall->getArg(i);
4834 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
4835 continue;
4836
4837 bool IsSwapped = ((i > 0) &&
4838 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
4839 IsSwapped |= ((i < (NumArgs - 1)) &&
4840 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
4841 if (IsSwapped) {
4842 // Warn on this floating-point to bool conversion.
4843 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
4844 CurrA->getType(), CC,
4845 diag::warn_impcast_floating_point_to_bool);
4846 }
4847 }
4848}
4849
John McCall323ed742010-05-06 08:58:33 +00004850void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00004851 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00004852 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00004853
John McCall323ed742010-05-06 08:58:33 +00004854 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
4855 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
4856 if (Source == Target) return;
4857 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00004858
Chandler Carruth108f7562011-07-26 05:40:03 +00004859 // If the conversion context location is invalid don't complain. We also
4860 // don't want to emit a warning if the issue occurs from the expansion of
4861 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
4862 // delay this check as long as possible. Once we detect we are in that
4863 // scenario, we just return.
Ted Kremenekef9ff882011-03-10 20:03:42 +00004864 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00004865 return;
4866
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004867 // Diagnose implicit casts to bool.
4868 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
4869 if (isa<StringLiteral>(E))
4870 // Warn on string literal to bool. Checks for string literals in logical
4871 // expressions, for instances, assert(0 && "error here"), is prevented
4872 // by a check in AnalyzeImplicitConversions().
4873 return DiagnoseImpCast(S, E, T, CC,
4874 diag::warn_impcast_string_literal_to_bool);
Lang Hamese14ca9f2011-12-05 20:49:50 +00004875 if (Source->isFunctionType()) {
4876 // Warn on function to bool. Checks free functions and static member
4877 // functions. Weakly imported functions are excluded from the check,
4878 // since it's common to test their value to check whether the linker
4879 // found a definition for them.
4880 ValueDecl *D = 0;
4881 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
4882 D = R->getDecl();
4883 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
4884 D = M->getMemberDecl();
4885 }
4886
4887 if (D && !D->isWeak()) {
Richard Trieu26b45d82011-12-06 04:48:01 +00004888 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
4889 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
4890 << F << E->getSourceRange() << SourceRange(CC);
David Blaikie2def7732011-12-09 21:42:37 +00004891 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
4892 << FixItHint::CreateInsertion(E->getExprLoc(), "&");
4893 QualType ReturnType;
4894 UnresolvedSet<4> NonTemplateOverloads;
David Blaikiec8fa5252013-06-21 23:54:45 +00004895 S.tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
David Blaikie2def7732011-12-09 21:42:37 +00004896 if (!ReturnType.isNull()
4897 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
4898 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
4899 << FixItHint::CreateInsertion(
4900 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu26b45d82011-12-06 04:48:01 +00004901 return;
4902 }
Lang Hamese14ca9f2011-12-05 20:49:50 +00004903 }
4904 }
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004905 }
John McCall51313c32010-01-04 23:31:57 +00004906
4907 // Strip vector types.
4908 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004909 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004910 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004911 return;
John McCallb4eb64d2010-10-08 02:01:28 +00004912 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004913 }
Chris Lattnerb792b302011-06-14 04:51:15 +00004914
4915 // If the vector cast is cast between two vectors of the same size, it is
4916 // a bitcast, not a conversion.
4917 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
4918 return;
John McCall51313c32010-01-04 23:31:57 +00004919
4920 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
4921 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
4922 }
4923
4924 // Strip complex types.
4925 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004926 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004927 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004928 return;
4929
John McCallb4eb64d2010-10-08 02:01:28 +00004930 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004931 }
John McCall51313c32010-01-04 23:31:57 +00004932
4933 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
4934 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
4935 }
4936
4937 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
4938 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
4939
4940 // If the source is floating point...
4941 if (SourceBT && SourceBT->isFloatingPoint()) {
4942 // ...and the target is floating point...
4943 if (TargetBT && TargetBT->isFloatingPoint()) {
4944 // ...then warn if we're dropping FP rank.
4945
4946 // Builtin FP kinds are ordered by increasing FP rank.
4947 if (SourceBT->getKind() > TargetBT->getKind()) {
4948 // Don't warn about float constants that are precisely
4949 // representable in the target type.
4950 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00004951 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00004952 // Value might be a float, a float vector, or a float complex.
4953 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00004954 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
4955 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00004956 return;
4957 }
4958
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004959 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004960 return;
4961
John McCallb4eb64d2010-10-08 02:01:28 +00004962 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00004963 }
4964 return;
4965 }
4966
Ted Kremenekef9ff882011-03-10 20:03:42 +00004967 // If the target is integral, always warn.
David Blaikiebe0ee872012-05-15 16:56:36 +00004968 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004969 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004970 return;
4971
Chandler Carrutha5b93322011-02-17 11:05:49 +00004972 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay634c8af2011-09-08 22:30:47 +00004973 // We also want to warn on, e.g., "int i = -1.234"
4974 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
4975 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
4976 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
4977
Chandler Carruthf65076e2011-04-10 08:36:24 +00004978 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
4979 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00004980 } else {
4981 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
4982 }
4983 }
John McCall51313c32010-01-04 23:31:57 +00004984
Hans Wennborg88617a22012-08-28 15:44:30 +00004985 // If the target is bool, warn if expr is a function or method call.
4986 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
4987 isa<CallExpr>(E)) {
4988 // Check last argument of function call to see if it is an
4989 // implicit cast from a type matching the type the result
4990 // is being cast to.
4991 CallExpr *CEx = cast<CallExpr>(E);
4992 unsigned NumArgs = CEx->getNumArgs();
4993 if (NumArgs > 0) {
4994 Expr *LastA = CEx->getArg(NumArgs - 1);
4995 Expr *InnerE = LastA->IgnoreParenImpCasts();
4996 const Type *InnerType =
4997 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
4998 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
4999 // Warn on this floating-point to bool conversion
5000 DiagnoseImpCast(S, E, T, CC,
5001 diag::warn_impcast_floating_point_to_bool);
5002 }
5003 }
5004 }
John McCall51313c32010-01-04 23:31:57 +00005005 return;
5006 }
5007
Richard Trieu1838ca52011-05-29 19:59:02 +00005008 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
David Blaikieb26331b2012-06-19 21:19:06 +00005009 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
David Blaikiee81b43b2012-11-08 00:41:20 +00005010 && !Target->isBlockPointerType() && !Target->isMemberPointerType()
David Blaikie896c7dd2013-02-16 00:56:22 +00005011 && Target->isScalarType() && !Target->isNullPtrType()) {
David Blaikieb1360492012-03-16 20:30:12 +00005012 SourceLocation Loc = E->getSourceRange().getBegin();
5013 if (Loc.isMacroID())
5014 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
David Blaikie9fb1ac52012-05-15 21:57:38 +00005015 if (!Loc.isMacroID() || CC.isMacroID())
5016 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
5017 << T << clang::SourceRange(CC)
5018 << FixItHint::CreateReplacement(Loc, S.getFixItZeroLiteralForType(T));
Richard Trieu1838ca52011-05-29 19:59:02 +00005019 }
5020
David Blaikieb26331b2012-06-19 21:19:06 +00005021 if (!Source->isIntegerType() || !Target->isIntegerType())
5022 return;
5023
David Blaikiebe0ee872012-05-15 16:56:36 +00005024 // TODO: remove this early return once the false positives for constant->bool
5025 // in templates, macros, etc, are reduced or removed.
5026 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
5027 return;
5028
John McCall323ed742010-05-06 08:58:33 +00005029 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00005030 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00005031
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005032 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer25ffbef2013-03-28 19:07:11 +00005033 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005034 // TODO: this should happen for bitfield stores, too.
5035 llvm::APSInt Value(32);
5036 if (E->isIntegerConstantExpr(Value, S.Context)) {
5037 if (S.SourceMgr.isInSystemMacro(CC))
5038 return;
5039
John McCall091f23f2010-11-09 22:22:12 +00005040 std::string PrettySourceValue = Value.toString(10);
5041 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005042
Ted Kremenek5e745da2011-10-22 02:37:33 +00005043 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5044 S.PDiag(diag::warn_impcast_integer_precision_constant)
5045 << PrettySourceValue << PrettyTargetValue
5046 << E->getType() << T << E->getSourceRange()
5047 << clang::SourceRange(CC));
John McCall091f23f2010-11-09 22:22:12 +00005048 return;
5049 }
5050
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005051 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
5052 if (S.SourceMgr.isInSystemMacro(CC))
5053 return;
5054
David Blaikie37050842012-04-12 22:40:54 +00005055 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaksc36bedc2012-02-01 19:08:57 +00005056 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
5057 /* pruneControlFlow */ true);
John McCallb4eb64d2010-10-08 02:01:28 +00005058 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00005059 }
5060
5061 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
5062 (!TargetRange.NonNegative && SourceRange.NonNegative &&
5063 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00005064
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005065 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005066 return;
5067
John McCall323ed742010-05-06 08:58:33 +00005068 unsigned DiagID = diag::warn_impcast_integer_sign;
5069
5070 // Traditionally, gcc has warned about this under -Wsign-compare.
5071 // We also want to warn about it in -Wconversion.
5072 // So if -Wconversion is off, use a completely identical diagnostic
5073 // in the sign-compare group.
5074 // The conditional-checking code will
5075 if (ICContext) {
5076 DiagID = diag::warn_impcast_integer_sign_conditional;
5077 *ICContext = true;
5078 }
5079
John McCallb4eb64d2010-10-08 02:01:28 +00005080 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00005081 }
5082
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005083 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005084 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
5085 // type, to give us better diagnostics.
5086 QualType SourceType = E->getType();
David Blaikie4e4d0842012-03-11 07:00:24 +00005087 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005088 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5089 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
5090 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
5091 SourceType = S.Context.getTypeDeclType(Enum);
5092 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
5093 }
5094 }
5095
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005096 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
5097 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall83972f12013-03-09 00:54:27 +00005098 if (SourceEnum->getDecl()->hasNameForLinkage() &&
5099 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00005100 SourceEnum != TargetEnum) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005101 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005102 return;
5103
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005104 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005105 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00005106 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005107
John McCall51313c32010-01-04 23:31:57 +00005108 return;
5109}
5110
David Blaikie9fb1ac52012-05-15 21:57:38 +00005111void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5112 SourceLocation CC, QualType T);
John McCall323ed742010-05-06 08:58:33 +00005113
5114void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00005115 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00005116 E = E->IgnoreParenImpCasts();
5117
5118 if (isa<ConditionalOperator>(E))
David Blaikie9fb1ac52012-05-15 21:57:38 +00005119 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCall323ed742010-05-06 08:58:33 +00005120
John McCallb4eb64d2010-10-08 02:01:28 +00005121 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005122 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00005123 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00005124 return;
5125}
5126
David Blaikie9fb1ac52012-05-15 21:57:38 +00005127void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5128 SourceLocation CC, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00005129 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00005130
5131 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00005132 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
5133 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00005134
5135 // If -Wconversion would have warned about either of the candidates
5136 // for a signedness conversion to the context type...
5137 if (!Suspicious) return;
5138
5139 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00005140 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
5141 CC))
John McCall323ed742010-05-06 08:58:33 +00005142 return;
5143
John McCall323ed742010-05-06 08:58:33 +00005144 // ...then check whether it would have warned about either of the
5145 // candidates for a signedness conversion to the condition type.
Richard Trieu52541612011-07-21 02:46:28 +00005146 if (E->getType() == T) return;
5147
5148 Suspicious = false;
5149 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
5150 E->getType(), CC, &Suspicious);
5151 if (!Suspicious)
5152 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00005153 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00005154}
5155
5156/// AnalyzeImplicitConversions - Find and report any interesting
5157/// implicit conversions in the given expression. There are a couple
5158/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00005159void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00005160 QualType T = OrigE->getType();
5161 Expr *E = OrigE->IgnoreParenImpCasts();
5162
Douglas Gregorf8b6e152011-10-10 17:38:18 +00005163 if (E->isTypeDependent() || E->isValueDependent())
5164 return;
5165
John McCall323ed742010-05-06 08:58:33 +00005166 // For conditional operators, we analyze the arguments as if they
5167 // were being fed directly into the output.
5168 if (isa<ConditionalOperator>(E)) {
5169 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie9fb1ac52012-05-15 21:57:38 +00005170 CheckConditionalOperator(S, CO, CC, T);
John McCall323ed742010-05-06 08:58:33 +00005171 return;
5172 }
5173
Hans Wennborg88617a22012-08-28 15:44:30 +00005174 // Check implicit argument conversions for function calls.
5175 if (CallExpr *Call = dyn_cast<CallExpr>(E))
5176 CheckImplicitArgumentConversions(S, Call, CC);
5177
John McCall323ed742010-05-06 08:58:33 +00005178 // Go ahead and check any implicit conversions we might have skipped.
5179 // The non-canonical typecheck is just an optimization;
5180 // CheckImplicitConversion will filter out dead implicit conversions.
5181 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00005182 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00005183
5184 // Now continue drilling into this expression.
Fariborz Jahanian6f2a9fa2013-05-15 19:03:04 +00005185
5186 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahaniana1bfe1c2013-05-15 22:25:03 +00005187 if (POE->getResultExpr())
5188 E = POE->getResultExpr();
Fariborz Jahanian6f2a9fa2013-05-15 19:03:04 +00005189 }
5190
Fariborz Jahaniana1bfe1c2013-05-15 22:25:03 +00005191 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5192 return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
5193
John McCall323ed742010-05-06 08:58:33 +00005194 // Skip past explicit casts.
5195 if (isa<ExplicitCastExpr>(E)) {
5196 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00005197 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005198 }
5199
John McCallbeb22aa2010-11-09 23:24:47 +00005200 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5201 // Do a somewhat different check with comparison operators.
5202 if (BO->isComparisonOp())
5203 return AnalyzeComparison(S, BO);
5204
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005205 // And with simple assignments.
5206 if (BO->getOpcode() == BO_Assign)
John McCallbeb22aa2010-11-09 23:24:47 +00005207 return AnalyzeAssignment(S, BO);
5208 }
John McCall323ed742010-05-06 08:58:33 +00005209
5210 // These break the otherwise-useful invariant below. Fortunately,
5211 // we don't really need to recurse into them, because any internal
5212 // expressions should have been analyzed already when they were
5213 // built into statements.
5214 if (isa<StmtExpr>(E)) return;
5215
5216 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005217 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00005218
5219 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00005220 CC = E->getExprLoc();
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005221 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
5222 bool IsLogicalOperator = BO && BO->isLogicalOp();
5223 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor54042f12012-02-09 10:18:50 +00005224 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor503384f2012-02-09 00:47:04 +00005225 if (!ChildExpr)
5226 continue;
5227
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005228 if (IsLogicalOperator &&
5229 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
5230 // Ignore checking string literals that are in logical operators.
5231 continue;
5232 AnalyzeImplicitConversions(S, ChildExpr, CC);
5233 }
John McCall323ed742010-05-06 08:58:33 +00005234}
5235
5236} // end anonymous namespace
5237
5238/// Diagnoses "dangerous" implicit conversions within the given
5239/// expression (which is a full expression). Implements -Wconversion
5240/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00005241///
5242/// \param CC the "context" location of the implicit conversion, i.e.
5243/// the most location of the syntactic entity requiring the implicit
5244/// conversion
5245void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00005246 // Don't diagnose in unevaluated contexts.
David Blaikie71f55f72012-08-06 22:47:24 +00005247 if (isUnevaluatedContext())
John McCall323ed742010-05-06 08:58:33 +00005248 return;
5249
5250 // Don't diagnose for value- or type-dependent expressions.
5251 if (E->isTypeDependent() || E->isValueDependent())
5252 return;
5253
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005254 // Check for array bounds violations in cases where the check isn't triggered
5255 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
5256 // ArraySubscriptExpr is on the RHS of a variable initialization.
5257 CheckArrayAccess(E);
5258
John McCallb4eb64d2010-10-08 02:01:28 +00005259 // This is not the right CC for (e.g.) a variable initialization.
5260 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005261}
5262
Fariborz Jahanianad48a502013-01-24 22:11:45 +00005263/// Diagnose when expression is an integer constant expression and its evaluation
5264/// results in integer overflow
5265void Sema::CheckForIntOverflow (Expr *E) {
Fariborz Jahanian1fd8d462013-03-15 20:47:07 +00005266 if (isa<BinaryOperator>(E->IgnoreParens())) {
Fariborz Jahanianad48a502013-01-24 22:11:45 +00005267 llvm::SmallVector<PartialDiagnosticAt, 4> Diags;
5268 E->EvaluateForOverflow(Context, &Diags);
5269 }
5270}
5271
Richard Smith6c3af3d2013-01-17 01:17:56 +00005272namespace {
5273/// \brief Visitor for expressions which looks for unsequenced operations on the
5274/// same object.
5275class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smith0c0b3902013-06-30 10:40:20 +00005276 typedef EvaluatedExprVisitor<SequenceChecker> Base;
5277
Richard Smith6c3af3d2013-01-17 01:17:56 +00005278 /// \brief A tree of sequenced regions within an expression. Two regions are
5279 /// unsequenced if one is an ancestor or a descendent of the other. When we
5280 /// finish processing an expression with sequencing, such as a comma
5281 /// expression, we fold its tree nodes into its parent, since they are
5282 /// unsequenced with respect to nodes we will visit later.
5283 class SequenceTree {
5284 struct Value {
5285 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
5286 unsigned Parent : 31;
5287 bool Merged : 1;
5288 };
5289 llvm::SmallVector<Value, 8> Values;
5290
5291 public:
5292 /// \brief A region within an expression which may be sequenced with respect
5293 /// to some other region.
5294 class Seq {
5295 explicit Seq(unsigned N) : Index(N) {}
5296 unsigned Index;
5297 friend class SequenceTree;
5298 public:
5299 Seq() : Index(0) {}
5300 };
5301
5302 SequenceTree() { Values.push_back(Value(0)); }
5303 Seq root() const { return Seq(0); }
5304
5305 /// \brief Create a new sequence of operations, which is an unsequenced
5306 /// subset of \p Parent. This sequence of operations is sequenced with
5307 /// respect to other children of \p Parent.
5308 Seq allocate(Seq Parent) {
5309 Values.push_back(Value(Parent.Index));
5310 return Seq(Values.size() - 1);
5311 }
5312
5313 /// \brief Merge a sequence of operations into its parent.
5314 void merge(Seq S) {
5315 Values[S.Index].Merged = true;
5316 }
5317
5318 /// \brief Determine whether two operations are unsequenced. This operation
5319 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
5320 /// should have been merged into its parent as appropriate.
5321 bool isUnsequenced(Seq Cur, Seq Old) {
5322 unsigned C = representative(Cur.Index);
5323 unsigned Target = representative(Old.Index);
5324 while (C >= Target) {
5325 if (C == Target)
5326 return true;
5327 C = Values[C].Parent;
5328 }
5329 return false;
5330 }
5331
5332 private:
5333 /// \brief Pick a representative for a sequence.
5334 unsigned representative(unsigned K) {
5335 if (Values[K].Merged)
5336 // Perform path compression as we go.
5337 return Values[K].Parent = representative(Values[K].Parent);
5338 return K;
5339 }
5340 };
5341
5342 /// An object for which we can track unsequenced uses.
5343 typedef NamedDecl *Object;
5344
5345 /// Different flavors of object usage which we track. We only track the
5346 /// least-sequenced usage of each kind.
5347 enum UsageKind {
5348 /// A read of an object. Multiple unsequenced reads are OK.
5349 UK_Use,
5350 /// A modification of an object which is sequenced before the value
Richard Smith418dd3e2013-06-26 23:16:51 +00005351 /// computation of the expression, such as ++n in C++.
Richard Smith6c3af3d2013-01-17 01:17:56 +00005352 UK_ModAsValue,
5353 /// A modification of an object which is not sequenced before the value
5354 /// computation of the expression, such as n++.
5355 UK_ModAsSideEffect,
5356
5357 UK_Count = UK_ModAsSideEffect + 1
5358 };
5359
5360 struct Usage {
5361 Usage() : Use(0), Seq() {}
5362 Expr *Use;
5363 SequenceTree::Seq Seq;
5364 };
5365
5366 struct UsageInfo {
5367 UsageInfo() : Diagnosed(false) {}
5368 Usage Uses[UK_Count];
5369 /// Have we issued a diagnostic for this variable already?
5370 bool Diagnosed;
5371 };
5372 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
5373
5374 Sema &SemaRef;
5375 /// Sequenced regions within the expression.
5376 SequenceTree Tree;
5377 /// Declaration modifications and references which we have seen.
5378 UsageInfoMap UsageMap;
5379 /// The region we are currently within.
5380 SequenceTree::Seq Region;
5381 /// Filled in with declarations which were modified as a side-effect
5382 /// (that is, post-increment operations).
5383 llvm::SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smith1a2dcd52013-01-17 23:18:09 +00005384 /// Expressions to check later. We defer checking these to reduce
5385 /// stack usage.
5386 llvm::SmallVectorImpl<Expr*> &WorkList;
Richard Smith6c3af3d2013-01-17 01:17:56 +00005387
5388 /// RAII object wrapping the visitation of a sequenced subexpression of an
5389 /// expression. At the end of this process, the side-effects of the evaluation
5390 /// become sequenced with respect to the value computation of the result, so
5391 /// we downgrade any UK_ModAsSideEffect within the evaluation to
5392 /// UK_ModAsValue.
5393 struct SequencedSubexpression {
5394 SequencedSubexpression(SequenceChecker &Self)
5395 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
5396 Self.ModAsSideEffect = &ModAsSideEffect;
5397 }
5398 ~SequencedSubexpression() {
5399 for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) {
5400 UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first];
5401 U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second;
5402 Self.addUsage(U, ModAsSideEffect[I].first,
5403 ModAsSideEffect[I].second.Use, UK_ModAsValue);
5404 }
5405 Self.ModAsSideEffect = OldModAsSideEffect;
5406 }
5407
5408 SequenceChecker &Self;
5409 llvm::SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
5410 llvm::SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
5411 };
5412
Richard Smith67470052013-06-20 22:21:56 +00005413 /// RAII object wrapping the visitation of a subexpression which we might
5414 /// choose to evaluate as a constant. If any subexpression is evaluated and
5415 /// found to be non-constant, this allows us to suppress the evaluation of
5416 /// the outer expression.
5417 class EvaluationTracker {
5418 public:
5419 EvaluationTracker(SequenceChecker &Self)
5420 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
5421 Self.EvalTracker = this;
5422 }
5423 ~EvaluationTracker() {
5424 Self.EvalTracker = Prev;
5425 if (Prev)
5426 Prev->EvalOK &= EvalOK;
5427 }
5428
5429 bool evaluate(const Expr *E, bool &Result) {
5430 if (!EvalOK || E->isValueDependent())
5431 return false;
5432 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
5433 return EvalOK;
5434 }
5435
5436 private:
5437 SequenceChecker &Self;
5438 EvaluationTracker *Prev;
5439 bool EvalOK;
5440 } *EvalTracker;
5441
Richard Smith6c3af3d2013-01-17 01:17:56 +00005442 /// \brief Find the object which is produced by the specified expression,
5443 /// if any.
5444 Object getObject(Expr *E, bool Mod) const {
5445 E = E->IgnoreParenCasts();
5446 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5447 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
5448 return getObject(UO->getSubExpr(), Mod);
5449 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5450 if (BO->getOpcode() == BO_Comma)
5451 return getObject(BO->getRHS(), Mod);
5452 if (Mod && BO->isAssignmentOp())
5453 return getObject(BO->getLHS(), Mod);
5454 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
5455 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
5456 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
5457 return ME->getMemberDecl();
5458 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5459 // FIXME: If this is a reference, map through to its value.
5460 return DRE->getDecl();
5461 return 0;
5462 }
5463
5464 /// \brief Note that an object was modified or used by an expression.
5465 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
5466 Usage &U = UI.Uses[UK];
5467 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
5468 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
5469 ModAsSideEffect->push_back(std::make_pair(O, U));
5470 U.Use = Ref;
5471 U.Seq = Region;
5472 }
5473 }
5474 /// \brief Check whether a modification or use conflicts with a prior usage.
5475 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
5476 bool IsModMod) {
5477 if (UI.Diagnosed)
5478 return;
5479
5480 const Usage &U = UI.Uses[OtherKind];
5481 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
5482 return;
5483
5484 Expr *Mod = U.Use;
5485 Expr *ModOrUse = Ref;
5486 if (OtherKind == UK_Use)
5487 std::swap(Mod, ModOrUse);
5488
5489 SemaRef.Diag(Mod->getExprLoc(),
5490 IsModMod ? diag::warn_unsequenced_mod_mod
5491 : diag::warn_unsequenced_mod_use)
5492 << O << SourceRange(ModOrUse->getExprLoc());
5493 UI.Diagnosed = true;
5494 }
5495
5496 void notePreUse(Object O, Expr *Use) {
5497 UsageInfo &U = UsageMap[O];
5498 // Uses conflict with other modifications.
5499 checkUsage(O, U, Use, UK_ModAsValue, false);
5500 }
5501 void notePostUse(Object O, Expr *Use) {
5502 UsageInfo &U = UsageMap[O];
5503 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
5504 addUsage(U, O, Use, UK_Use);
5505 }
5506
5507 void notePreMod(Object O, Expr *Mod) {
5508 UsageInfo &U = UsageMap[O];
5509 // Modifications conflict with other modifications and with uses.
5510 checkUsage(O, U, Mod, UK_ModAsValue, true);
5511 checkUsage(O, U, Mod, UK_Use, false);
5512 }
5513 void notePostMod(Object O, Expr *Use, UsageKind UK) {
5514 UsageInfo &U = UsageMap[O];
5515 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
5516 addUsage(U, O, Use, UK);
5517 }
5518
5519public:
Richard Smith1a2dcd52013-01-17 23:18:09 +00005520 SequenceChecker(Sema &S, Expr *E,
5521 llvm::SmallVectorImpl<Expr*> &WorkList)
Richard Smith0c0b3902013-06-30 10:40:20 +00005522 : Base(S.Context), SemaRef(S), Region(Tree.root()),
5523 ModAsSideEffect(0), WorkList(WorkList), EvalTracker(0) {
Richard Smith6c3af3d2013-01-17 01:17:56 +00005524 Visit(E);
5525 }
5526
5527 void VisitStmt(Stmt *S) {
5528 // Skip all statements which aren't expressions for now.
5529 }
5530
5531 void VisitExpr(Expr *E) {
5532 // By default, just recurse to evaluated subexpressions.
Richard Smith0c0b3902013-06-30 10:40:20 +00005533 Base::VisitStmt(E);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005534 }
5535
5536 void VisitCastExpr(CastExpr *E) {
5537 Object O = Object();
5538 if (E->getCastKind() == CK_LValueToRValue)
5539 O = getObject(E->getSubExpr(), false);
5540
5541 if (O)
5542 notePreUse(O, E);
5543 VisitExpr(E);
5544 if (O)
5545 notePostUse(O, E);
5546 }
5547
5548 void VisitBinComma(BinaryOperator *BO) {
5549 // C++11 [expr.comma]p1:
5550 // Every value computation and side effect associated with the left
5551 // expression is sequenced before every value computation and side
5552 // effect associated with the right expression.
5553 SequenceTree::Seq LHS = Tree.allocate(Region);
5554 SequenceTree::Seq RHS = Tree.allocate(Region);
5555 SequenceTree::Seq OldRegion = Region;
5556
5557 {
5558 SequencedSubexpression SeqLHS(*this);
5559 Region = LHS;
5560 Visit(BO->getLHS());
5561 }
5562
5563 Region = RHS;
5564 Visit(BO->getRHS());
5565
5566 Region = OldRegion;
5567
5568 // Forget that LHS and RHS are sequenced. They are both unsequenced
5569 // with respect to other stuff.
5570 Tree.merge(LHS);
5571 Tree.merge(RHS);
5572 }
5573
5574 void VisitBinAssign(BinaryOperator *BO) {
5575 // The modification is sequenced after the value computation of the LHS
5576 // and RHS, so check it before inspecting the operands and update the
5577 // map afterwards.
5578 Object O = getObject(BO->getLHS(), true);
5579 if (!O)
5580 return VisitExpr(BO);
5581
5582 notePreMod(O, BO);
5583
5584 // C++11 [expr.ass]p7:
5585 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
5586 // only once.
5587 //
5588 // Therefore, for a compound assignment operator, O is considered used
5589 // everywhere except within the evaluation of E1 itself.
5590 if (isa<CompoundAssignOperator>(BO))
5591 notePreUse(O, BO);
5592
5593 Visit(BO->getLHS());
5594
5595 if (isa<CompoundAssignOperator>(BO))
5596 notePostUse(O, BO);
5597
5598 Visit(BO->getRHS());
5599
Richard Smith418dd3e2013-06-26 23:16:51 +00005600 // C++11 [expr.ass]p1:
5601 // the assignment is sequenced [...] before the value computation of the
5602 // assignment expression.
5603 // C11 6.5.16/3 has no such rule.
5604 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
5605 : UK_ModAsSideEffect);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005606 }
5607 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
5608 VisitBinAssign(CAO);
5609 }
5610
5611 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
5612 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
5613 void VisitUnaryPreIncDec(UnaryOperator *UO) {
5614 Object O = getObject(UO->getSubExpr(), true);
5615 if (!O)
5616 return VisitExpr(UO);
5617
5618 notePreMod(O, UO);
5619 Visit(UO->getSubExpr());
Richard Smith418dd3e2013-06-26 23:16:51 +00005620 // C++11 [expr.pre.incr]p1:
5621 // the expression ++x is equivalent to x+=1
5622 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
5623 : UK_ModAsSideEffect);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005624 }
5625
5626 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
5627 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
5628 void VisitUnaryPostIncDec(UnaryOperator *UO) {
5629 Object O = getObject(UO->getSubExpr(), true);
5630 if (!O)
5631 return VisitExpr(UO);
5632
5633 notePreMod(O, UO);
5634 Visit(UO->getSubExpr());
5635 notePostMod(O, UO, UK_ModAsSideEffect);
5636 }
5637
5638 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
5639 void VisitBinLOr(BinaryOperator *BO) {
5640 // The side-effects of the LHS of an '&&' are sequenced before the
5641 // value computation of the RHS, and hence before the value computation
5642 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
5643 // as if they were unconditionally sequenced.
Richard Smith67470052013-06-20 22:21:56 +00005644 EvaluationTracker Eval(*this);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005645 {
5646 SequencedSubexpression Sequenced(*this);
5647 Visit(BO->getLHS());
5648 }
5649
5650 bool Result;
Richard Smith67470052013-06-20 22:21:56 +00005651 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith995e4a72013-01-17 22:06:26 +00005652 if (!Result)
5653 Visit(BO->getRHS());
5654 } else {
5655 // Check for unsequenced operations in the RHS, treating it as an
5656 // entirely separate evaluation.
5657 //
5658 // FIXME: If there are operations in the RHS which are unsequenced
5659 // with respect to operations outside the RHS, and those operations
5660 // are unconditionally evaluated, diagnose them.
Richard Smith1a2dcd52013-01-17 23:18:09 +00005661 WorkList.push_back(BO->getRHS());
Richard Smith995e4a72013-01-17 22:06:26 +00005662 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00005663 }
5664 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith67470052013-06-20 22:21:56 +00005665 EvaluationTracker Eval(*this);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005666 {
5667 SequencedSubexpression Sequenced(*this);
5668 Visit(BO->getLHS());
5669 }
5670
5671 bool Result;
Richard Smith67470052013-06-20 22:21:56 +00005672 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith995e4a72013-01-17 22:06:26 +00005673 if (Result)
5674 Visit(BO->getRHS());
5675 } else {
Richard Smith1a2dcd52013-01-17 23:18:09 +00005676 WorkList.push_back(BO->getRHS());
Richard Smith995e4a72013-01-17 22:06:26 +00005677 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00005678 }
5679
5680 // Only visit the condition, unless we can be sure which subexpression will
5681 // be chosen.
5682 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith67470052013-06-20 22:21:56 +00005683 EvaluationTracker Eval(*this);
Richard Smith418dd3e2013-06-26 23:16:51 +00005684 {
5685 SequencedSubexpression Sequenced(*this);
5686 Visit(CO->getCond());
5687 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00005688
5689 bool Result;
Richard Smith67470052013-06-20 22:21:56 +00005690 if (Eval.evaluate(CO->getCond(), Result))
Richard Smith6c3af3d2013-01-17 01:17:56 +00005691 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith995e4a72013-01-17 22:06:26 +00005692 else {
Richard Smith1a2dcd52013-01-17 23:18:09 +00005693 WorkList.push_back(CO->getTrueExpr());
5694 WorkList.push_back(CO->getFalseExpr());
Richard Smith995e4a72013-01-17 22:06:26 +00005695 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00005696 }
5697
Richard Smith0c0b3902013-06-30 10:40:20 +00005698 void VisitCallExpr(CallExpr *CE) {
5699 // C++11 [intro.execution]p15:
5700 // When calling a function [...], every value computation and side effect
5701 // associated with any argument expression, or with the postfix expression
5702 // designating the called function, is sequenced before execution of every
5703 // expression or statement in the body of the function [and thus before
5704 // the value computation of its result].
5705 SequencedSubexpression Sequenced(*this);
5706 Base::VisitCallExpr(CE);
5707
5708 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
5709 }
5710
Richard Smith6c3af3d2013-01-17 01:17:56 +00005711 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smith0c0b3902013-06-30 10:40:20 +00005712 // This is a call, so all subexpressions are sequenced before the result.
5713 SequencedSubexpression Sequenced(*this);
5714
Richard Smith6c3af3d2013-01-17 01:17:56 +00005715 if (!CCE->isListInitialization())
5716 return VisitExpr(CCE);
5717
5718 // In C++11, list initializations are sequenced.
5719 llvm::SmallVector<SequenceTree::Seq, 32> Elts;
5720 SequenceTree::Seq Parent = Region;
5721 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
5722 E = CCE->arg_end();
5723 I != E; ++I) {
5724 Region = Tree.allocate(Parent);
5725 Elts.push_back(Region);
5726 Visit(*I);
5727 }
5728
5729 // Forget that the initializers are sequenced.
5730 Region = Parent;
5731 for (unsigned I = 0; I < Elts.size(); ++I)
5732 Tree.merge(Elts[I]);
5733 }
5734
5735 void VisitInitListExpr(InitListExpr *ILE) {
5736 if (!SemaRef.getLangOpts().CPlusPlus11)
5737 return VisitExpr(ILE);
5738
5739 // In C++11, list initializations are sequenced.
5740 llvm::SmallVector<SequenceTree::Seq, 32> Elts;
5741 SequenceTree::Seq Parent = Region;
5742 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
5743 Expr *E = ILE->getInit(I);
5744 if (!E) continue;
5745 Region = Tree.allocate(Parent);
5746 Elts.push_back(Region);
5747 Visit(E);
5748 }
5749
5750 // Forget that the initializers are sequenced.
5751 Region = Parent;
5752 for (unsigned I = 0; I < Elts.size(); ++I)
5753 Tree.merge(Elts[I]);
5754 }
5755};
5756}
5757
5758void Sema::CheckUnsequencedOperations(Expr *E) {
Richard Smith1a2dcd52013-01-17 23:18:09 +00005759 llvm::SmallVector<Expr*, 8> WorkList;
5760 WorkList.push_back(E);
5761 while (!WorkList.empty()) {
5762 Expr *Item = WorkList.back();
5763 WorkList.pop_back();
5764 SequenceChecker(*this, Item, WorkList);
5765 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00005766}
5767
Fariborz Jahanianad48a502013-01-24 22:11:45 +00005768void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
5769 bool IsConstexpr) {
Richard Smith6c3af3d2013-01-17 01:17:56 +00005770 CheckImplicitConversions(E, CheckLoc);
5771 CheckUnsequencedOperations(E);
Fariborz Jahanianad48a502013-01-24 22:11:45 +00005772 if (!IsConstexpr && !E->isValueDependent())
5773 CheckForIntOverflow(E);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005774}
5775
John McCall15d7d122010-11-11 03:21:53 +00005776void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
5777 FieldDecl *BitField,
5778 Expr *Init) {
5779 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
5780}
5781
Mike Stumpf8c49212010-01-21 03:59:47 +00005782/// CheckParmsForFunctionDef - Check that the parameters of the given
5783/// function are appropriate for the definition of a function. This
5784/// takes care of any checks that cannot be performed on the
5785/// declaration itself, e.g., that the types of each of the function
5786/// parameters are complete.
Reid Kleckner8c0501c2013-06-24 14:38:26 +00005787bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
5788 ParmVarDecl *const *PEnd,
Douglas Gregor82aa7132010-11-01 18:37:59 +00005789 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00005790 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00005791 for (; P != PEnd; ++P) {
5792 ParmVarDecl *Param = *P;
5793
Mike Stumpf8c49212010-01-21 03:59:47 +00005794 // C99 6.7.5.3p4: the parameters in a parameter type list in a
5795 // function declarator that is part of a function definition of
5796 // that function shall not have incomplete type.
5797 //
5798 // This is also C++ [dcl.fct]p6.
5799 if (!Param->isInvalidDecl() &&
5800 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00005801 diag::err_typecheck_decl_incomplete_type)) {
Mike Stumpf8c49212010-01-21 03:59:47 +00005802 Param->setInvalidDecl();
5803 HasInvalidParm = true;
5804 }
5805
5806 // C99 6.9.1p5: If the declarator includes a parameter type list, the
5807 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00005808 if (CheckParameterNames &&
5809 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00005810 !Param->isImplicit() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00005811 !getLangOpts().CPlusPlus)
Mike Stumpf8c49212010-01-21 03:59:47 +00005812 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00005813
5814 // C99 6.7.5.3p12:
5815 // If the function declarator is not part of a definition of that
5816 // function, parameters may have incomplete type and may use the [*]
5817 // notation in their sequences of declarator specifiers to specify
5818 // variable length array types.
5819 QualType PType = Param->getOriginalType();
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00005820 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigd17e3402010-02-01 05:02:49 +00005821 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitfc093362013-03-01 21:41:22 +00005822 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigd17e3402010-02-01 05:02:49 +00005823 // information is added for it.
5824 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00005825 break;
Sam Weinigd17e3402010-02-01 05:02:49 +00005826 }
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00005827 PType= AT->getElementType();
Sam Weinigd17e3402010-02-01 05:02:49 +00005828 }
Reid Kleckner9b601952013-06-21 12:45:15 +00005829
5830 // MSVC destroys objects passed by value in the callee. Therefore a
5831 // function definition which takes such a parameter must be able to call the
5832 // object's destructor.
5833 if (getLangOpts().CPlusPlus &&
5834 Context.getTargetInfo().getCXXABI().isArgumentDestroyedByCallee()) {
5835 if (const RecordType *RT = Param->getType()->getAs<RecordType>())
5836 FinalizeVarWithDestructor(Param, RT);
5837 }
Mike Stumpf8c49212010-01-21 03:59:47 +00005838 }
5839
5840 return HasInvalidParm;
5841}
John McCallb7f4ffe2010-08-12 21:44:57 +00005842
5843/// CheckCastAlign - Implements -Wcast-align, which warns when a
5844/// pointer cast increases the alignment requirements.
5845void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
5846 // This is actually a lot of work to potentially be doing on every
5847 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00005848 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
5849 TRange.getBegin())
David Blaikied6471f72011-09-25 23:23:43 +00005850 == DiagnosticsEngine::Ignored)
John McCallb7f4ffe2010-08-12 21:44:57 +00005851 return;
5852
5853 // Ignore dependent types.
5854 if (T->isDependentType() || Op->getType()->isDependentType())
5855 return;
5856
5857 // Require that the destination be a pointer type.
5858 const PointerType *DestPtr = T->getAs<PointerType>();
5859 if (!DestPtr) return;
5860
5861 // If the destination has alignment 1, we're done.
5862 QualType DestPointee = DestPtr->getPointeeType();
5863 if (DestPointee->isIncompleteType()) return;
5864 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
5865 if (DestAlign.isOne()) return;
5866
5867 // Require that the source be a pointer type.
5868 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
5869 if (!SrcPtr) return;
5870 QualType SrcPointee = SrcPtr->getPointeeType();
5871
5872 // Whitelist casts from cv void*. We already implicitly
5873 // whitelisted casts to cv void*, since they have alignment 1.
5874 // Also whitelist casts involving incomplete types, which implicitly
5875 // includes 'void'.
5876 if (SrcPointee->isIncompleteType()) return;
5877
5878 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
5879 if (SrcAlign >= DestAlign) return;
5880
5881 Diag(TRange.getBegin(), diag::warn_cast_align)
5882 << Op->getType() << T
5883 << static_cast<unsigned>(SrcAlign.getQuantity())
5884 << static_cast<unsigned>(DestAlign.getQuantity())
5885 << TRange << Op->getSourceRange();
5886}
5887
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005888static const Type* getElementType(const Expr *BaseExpr) {
5889 const Type* EltType = BaseExpr->getType().getTypePtr();
5890 if (EltType->isAnyPointerType())
5891 return EltType->getPointeeType().getTypePtr();
5892 else if (EltType->isArrayType())
5893 return EltType->getBaseElementTypeUnsafe();
5894 return EltType;
5895}
5896
Chandler Carruthc2684342011-08-05 09:10:50 +00005897/// \brief Check whether this array fits the idiom of a size-one tail padded
5898/// array member of a struct.
5899///
5900/// We avoid emitting out-of-bounds access warnings for such arrays as they are
5901/// commonly used to emulate flexible arrays in C89 code.
5902static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
5903 const NamedDecl *ND) {
5904 if (Size != 1 || !ND) return false;
5905
5906 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
5907 if (!FD) return false;
5908
5909 // Don't consider sizes resulting from macro expansions or template argument
5910 // substitution to form C89 tail-padded arrays.
Sean Callanand2cf3482012-05-04 18:22:53 +00005911
5912 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00005913 while (TInfo) {
5914 TypeLoc TL = TInfo->getTypeLoc();
5915 // Look through typedefs.
David Blaikie39e6ab42013-02-18 22:06:02 +00005916 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
5917 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00005918 TInfo = TDL->getTypeSourceInfo();
5919 continue;
5920 }
David Blaikie39e6ab42013-02-18 22:06:02 +00005921 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
5922 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier5e253012013-02-06 00:58:34 +00005923 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
5924 return false;
5925 }
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00005926 break;
Sean Callanand2cf3482012-05-04 18:22:53 +00005927 }
Chandler Carruthc2684342011-08-05 09:10:50 +00005928
5929 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gay381711c2011-11-29 22:43:53 +00005930 if (!RD) return false;
5931 if (RD->isUnion()) return false;
5932 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
5933 if (!CRD->isStandardLayout()) return false;
5934 }
Chandler Carruthc2684342011-08-05 09:10:50 +00005935
Benjamin Kramer22d4fed2011-08-06 03:04:42 +00005936 // See if this is the last field decl in the record.
5937 const Decl *D = FD;
5938 while ((D = D->getNextDeclInContext()))
5939 if (isa<FieldDecl>(D))
5940 return false;
5941 return true;
Chandler Carruthc2684342011-08-05 09:10:50 +00005942}
5943
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005944void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005945 const ArraySubscriptExpr *ASE,
Richard Smith25b009a2011-12-16 19:31:14 +00005946 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman92b670e2012-02-27 21:21:40 +00005947 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005948 if (IndexExpr->isValueDependent())
5949 return;
5950
Matt Beaumont-Gay8ef8f432011-12-12 22:35:02 +00005951 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005952 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00005953 const ConstantArrayType *ArrayTy =
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005954 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00005955 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00005956 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00005957
Chandler Carruth34064582011-02-17 20:55:08 +00005958 llvm::APSInt index;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005959 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00005960 return;
Richard Smith25b009a2011-12-16 19:31:14 +00005961 if (IndexNegated)
5962 index = -index;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00005963
Chandler Carruthba447122011-08-05 08:07:29 +00005964 const NamedDecl *ND = NULL;
Chandler Carruthba447122011-08-05 08:07:29 +00005965 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
5966 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruthc2684342011-08-05 09:10:50 +00005967 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruthba447122011-08-05 08:07:29 +00005968 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruthba447122011-08-05 08:07:29 +00005969
Ted Kremenek9e060ca2011-02-23 23:06:04 +00005970 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00005971 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00005972 if (!size.isStrictlyPositive())
5973 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005974
5975 const Type* BaseType = getElementType(BaseExpr);
Nico Weberde5998f2011-09-17 22:59:41 +00005976 if (BaseType != EffectiveType) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005977 // Make sure we're comparing apples to apples when comparing index to size
5978 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
5979 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhraind10f4bc2011-08-10 19:47:25 +00005980 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhrain18f16972011-08-10 18:49:28 +00005981 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005982 if (ptrarith_typesize != array_typesize) {
5983 // There's a cast to a different size type involved
5984 uint64_t ratio = array_typesize / ptrarith_typesize;
5985 // TODO: Be smarter about handling cases where array_typesize is not a
5986 // multiple of ptrarith_typesize
5987 if (ptrarith_typesize * ratio == array_typesize)
5988 size *= llvm::APInt(size.getBitWidth(), ratio);
5989 }
5990 }
5991
Chandler Carruth34064582011-02-17 20:55:08 +00005992 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00005993 index = index.zext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00005994 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00005995 size = size.zext(index.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00005996
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005997 // For array subscripting the index must be less than size, but for pointer
5998 // arithmetic also allow the index (offset) to be equal to size since
5999 // computing the next address after the end of the array is legal and
6000 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman92b670e2012-02-27 21:21:40 +00006001 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruthba447122011-08-05 08:07:29 +00006002 return;
6003
6004 // Also don't warn for arrays of size 1 which are members of some
6005 // structure. These are often used to approximate flexible arrays in C89
6006 // code.
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006007 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00006008 return;
Chandler Carruth34064582011-02-17 20:55:08 +00006009
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006010 // Suppress the warning if the subscript expression (as identified by the
6011 // ']' location) and the index expression are both from macro expansions
6012 // within a system header.
6013 if (ASE) {
6014 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
6015 ASE->getRBracketLoc());
6016 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
6017 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
6018 IndexExpr->getLocStart());
6019 if (SourceMgr.isFromSameFile(RBracketLoc, IndexLoc))
6020 return;
6021 }
6022 }
6023
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006024 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006025 if (ASE)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006026 DiagID = diag::warn_array_index_exceeds_bounds;
6027
6028 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6029 PDiag(DiagID) << index.toString(10, true)
6030 << size.toString(10, true)
6031 << (unsigned)size.getLimitedValue(~0U)
6032 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00006033 } else {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006034 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006035 if (!ASE) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006036 DiagID = diag::warn_ptr_arith_precedes_bounds;
6037 if (index.isNegative()) index = -index;
6038 }
6039
6040 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6041 PDiag(DiagID) << index.toString(10, true)
6042 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00006043 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00006044
Matt Beaumont-Gaycfbc5b52011-11-29 19:27:11 +00006045 if (!ND) {
6046 // Try harder to find a NamedDecl to point at in the note.
6047 while (const ArraySubscriptExpr *ASE =
6048 dyn_cast<ArraySubscriptExpr>(BaseExpr))
6049 BaseExpr = ASE->getBase()->IgnoreParenCasts();
6050 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
6051 ND = dyn_cast<NamedDecl>(DRE->getDecl());
6052 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
6053 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
6054 }
6055
Chandler Carruth35001ca2011-02-17 21:10:52 +00006056 if (ND)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006057 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
6058 PDiag(diag::note_array_index_out_of_bounds)
6059 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00006060}
6061
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006062void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006063 int AllowOnePastEnd = 0;
6064 while (expr) {
6065 expr = expr->IgnoreParenImpCasts();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006066 switch (expr->getStmtClass()) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006067 case Stmt::ArraySubscriptExprClass: {
6068 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006069 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006070 AllowOnePastEnd > 0);
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006071 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006072 }
6073 case Stmt::UnaryOperatorClass: {
6074 // Only unwrap the * and & unary operators
6075 const UnaryOperator *UO = cast<UnaryOperator>(expr);
6076 expr = UO->getSubExpr();
6077 switch (UO->getOpcode()) {
6078 case UO_AddrOf:
6079 AllowOnePastEnd++;
6080 break;
6081 case UO_Deref:
6082 AllowOnePastEnd--;
6083 break;
6084 default:
6085 return;
6086 }
6087 break;
6088 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006089 case Stmt::ConditionalOperatorClass: {
6090 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
6091 if (const Expr *lhs = cond->getLHS())
6092 CheckArrayAccess(lhs);
6093 if (const Expr *rhs = cond->getRHS())
6094 CheckArrayAccess(rhs);
6095 return;
6096 }
6097 default:
6098 return;
6099 }
Peter Collingbournef111d932011-04-15 00:35:48 +00006100 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006101}
John McCallf85e1932011-06-15 23:02:42 +00006102
6103//===--- CHECK: Objective-C retain cycles ----------------------------------//
6104
6105namespace {
6106 struct RetainCycleOwner {
6107 RetainCycleOwner() : Variable(0), Indirect(false) {}
6108 VarDecl *Variable;
6109 SourceRange Range;
6110 SourceLocation Loc;
6111 bool Indirect;
6112
6113 void setLocsFrom(Expr *e) {
6114 Loc = e->getExprLoc();
6115 Range = e->getSourceRange();
6116 }
6117 };
6118}
6119
6120/// Consider whether capturing the given variable can possibly lead to
6121/// a retain cycle.
6122static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledruf3477c12012-09-27 10:16:10 +00006123 // In ARC, it's captured strongly iff the variable has __strong
John McCallf85e1932011-06-15 23:02:42 +00006124 // lifetime. In MRR, it's captured strongly if the variable is
6125 // __block and has an appropriate type.
6126 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
6127 return false;
6128
6129 owner.Variable = var;
Jordan Rosee10f4d32012-09-15 02:48:31 +00006130 if (ref)
6131 owner.setLocsFrom(ref);
John McCallf85e1932011-06-15 23:02:42 +00006132 return true;
6133}
6134
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006135static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCallf85e1932011-06-15 23:02:42 +00006136 while (true) {
6137 e = e->IgnoreParens();
6138 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
6139 switch (cast->getCastKind()) {
6140 case CK_BitCast:
6141 case CK_LValueBitCast:
6142 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00006143 case CK_ARCReclaimReturnedObject:
John McCallf85e1932011-06-15 23:02:42 +00006144 e = cast->getSubExpr();
6145 continue;
6146
John McCallf85e1932011-06-15 23:02:42 +00006147 default:
6148 return false;
6149 }
6150 }
6151
6152 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
6153 ObjCIvarDecl *ivar = ref->getDecl();
6154 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
6155 return false;
6156
6157 // Try to find a retain cycle in the base.
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006158 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCallf85e1932011-06-15 23:02:42 +00006159 return false;
6160
6161 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
6162 owner.Indirect = true;
6163 return true;
6164 }
6165
6166 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
6167 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
6168 if (!var) return false;
6169 return considerVariable(var, ref, owner);
6170 }
6171
John McCallf85e1932011-06-15 23:02:42 +00006172 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
6173 if (member->isArrow()) return false;
6174
6175 // Don't count this as an indirect ownership.
6176 e = member->getBase();
6177 continue;
6178 }
6179
John McCall4b9c2d22011-11-06 09:01:30 +00006180 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
6181 // Only pay attention to pseudo-objects on property references.
6182 ObjCPropertyRefExpr *pre
6183 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
6184 ->IgnoreParens());
6185 if (!pre) return false;
6186 if (pre->isImplicitProperty()) return false;
6187 ObjCPropertyDecl *property = pre->getExplicitProperty();
6188 if (!property->isRetaining() &&
6189 !(property->getPropertyIvarDecl() &&
6190 property->getPropertyIvarDecl()->getType()
6191 .getObjCLifetime() == Qualifiers::OCL_Strong))
6192 return false;
6193
6194 owner.Indirect = true;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006195 if (pre->isSuperReceiver()) {
6196 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
6197 if (!owner.Variable)
6198 return false;
6199 owner.Loc = pre->getLocation();
6200 owner.Range = pre->getSourceRange();
6201 return true;
6202 }
John McCall4b9c2d22011-11-06 09:01:30 +00006203 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
6204 ->getSourceExpr());
6205 continue;
6206 }
6207
John McCallf85e1932011-06-15 23:02:42 +00006208 // Array ivars?
6209
6210 return false;
6211 }
6212}
6213
6214namespace {
6215 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
6216 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
6217 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
6218 Variable(variable), Capturer(0) {}
6219
6220 VarDecl *Variable;
6221 Expr *Capturer;
6222
6223 void VisitDeclRefExpr(DeclRefExpr *ref) {
6224 if (ref->getDecl() == Variable && !Capturer)
6225 Capturer = ref;
6226 }
6227
John McCallf85e1932011-06-15 23:02:42 +00006228 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
6229 if (Capturer) return;
6230 Visit(ref->getBase());
6231 if (Capturer && ref->isFreeIvar())
6232 Capturer = ref;
6233 }
6234
6235 void VisitBlockExpr(BlockExpr *block) {
6236 // Look inside nested blocks
6237 if (block->getBlockDecl()->capturesVariable(Variable))
6238 Visit(block->getBlockDecl()->getBody());
6239 }
Fariborz Jahanian7e2e4c32012-08-31 20:04:47 +00006240
6241 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
6242 if (Capturer) return;
6243 if (OVE->getSourceExpr())
6244 Visit(OVE->getSourceExpr());
6245 }
John McCallf85e1932011-06-15 23:02:42 +00006246 };
6247}
6248
6249/// Check whether the given argument is a block which captures a
6250/// variable.
6251static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
6252 assert(owner.Variable && owner.Loc.isValid());
6253
6254 e = e->IgnoreParenCasts();
Jordan Rose1fac58a2012-09-17 17:54:30 +00006255
6256 // Look through [^{...} copy] and Block_copy(^{...}).
6257 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
6258 Selector Cmd = ME->getSelector();
6259 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
6260 e = ME->getInstanceReceiver();
6261 if (!e)
6262 return 0;
6263 e = e->IgnoreParenCasts();
6264 }
6265 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
6266 if (CE->getNumArgs() == 1) {
6267 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekd13eff62012-10-02 04:36:54 +00006268 if (Fn) {
6269 const IdentifierInfo *FnI = Fn->getIdentifier();
6270 if (FnI && FnI->isStr("_Block_copy")) {
6271 e = CE->getArg(0)->IgnoreParenCasts();
6272 }
6273 }
Jordan Rose1fac58a2012-09-17 17:54:30 +00006274 }
6275 }
6276
John McCallf85e1932011-06-15 23:02:42 +00006277 BlockExpr *block = dyn_cast<BlockExpr>(e);
6278 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
6279 return 0;
6280
6281 FindCaptureVisitor visitor(S.Context, owner.Variable);
6282 visitor.Visit(block->getBlockDecl()->getBody());
6283 return visitor.Capturer;
6284}
6285
6286static void diagnoseRetainCycle(Sema &S, Expr *capturer,
6287 RetainCycleOwner &owner) {
6288 assert(capturer);
6289 assert(owner.Variable && owner.Loc.isValid());
6290
6291 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
6292 << owner.Variable << capturer->getSourceRange();
6293 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
6294 << owner.Indirect << owner.Range;
6295}
6296
6297/// Check for a keyword selector that starts with the word 'add' or
6298/// 'set'.
6299static bool isSetterLikeSelector(Selector sel) {
6300 if (sel.isUnarySelector()) return false;
6301
Chris Lattner5f9e2722011-07-23 10:55:15 +00006302 StringRef str = sel.getNameForSlot(0);
John McCallf85e1932011-06-15 23:02:42 +00006303 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00006304 if (str.startswith("set"))
John McCallf85e1932011-06-15 23:02:42 +00006305 str = str.substr(3);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00006306 else if (str.startswith("add")) {
6307 // Specially whitelist 'addOperationWithBlock:'.
6308 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
6309 return false;
6310 str = str.substr(3);
6311 }
John McCallf85e1932011-06-15 23:02:42 +00006312 else
6313 return false;
6314
6315 if (str.empty()) return true;
Jordan Rose3f6f51e2013-02-08 22:30:41 +00006316 return !isLowercase(str.front());
John McCallf85e1932011-06-15 23:02:42 +00006317}
6318
6319/// Check a message send to see if it's likely to cause a retain cycle.
6320void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
6321 // Only check instance methods whose selector looks like a setter.
6322 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
6323 return;
6324
6325 // Try to find a variable that the receiver is strongly owned by.
6326 RetainCycleOwner owner;
6327 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006328 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCallf85e1932011-06-15 23:02:42 +00006329 return;
6330 } else {
6331 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
6332 owner.Variable = getCurMethodDecl()->getSelfDecl();
6333 owner.Loc = msg->getSuperLoc();
6334 owner.Range = msg->getSuperLoc();
6335 }
6336
6337 // Check whether the receiver is captured by any of the arguments.
6338 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
6339 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
6340 return diagnoseRetainCycle(*this, capturer, owner);
6341}
6342
6343/// Check a property assign to see if it's likely to cause a retain cycle.
6344void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
6345 RetainCycleOwner owner;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006346 if (!findRetainCycleOwner(*this, receiver, owner))
John McCallf85e1932011-06-15 23:02:42 +00006347 return;
6348
6349 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
6350 diagnoseRetainCycle(*this, capturer, owner);
6351}
6352
Jordan Rosee10f4d32012-09-15 02:48:31 +00006353void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
6354 RetainCycleOwner Owner;
6355 if (!considerVariable(Var, /*DeclRefExpr=*/0, Owner))
6356 return;
6357
6358 // Because we don't have an expression for the variable, we have to set the
6359 // location explicitly here.
6360 Owner.Loc = Var->getLocation();
6361 Owner.Range = Var->getSourceRange();
6362
6363 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
6364 diagnoseRetainCycle(*this, Capturer, Owner);
6365}
6366
Ted Kremenek9d084012012-12-21 08:04:28 +00006367static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
6368 Expr *RHS, bool isProperty) {
6369 // Check if RHS is an Objective-C object literal, which also can get
6370 // immediately zapped in a weak reference. Note that we explicitly
6371 // allow ObjCStringLiterals, since those are designed to never really die.
6372 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenekf530ff72012-12-21 21:59:39 +00006373
Ted Kremenekd3292c82012-12-21 22:46:35 +00006374 // This enum needs to match with the 'select' in
6375 // warn_objc_arc_literal_assign (off-by-1).
6376 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
6377 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
6378 return false;
Ted Kremenekf530ff72012-12-21 21:59:39 +00006379
6380 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenekd3292c82012-12-21 22:46:35 +00006381 << (unsigned) Kind
Ted Kremenek9d084012012-12-21 08:04:28 +00006382 << (isProperty ? 0 : 1)
6383 << RHS->getSourceRange();
Ted Kremenekf530ff72012-12-21 21:59:39 +00006384
6385 return true;
Ted Kremenek9d084012012-12-21 08:04:28 +00006386}
6387
Ted Kremenekb29b30f2012-12-21 19:45:30 +00006388static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
6389 Qualifiers::ObjCLifetime LT,
6390 Expr *RHS, bool isProperty) {
6391 // Strip off any implicit cast added to get to the one ARC-specific.
6392 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
6393 if (cast->getCastKind() == CK_ARCConsumeObject) {
6394 S.Diag(Loc, diag::warn_arc_retained_assign)
6395 << (LT == Qualifiers::OCL_ExplicitNone)
6396 << (isProperty ? 0 : 1)
6397 << RHS->getSourceRange();
6398 return true;
6399 }
6400 RHS = cast->getSubExpr();
6401 }
6402
6403 if (LT == Qualifiers::OCL_Weak &&
6404 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
6405 return true;
6406
6407 return false;
6408}
6409
Ted Kremenekb1ea5102012-12-21 08:04:20 +00006410bool Sema::checkUnsafeAssigns(SourceLocation Loc,
6411 QualType LHS, Expr *RHS) {
6412 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
6413
6414 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
6415 return false;
6416
6417 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
6418 return true;
6419
6420 return false;
6421}
6422
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006423void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
6424 Expr *LHS, Expr *RHS) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006425 QualType LHSType;
6426 // PropertyRef on LHS type need be directly obtained from
6427 // its declaration as it has a PsuedoType.
6428 ObjCPropertyRefExpr *PRE
6429 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
6430 if (PRE && !PRE->isImplicitProperty()) {
6431 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
6432 if (PD)
6433 LHSType = PD->getType();
6434 }
6435
6436 if (LHSType.isNull())
6437 LHSType = LHS->getType();
Jordan Rose7a270482012-09-28 22:21:35 +00006438
6439 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
6440
6441 if (LT == Qualifiers::OCL_Weak) {
6442 DiagnosticsEngine::Level Level =
6443 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
6444 if (Level != DiagnosticsEngine::Ignored)
6445 getCurFunction()->markSafeWeakUse(LHS);
6446 }
6447
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006448 if (checkUnsafeAssigns(Loc, LHSType, RHS))
6449 return;
Jordan Rose7a270482012-09-28 22:21:35 +00006450
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006451 // FIXME. Check for other life times.
6452 if (LT != Qualifiers::OCL_None)
6453 return;
6454
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006455 if (PRE) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006456 if (PRE->isImplicitProperty())
6457 return;
6458 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
6459 if (!PD)
6460 return;
6461
Bill Wendlingad017fa2012-12-20 19:22:21 +00006462 unsigned Attributes = PD->getPropertyAttributes();
6463 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006464 // when 'assign' attribute was not explicitly specified
6465 // by user, ignore it and rely on property type itself
6466 // for lifetime info.
6467 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
6468 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
6469 LHSType->isObjCRetainableType())
6470 return;
6471
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006472 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00006473 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006474 Diag(Loc, diag::warn_arc_retained_property_assign)
6475 << RHS->getSourceRange();
6476 return;
6477 }
6478 RHS = cast->getSubExpr();
6479 }
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006480 }
Bill Wendlingad017fa2012-12-20 19:22:21 +00006481 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb1ea5102012-12-21 08:04:20 +00006482 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
6483 return;
Fariborz Jahanianbd2e27e2012-07-06 21:09:27 +00006484 }
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006485 }
6486}
Dmitri Gribenko625bb562012-02-14 22:14:32 +00006487
6488//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
6489
6490namespace {
6491bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
6492 SourceLocation StmtLoc,
6493 const NullStmt *Body) {
6494 // Do not warn if the body is a macro that expands to nothing, e.g:
6495 //
6496 // #define CALL(x)
6497 // if (condition)
6498 // CALL(0);
6499 //
6500 if (Body->hasLeadingEmptyMacro())
6501 return false;
6502
6503 // Get line numbers of statement and body.
6504 bool StmtLineInvalid;
6505 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
6506 &StmtLineInvalid);
6507 if (StmtLineInvalid)
6508 return false;
6509
6510 bool BodyLineInvalid;
6511 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
6512 &BodyLineInvalid);
6513 if (BodyLineInvalid)
6514 return false;
6515
6516 // Warn if null statement and body are on the same line.
6517 if (StmtLine != BodyLine)
6518 return false;
6519
6520 return true;
6521}
6522} // Unnamed namespace
6523
6524void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
6525 const Stmt *Body,
6526 unsigned DiagID) {
6527 // Since this is a syntactic check, don't emit diagnostic for template
6528 // instantiations, this just adds noise.
6529 if (CurrentInstantiationScope)
6530 return;
6531
6532 // The body should be a null statement.
6533 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
6534 if (!NBody)
6535 return;
6536
6537 // Do the usual checks.
6538 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
6539 return;
6540
6541 Diag(NBody->getSemiLoc(), DiagID);
6542 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
6543}
6544
6545void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
6546 const Stmt *PossibleBody) {
6547 assert(!CurrentInstantiationScope); // Ensured by caller
6548
6549 SourceLocation StmtLoc;
6550 const Stmt *Body;
6551 unsigned DiagID;
6552 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
6553 StmtLoc = FS->getRParenLoc();
6554 Body = FS->getBody();
6555 DiagID = diag::warn_empty_for_body;
6556 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
6557 StmtLoc = WS->getCond()->getSourceRange().getEnd();
6558 Body = WS->getBody();
6559 DiagID = diag::warn_empty_while_body;
6560 } else
6561 return; // Neither `for' nor `while'.
6562
6563 // The body should be a null statement.
6564 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
6565 if (!NBody)
6566 return;
6567
6568 // Skip expensive checks if diagnostic is disabled.
6569 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
6570 DiagnosticsEngine::Ignored)
6571 return;
6572
6573 // Do the usual checks.
6574 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
6575 return;
6576
6577 // `for(...);' and `while(...);' are popular idioms, so in order to keep
6578 // noise level low, emit diagnostics only if for/while is followed by a
6579 // CompoundStmt, e.g.:
6580 // for (int i = 0; i < n; i++);
6581 // {
6582 // a(i);
6583 // }
6584 // or if for/while is followed by a statement with more indentation
6585 // than for/while itself:
6586 // for (int i = 0; i < n; i++);
6587 // a(i);
6588 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
6589 if (!ProbableTypo) {
6590 bool BodyColInvalid;
6591 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
6592 PossibleBody->getLocStart(),
6593 &BodyColInvalid);
6594 if (BodyColInvalid)
6595 return;
6596
6597 bool StmtColInvalid;
6598 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
6599 S->getLocStart(),
6600 &StmtColInvalid);
6601 if (StmtColInvalid)
6602 return;
6603
6604 if (BodyCol > StmtCol)
6605 ProbableTypo = true;
6606 }
6607
6608 if (ProbableTypo) {
6609 Diag(NBody->getSemiLoc(), DiagID);
6610 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
6611 }
6612}
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00006613
6614//===--- Layout compatibility ----------------------------------------------//
6615
6616namespace {
6617
6618bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
6619
6620/// \brief Check if two enumeration types are layout-compatible.
6621bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
6622 // C++11 [dcl.enum] p8:
6623 // Two enumeration types are layout-compatible if they have the same
6624 // underlying type.
6625 return ED1->isComplete() && ED2->isComplete() &&
6626 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
6627}
6628
6629/// \brief Check if two fields are layout-compatible.
6630bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
6631 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
6632 return false;
6633
6634 if (Field1->isBitField() != Field2->isBitField())
6635 return false;
6636
6637 if (Field1->isBitField()) {
6638 // Make sure that the bit-fields are the same length.
6639 unsigned Bits1 = Field1->getBitWidthValue(C);
6640 unsigned Bits2 = Field2->getBitWidthValue(C);
6641
6642 if (Bits1 != Bits2)
6643 return false;
6644 }
6645
6646 return true;
6647}
6648
6649/// \brief Check if two standard-layout structs are layout-compatible.
6650/// (C++11 [class.mem] p17)
6651bool isLayoutCompatibleStruct(ASTContext &C,
6652 RecordDecl *RD1,
6653 RecordDecl *RD2) {
6654 // If both records are C++ classes, check that base classes match.
6655 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
6656 // If one of records is a CXXRecordDecl we are in C++ mode,
6657 // thus the other one is a CXXRecordDecl, too.
6658 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
6659 // Check number of base classes.
6660 if (D1CXX->getNumBases() != D2CXX->getNumBases())
6661 return false;
6662
6663 // Check the base classes.
6664 for (CXXRecordDecl::base_class_const_iterator
6665 Base1 = D1CXX->bases_begin(),
6666 BaseEnd1 = D1CXX->bases_end(),
6667 Base2 = D2CXX->bases_begin();
6668 Base1 != BaseEnd1;
6669 ++Base1, ++Base2) {
6670 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
6671 return false;
6672 }
6673 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
6674 // If only RD2 is a C++ class, it should have zero base classes.
6675 if (D2CXX->getNumBases() > 0)
6676 return false;
6677 }
6678
6679 // Check the fields.
6680 RecordDecl::field_iterator Field2 = RD2->field_begin(),
6681 Field2End = RD2->field_end(),
6682 Field1 = RD1->field_begin(),
6683 Field1End = RD1->field_end();
6684 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
6685 if (!isLayoutCompatible(C, *Field1, *Field2))
6686 return false;
6687 }
6688 if (Field1 != Field1End || Field2 != Field2End)
6689 return false;
6690
6691 return true;
6692}
6693
6694/// \brief Check if two standard-layout unions are layout-compatible.
6695/// (C++11 [class.mem] p18)
6696bool isLayoutCompatibleUnion(ASTContext &C,
6697 RecordDecl *RD1,
6698 RecordDecl *RD2) {
6699 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
6700 for (RecordDecl::field_iterator Field2 = RD2->field_begin(),
6701 Field2End = RD2->field_end();
6702 Field2 != Field2End; ++Field2) {
6703 UnmatchedFields.insert(*Field2);
6704 }
6705
6706 for (RecordDecl::field_iterator Field1 = RD1->field_begin(),
6707 Field1End = RD1->field_end();
6708 Field1 != Field1End; ++Field1) {
6709 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
6710 I = UnmatchedFields.begin(),
6711 E = UnmatchedFields.end();
6712
6713 for ( ; I != E; ++I) {
6714 if (isLayoutCompatible(C, *Field1, *I)) {
6715 bool Result = UnmatchedFields.erase(*I);
6716 (void) Result;
6717 assert(Result);
6718 break;
6719 }
6720 }
6721 if (I == E)
6722 return false;
6723 }
6724
6725 return UnmatchedFields.empty();
6726}
6727
6728bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
6729 if (RD1->isUnion() != RD2->isUnion())
6730 return false;
6731
6732 if (RD1->isUnion())
6733 return isLayoutCompatibleUnion(C, RD1, RD2);
6734 else
6735 return isLayoutCompatibleStruct(C, RD1, RD2);
6736}
6737
6738/// \brief Check if two types are layout-compatible in C++11 sense.
6739bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
6740 if (T1.isNull() || T2.isNull())
6741 return false;
6742
6743 // C++11 [basic.types] p11:
6744 // If two types T1 and T2 are the same type, then T1 and T2 are
6745 // layout-compatible types.
6746 if (C.hasSameType(T1, T2))
6747 return true;
6748
6749 T1 = T1.getCanonicalType().getUnqualifiedType();
6750 T2 = T2.getCanonicalType().getUnqualifiedType();
6751
6752 const Type::TypeClass TC1 = T1->getTypeClass();
6753 const Type::TypeClass TC2 = T2->getTypeClass();
6754
6755 if (TC1 != TC2)
6756 return false;
6757
6758 if (TC1 == Type::Enum) {
6759 return isLayoutCompatible(C,
6760 cast<EnumType>(T1)->getDecl(),
6761 cast<EnumType>(T2)->getDecl());
6762 } else if (TC1 == Type::Record) {
6763 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
6764 return false;
6765
6766 return isLayoutCompatible(C,
6767 cast<RecordType>(T1)->getDecl(),
6768 cast<RecordType>(T2)->getDecl());
6769 }
6770
6771 return false;
6772}
6773}
6774
6775//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
6776
6777namespace {
6778/// \brief Given a type tag expression find the type tag itself.
6779///
6780/// \param TypeExpr Type tag expression, as it appears in user's code.
6781///
6782/// \param VD Declaration of an identifier that appears in a type tag.
6783///
6784/// \param MagicValue Type tag magic value.
6785bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
6786 const ValueDecl **VD, uint64_t *MagicValue) {
6787 while(true) {
6788 if (!TypeExpr)
6789 return false;
6790
6791 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
6792
6793 switch (TypeExpr->getStmtClass()) {
6794 case Stmt::UnaryOperatorClass: {
6795 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
6796 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
6797 TypeExpr = UO->getSubExpr();
6798 continue;
6799 }
6800 return false;
6801 }
6802
6803 case Stmt::DeclRefExprClass: {
6804 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
6805 *VD = DRE->getDecl();
6806 return true;
6807 }
6808
6809 case Stmt::IntegerLiteralClass: {
6810 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
6811 llvm::APInt MagicValueAPInt = IL->getValue();
6812 if (MagicValueAPInt.getActiveBits() <= 64) {
6813 *MagicValue = MagicValueAPInt.getZExtValue();
6814 return true;
6815 } else
6816 return false;
6817 }
6818
6819 case Stmt::BinaryConditionalOperatorClass:
6820 case Stmt::ConditionalOperatorClass: {
6821 const AbstractConditionalOperator *ACO =
6822 cast<AbstractConditionalOperator>(TypeExpr);
6823 bool Result;
6824 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
6825 if (Result)
6826 TypeExpr = ACO->getTrueExpr();
6827 else
6828 TypeExpr = ACO->getFalseExpr();
6829 continue;
6830 }
6831 return false;
6832 }
6833
6834 case Stmt::BinaryOperatorClass: {
6835 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
6836 if (BO->getOpcode() == BO_Comma) {
6837 TypeExpr = BO->getRHS();
6838 continue;
6839 }
6840 return false;
6841 }
6842
6843 default:
6844 return false;
6845 }
6846 }
6847}
6848
6849/// \brief Retrieve the C type corresponding to type tag TypeExpr.
6850///
6851/// \param TypeExpr Expression that specifies a type tag.
6852///
6853/// \param MagicValues Registered magic values.
6854///
6855/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
6856/// kind.
6857///
6858/// \param TypeInfo Information about the corresponding C type.
6859///
6860/// \returns true if the corresponding C type was found.
6861bool GetMatchingCType(
6862 const IdentifierInfo *ArgumentKind,
6863 const Expr *TypeExpr, const ASTContext &Ctx,
6864 const llvm::DenseMap<Sema::TypeTagMagicValue,
6865 Sema::TypeTagData> *MagicValues,
6866 bool &FoundWrongKind,
6867 Sema::TypeTagData &TypeInfo) {
6868 FoundWrongKind = false;
6869
6870 // Variable declaration that has type_tag_for_datatype attribute.
6871 const ValueDecl *VD = NULL;
6872
6873 uint64_t MagicValue;
6874
6875 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
6876 return false;
6877
6878 if (VD) {
6879 for (specific_attr_iterator<TypeTagForDatatypeAttr>
6880 I = VD->specific_attr_begin<TypeTagForDatatypeAttr>(),
6881 E = VD->specific_attr_end<TypeTagForDatatypeAttr>();
6882 I != E; ++I) {
6883 if (I->getArgumentKind() != ArgumentKind) {
6884 FoundWrongKind = true;
6885 return false;
6886 }
6887 TypeInfo.Type = I->getMatchingCType();
6888 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
6889 TypeInfo.MustBeNull = I->getMustBeNull();
6890 return true;
6891 }
6892 return false;
6893 }
6894
6895 if (!MagicValues)
6896 return false;
6897
6898 llvm::DenseMap<Sema::TypeTagMagicValue,
6899 Sema::TypeTagData>::const_iterator I =
6900 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
6901 if (I == MagicValues->end())
6902 return false;
6903
6904 TypeInfo = I->second;
6905 return true;
6906}
6907} // unnamed namespace
6908
6909void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
6910 uint64_t MagicValue, QualType Type,
6911 bool LayoutCompatible,
6912 bool MustBeNull) {
6913 if (!TypeTagForDatatypeMagicValues)
6914 TypeTagForDatatypeMagicValues.reset(
6915 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
6916
6917 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
6918 (*TypeTagForDatatypeMagicValues)[Magic] =
6919 TypeTagData(Type, LayoutCompatible, MustBeNull);
6920}
6921
6922namespace {
6923bool IsSameCharType(QualType T1, QualType T2) {
6924 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
6925 if (!BT1)
6926 return false;
6927
6928 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
6929 if (!BT2)
6930 return false;
6931
6932 BuiltinType::Kind T1Kind = BT1->getKind();
6933 BuiltinType::Kind T2Kind = BT2->getKind();
6934
6935 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
6936 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
6937 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
6938 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
6939}
6940} // unnamed namespace
6941
6942void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
6943 const Expr * const *ExprArgs) {
6944 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
6945 bool IsPointerAttr = Attr->getIsPointer();
6946
6947 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
6948 bool FoundWrongKind;
6949 TypeTagData TypeInfo;
6950 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
6951 TypeTagForDatatypeMagicValues.get(),
6952 FoundWrongKind, TypeInfo)) {
6953 if (FoundWrongKind)
6954 Diag(TypeTagExpr->getExprLoc(),
6955 diag::warn_type_tag_for_datatype_wrong_kind)
6956 << TypeTagExpr->getSourceRange();
6957 return;
6958 }
6959
6960 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
6961 if (IsPointerAttr) {
6962 // Skip implicit cast of pointer to `void *' (as a function argument).
6963 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5a249802012-11-03 16:07:49 +00006964 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkob57ce4e2012-11-03 22:10:18 +00006965 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00006966 ArgumentExpr = ICE->getSubExpr();
6967 }
6968 QualType ArgumentType = ArgumentExpr->getType();
6969
6970 // Passing a `void*' pointer shouldn't trigger a warning.
6971 if (IsPointerAttr && ArgumentType->isVoidPointerType())
6972 return;
6973
6974 if (TypeInfo.MustBeNull) {
6975 // Type tag with matching void type requires a null pointer.
6976 if (!ArgumentExpr->isNullPointerConstant(Context,
6977 Expr::NPC_ValueDependentIsNotNull)) {
6978 Diag(ArgumentExpr->getExprLoc(),
6979 diag::warn_type_safety_null_pointer_required)
6980 << ArgumentKind->getName()
6981 << ArgumentExpr->getSourceRange()
6982 << TypeTagExpr->getSourceRange();
6983 }
6984 return;
6985 }
6986
6987 QualType RequiredType = TypeInfo.Type;
6988 if (IsPointerAttr)
6989 RequiredType = Context.getPointerType(RequiredType);
6990
6991 bool mismatch = false;
6992 if (!TypeInfo.LayoutCompatible) {
6993 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
6994
6995 // C++11 [basic.fundamental] p1:
6996 // Plain char, signed char, and unsigned char are three distinct types.
6997 //
6998 // But we treat plain `char' as equivalent to `signed char' or `unsigned
6999 // char' depending on the current char signedness mode.
7000 if (mismatch)
7001 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
7002 RequiredType->getPointeeType())) ||
7003 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
7004 mismatch = false;
7005 } else
7006 if (IsPointerAttr)
7007 mismatch = !isLayoutCompatible(Context,
7008 ArgumentType->getPointeeType(),
7009 RequiredType->getPointeeType());
7010 else
7011 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
7012
7013 if (mismatch)
7014 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
7015 << ArgumentType << ArgumentKind->getName()
7016 << TypeInfo.LayoutCompatible << RequiredType
7017 << ArgumentExpr->getSourceRange()
7018 << TypeTagExpr->getSourceRange();
7019}