blob: e82f918198c5d208499461c1c2140658c7d4c7b8 [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
Eli Friedman09bddcf2013-07-08 20:20:06 +00004148static QualType GetExprType(Expr *E) {
4149 QualType Ty = E->getType();
4150 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
4151 Ty = AtomicRHS->getValueType();
4152 return Ty;
4153}
4154
John McCallf2370c92010-01-06 05:24:50 +00004155/// Pseudo-evaluate the given integer expression, estimating the
4156/// range of values it might take.
4157///
4158/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek0692a192012-01-31 05:37:37 +00004159static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004160 E = E->IgnoreParens();
4161
4162 // Try a full evaluation first.
4163 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00004164 if (E->EvaluateAsRValue(result, C))
Eli Friedman09bddcf2013-07-08 20:20:06 +00004165 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00004166
4167 // I think we only want to look through implicit casts here; if the
4168 // user has an explicit widening cast, we should treat the value as
4169 // being of the new, wider type.
4170 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedmanb17ee5b2011-12-15 02:41:52 +00004171 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCallf2370c92010-01-06 05:24:50 +00004172 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
4173
Eli Friedman09bddcf2013-07-08 20:20:06 +00004174 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCallf2370c92010-01-06 05:24:50 +00004175
John McCall2de56d12010-08-25 11:45:40 +00004176 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00004177
John McCallf2370c92010-01-06 05:24:50 +00004178 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00004179 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00004180 return OutputTypeRange;
4181
4182 IntRange SubRange
4183 = GetExprRange(C, CE->getSubExpr(),
4184 std::min(MaxWidth, OutputTypeRange.Width));
4185
4186 // Bail out if the subexpr's range is as wide as the cast type.
4187 if (SubRange.Width >= OutputTypeRange.Width)
4188 return OutputTypeRange;
4189
4190 // Otherwise, we take the smaller width, and we're non-negative if
4191 // either the output type or the subexpr is.
4192 return IntRange(SubRange.Width,
4193 SubRange.NonNegative || OutputTypeRange.NonNegative);
4194 }
4195
4196 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4197 // If we can fold the condition, just take that operand.
4198 bool CondResult;
4199 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
4200 return GetExprRange(C, CondResult ? CO->getTrueExpr()
4201 : CO->getFalseExpr(),
4202 MaxWidth);
4203
4204 // Otherwise, conservatively merge.
4205 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
4206 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
4207 return IntRange::join(L, R);
4208 }
4209
4210 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4211 switch (BO->getOpcode()) {
4212
4213 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00004214 case BO_LAnd:
4215 case BO_LOr:
4216 case BO_LT:
4217 case BO_GT:
4218 case BO_LE:
4219 case BO_GE:
4220 case BO_EQ:
4221 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00004222 return IntRange::forBoolType();
4223
John McCall862ff872011-07-13 06:35:24 +00004224 // The type of the assignments is the type of the LHS, so the RHS
4225 // is not necessarily the same type.
John McCall2de56d12010-08-25 11:45:40 +00004226 case BO_MulAssign:
4227 case BO_DivAssign:
4228 case BO_RemAssign:
4229 case BO_AddAssign:
4230 case BO_SubAssign:
John McCall862ff872011-07-13 06:35:24 +00004231 case BO_XorAssign:
4232 case BO_OrAssign:
4233 // TODO: bitfields?
Eli Friedman09bddcf2013-07-08 20:20:06 +00004234 return IntRange::forValueOfType(C, GetExprType(E));
John McCallc0cd21d2010-02-23 19:22:29 +00004235
John McCall862ff872011-07-13 06:35:24 +00004236 // Simple assignments just pass through the RHS, which will have
4237 // been coerced to the LHS type.
4238 case BO_Assign:
4239 // TODO: bitfields?
4240 return GetExprRange(C, BO->getRHS(), MaxWidth);
4241
John McCallf2370c92010-01-06 05:24:50 +00004242 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00004243 case BO_PtrMemD:
4244 case BO_PtrMemI:
Eli Friedman09bddcf2013-07-08 20:20:06 +00004245 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00004246
John McCall60fad452010-01-06 22:07:33 +00004247 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00004248 case BO_And:
4249 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00004250 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
4251 GetExprRange(C, BO->getRHS(), MaxWidth));
4252
John McCallf2370c92010-01-06 05:24:50 +00004253 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00004254 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00004255 // ...except that we want to treat '1 << (blah)' as logically
4256 // positive. It's an important idiom.
4257 if (IntegerLiteral *I
4258 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
4259 if (I->getValue() == 1) {
Eli Friedman09bddcf2013-07-08 20:20:06 +00004260 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall3aae6092010-04-07 01:14:35 +00004261 return IntRange(R.Width, /*NonNegative*/ true);
4262 }
4263 }
4264 // fallthrough
4265
John McCall2de56d12010-08-25 11:45:40 +00004266 case BO_ShlAssign:
Eli Friedman09bddcf2013-07-08 20:20:06 +00004267 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00004268
John McCall60fad452010-01-06 22:07:33 +00004269 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00004270 case BO_Shr:
4271 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00004272 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4273
4274 // If the shift amount is a positive constant, drop the width by
4275 // that much.
4276 llvm::APSInt shift;
4277 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
4278 shift.isNonNegative()) {
4279 unsigned zext = shift.getZExtValue();
4280 if (zext >= L.Width)
4281 L.Width = (L.NonNegative ? 0 : 1);
4282 else
4283 L.Width -= zext;
4284 }
4285
4286 return L;
4287 }
4288
4289 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00004290 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00004291 return GetExprRange(C, BO->getRHS(), MaxWidth);
4292
John McCall60fad452010-01-06 22:07:33 +00004293 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00004294 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00004295 if (BO->getLHS()->getType()->isPointerType())
Eli Friedman09bddcf2013-07-08 20:20:06 +00004296 return IntRange::forValueOfType(C, GetExprType(E));
John McCall00fe7612011-07-14 22:39:48 +00004297 break;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00004298
John McCall00fe7612011-07-14 22:39:48 +00004299 // The width of a division result is mostly determined by the size
4300 // of the LHS.
4301 case BO_Div: {
4302 // Don't 'pre-truncate' the operands.
Eli Friedman09bddcf2013-07-08 20:20:06 +00004303 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall00fe7612011-07-14 22:39:48 +00004304 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4305
4306 // If the divisor is constant, use that.
4307 llvm::APSInt divisor;
4308 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
4309 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
4310 if (log2 >= L.Width)
4311 L.Width = (L.NonNegative ? 0 : 1);
4312 else
4313 L.Width = std::min(L.Width - log2, MaxWidth);
4314 return L;
4315 }
4316
4317 // Otherwise, just use the LHS's width.
4318 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4319 return IntRange(L.Width, L.NonNegative && R.NonNegative);
4320 }
4321
4322 // The result of a remainder can't be larger than the result of
4323 // either side.
4324 case BO_Rem: {
4325 // Don't 'pre-truncate' the operands.
Eli Friedman09bddcf2013-07-08 20:20:06 +00004326 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall00fe7612011-07-14 22:39:48 +00004327 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4328 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4329
4330 IntRange meet = IntRange::meet(L, R);
4331 meet.Width = std::min(meet.Width, MaxWidth);
4332 return meet;
4333 }
4334
4335 // The default behavior is okay for these.
4336 case BO_Mul:
4337 case BO_Add:
4338 case BO_Xor:
4339 case BO_Or:
John McCallf2370c92010-01-06 05:24:50 +00004340 break;
4341 }
4342
John McCall00fe7612011-07-14 22:39:48 +00004343 // The default case is to treat the operation as if it were closed
4344 // on the narrowest type that encompasses both operands.
John McCallf2370c92010-01-06 05:24:50 +00004345 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4346 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
4347 return IntRange::join(L, R);
4348 }
4349
4350 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
4351 switch (UO->getOpcode()) {
4352 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00004353 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00004354 return IntRange::forBoolType();
4355
4356 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00004357 case UO_Deref:
4358 case UO_AddrOf: // should be impossible
Eli Friedman09bddcf2013-07-08 20:20:06 +00004359 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00004360
4361 default:
4362 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
4363 }
4364 }
4365
John McCall993f43f2013-05-06 21:39:12 +00004366 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004367 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00004368 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00004369
Eli Friedman09bddcf2013-07-08 20:20:06 +00004370 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00004371}
John McCall51313c32010-01-04 23:31:57 +00004372
Ted Kremenek0692a192012-01-31 05:37:37 +00004373static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedman09bddcf2013-07-08 20:20:06 +00004374 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCall323ed742010-05-06 08:58:33 +00004375}
4376
John McCall51313c32010-01-04 23:31:57 +00004377/// Checks whether the given value, which currently has the given
4378/// source semantics, has the same value when coerced through the
4379/// target semantics.
Ted Kremenek0692a192012-01-31 05:37:37 +00004380static bool IsSameFloatAfterCast(const llvm::APFloat &value,
4381 const llvm::fltSemantics &Src,
4382 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00004383 llvm::APFloat truncated = value;
4384
4385 bool ignored;
4386 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
4387 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
4388
4389 return truncated.bitwiseIsEqual(value);
4390}
4391
4392/// Checks whether the given value, which currently has the given
4393/// source semantics, has the same value when coerced through the
4394/// target semantics.
4395///
4396/// The value might be a vector of floats (or a complex number).
Ted Kremenek0692a192012-01-31 05:37:37 +00004397static bool IsSameFloatAfterCast(const APValue &value,
4398 const llvm::fltSemantics &Src,
4399 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00004400 if (value.isFloat())
4401 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
4402
4403 if (value.isVector()) {
4404 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
4405 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
4406 return false;
4407 return true;
4408 }
4409
4410 assert(value.isComplexFloat());
4411 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
4412 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
4413}
4414
Ted Kremenek0692a192012-01-31 05:37:37 +00004415static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00004416
Ted Kremeneke3b159c2010-09-23 21:43:44 +00004417static bool IsZero(Sema &S, Expr *E) {
4418 // Suppress cases where we are comparing against an enum constant.
4419 if (const DeclRefExpr *DR =
4420 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
4421 if (isa<EnumConstantDecl>(DR->getDecl()))
4422 return false;
4423
4424 // Suppress cases where the '0' value is expanded from a macro.
4425 if (E->getLocStart().isMacroID())
4426 return false;
4427
John McCall323ed742010-05-06 08:58:33 +00004428 llvm::APSInt Value;
4429 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
4430}
4431
John McCall372e1032010-10-06 00:25:24 +00004432static bool HasEnumType(Expr *E) {
4433 // Strip off implicit integral promotions.
4434 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00004435 if (ICE->getCastKind() != CK_IntegralCast &&
4436 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00004437 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00004438 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00004439 }
4440
4441 return E->getType()->isEnumeralType();
4442}
4443
Ted Kremenek0692a192012-01-31 05:37:37 +00004444static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00004445 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00004446 if (E->isValueDependent())
4447 return;
4448
John McCall2de56d12010-08-25 11:45:40 +00004449 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00004450 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004451 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00004452 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004453 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00004454 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004455 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00004456 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004457 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00004458 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004459 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00004460 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004461 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00004462 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004463 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00004464 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4465 }
4466}
4467
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004468static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004469 Expr *Constant, Expr *Other,
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004470 llvm::APSInt Value,
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004471 bool RhsConstant) {
Richard Trieu526e6272012-11-14 22:50:24 +00004472 // 0 values are handled later by CheckTrivialUnsignedComparison().
4473 if (Value == 0)
4474 return;
4475
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004476 BinaryOperatorKind op = E->getOpcode();
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004477 QualType OtherT = Other->getType();
4478 QualType ConstantT = Constant->getType();
Richard Trieu526e6272012-11-14 22:50:24 +00004479 QualType CommonT = E->getLHS()->getType();
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004480 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004481 return;
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004482 assert((OtherT->isIntegerType() && ConstantT->isIntegerType())
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004483 && "comparison with non-integer type");
Richard Trieu526e6272012-11-14 22:50:24 +00004484
4485 bool ConstantSigned = ConstantT->isSignedIntegerType();
Richard Trieu526e6272012-11-14 22:50:24 +00004486 bool CommonSigned = CommonT->isSignedIntegerType();
4487
4488 bool EqualityOnly = false;
4489
4490 // TODO: Investigate using GetExprRange() to get tighter bounds on
4491 // on the bit ranges.
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004492 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
Richard Trieu526e6272012-11-14 22:50:24 +00004493 unsigned OtherWidth = OtherRange.Width;
4494
4495 if (CommonSigned) {
4496 // The common type is signed, therefore no signed to unsigned conversion.
Eli Friedmand87de7b2012-11-30 23:09:29 +00004497 if (!OtherRange.NonNegative) {
Richard Trieu526e6272012-11-14 22:50:24 +00004498 // Check that the constant is representable in type OtherT.
4499 if (ConstantSigned) {
4500 if (OtherWidth >= Value.getMinSignedBits())
4501 return;
4502 } else { // !ConstantSigned
4503 if (OtherWidth >= Value.getActiveBits() + 1)
4504 return;
4505 }
4506 } else { // !OtherSigned
4507 // Check that the constant is representable in type OtherT.
4508 // Negative values are out of range.
4509 if (ConstantSigned) {
4510 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
4511 return;
4512 } else { // !ConstantSigned
4513 if (OtherWidth >= Value.getActiveBits())
4514 return;
4515 }
4516 }
4517 } else { // !CommonSigned
Eli Friedmand87de7b2012-11-30 23:09:29 +00004518 if (OtherRange.NonNegative) {
Richard Trieu526e6272012-11-14 22:50:24 +00004519 if (OtherWidth >= Value.getActiveBits())
4520 return;
Eli Friedmand87de7b2012-11-30 23:09:29 +00004521 } else if (!OtherRange.NonNegative && !ConstantSigned) {
Richard Trieu526e6272012-11-14 22:50:24 +00004522 // Check to see if the constant is representable in OtherT.
4523 if (OtherWidth > Value.getActiveBits())
4524 return;
4525 // Check to see if the constant is equivalent to a negative value
4526 // cast to CommonT.
4527 if (S.Context.getIntWidth(ConstantT) == S.Context.getIntWidth(CommonT) &&
Richard Trieu5d1cf4f2012-11-15 03:43:50 +00004528 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
Richard Trieu526e6272012-11-14 22:50:24 +00004529 return;
4530 // The constant value rests between values that OtherT can represent after
4531 // conversion. Relational comparison still works, but equality
4532 // comparisons will be tautological.
4533 EqualityOnly = true;
4534 } else { // OtherSigned && ConstantSigned
4535 assert(0 && "Two signed types converted to unsigned types.");
4536 }
4537 }
4538
4539 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
4540
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004541 bool IsTrue = true;
Richard Trieu526e6272012-11-14 22:50:24 +00004542 if (op == BO_EQ || op == BO_NE) {
4543 IsTrue = op == BO_NE;
4544 } else if (EqualityOnly) {
4545 return;
4546 } else if (RhsConstant) {
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004547 if (op == BO_GT || op == BO_GE)
Richard Trieu526e6272012-11-14 22:50:24 +00004548 IsTrue = !PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004549 else // op == BO_LT || op == BO_LE
Richard Trieu526e6272012-11-14 22:50:24 +00004550 IsTrue = PositiveConstant;
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004551 } else {
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004552 if (op == BO_LT || op == BO_LE)
Richard Trieu526e6272012-11-14 22:50:24 +00004553 IsTrue = !PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004554 else // op == BO_GT || op == BO_GE
Richard Trieu526e6272012-11-14 22:50:24 +00004555 IsTrue = PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004556 }
Ted Kremenek7adf3a92013-03-15 21:50:10 +00004557
4558 // If this is a comparison to an enum constant, include that
4559 // constant in the diagnostic.
4560 const EnumConstantDecl *ED = 0;
4561 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
4562 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
4563
4564 SmallString<64> PrettySourceValue;
4565 llvm::raw_svector_ostream OS(PrettySourceValue);
4566 if (ED)
Ted Kremenek9de50942013-03-15 22:02:46 +00004567 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenek7adf3a92013-03-15 21:50:10 +00004568 else
4569 OS << Value;
4570
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004571 S.Diag(E->getOperatorLoc(), diag::warn_out_of_range_compare)
Ted Kremenek7adf3a92013-03-15 21:50:10 +00004572 << OS.str() << OtherT << IsTrue
Richard Trieu526e6272012-11-14 22:50:24 +00004573 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004574}
4575
John McCall323ed742010-05-06 08:58:33 +00004576/// Analyze the operands of the given comparison. Implements the
4577/// fallback case from AnalyzeComparison.
Ted Kremenek0692a192012-01-31 05:37:37 +00004578static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00004579 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4580 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00004581}
John McCall51313c32010-01-04 23:31:57 +00004582
John McCallba26e582010-01-04 23:21:16 +00004583/// \brief Implements -Wsign-compare.
4584///
Richard Trieudd225092011-09-15 21:56:47 +00004585/// \param E the binary operator to check for warnings
Ted Kremenek0692a192012-01-31 05:37:37 +00004586static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCall323ed742010-05-06 08:58:33 +00004587 // The type the comparison is being performed in.
4588 QualType T = E->getLHS()->getType();
4589 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
4590 && "comparison with mismatched types");
Fariborz Jahanianab4702f2012-09-18 17:46:26 +00004591 if (E->isValueDependent())
4592 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004593
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004594 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
4595 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004596
4597 bool IsComparisonConstant = false;
4598
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004599 // Check whether an integer constant comparison results in a value
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004600 // of 'true' or 'false'.
4601 if (T->isIntegralType(S.Context)) {
4602 llvm::APSInt RHSValue;
4603 bool IsRHSIntegralLiteral =
4604 RHS->isIntegerConstantExpr(RHSValue, S.Context);
4605 llvm::APSInt LHSValue;
4606 bool IsLHSIntegralLiteral =
4607 LHS->isIntegerConstantExpr(LHSValue, S.Context);
4608 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
4609 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
4610 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
4611 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
4612 else
4613 IsComparisonConstant =
4614 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004615 } else if (!T->hasUnsignedIntegerRepresentation())
4616 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004617
John McCall323ed742010-05-06 08:58:33 +00004618 // We don't do anything special if this isn't an unsigned integral
4619 // comparison: we're only interested in integral comparisons, and
4620 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00004621 //
4622 // We also don't care about value-dependent expressions or expressions
4623 // whose result is a constant.
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004624 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCall323ed742010-05-06 08:58:33 +00004625 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004626
John McCall323ed742010-05-06 08:58:33 +00004627 // Check to see if one of the (unmodified) operands is of different
4628 // signedness.
4629 Expr *signedOperand, *unsignedOperand;
Richard Trieudd225092011-09-15 21:56:47 +00004630 if (LHS->getType()->hasSignedIntegerRepresentation()) {
4631 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00004632 "unsigned comparison between two signed integer expressions?");
Richard Trieudd225092011-09-15 21:56:47 +00004633 signedOperand = LHS;
4634 unsignedOperand = RHS;
4635 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
4636 signedOperand = RHS;
4637 unsignedOperand = LHS;
John McCallba26e582010-01-04 23:21:16 +00004638 } else {
John McCall323ed742010-05-06 08:58:33 +00004639 CheckTrivialUnsignedComparison(S, E);
4640 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004641 }
4642
John McCall323ed742010-05-06 08:58:33 +00004643 // Otherwise, calculate the effective range of the signed operand.
4644 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00004645
John McCall323ed742010-05-06 08:58:33 +00004646 // Go ahead and analyze implicit conversions in the operands. Note
4647 // that we skip the implicit conversions on both sides.
Richard Trieudd225092011-09-15 21:56:47 +00004648 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
4649 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00004650
John McCall323ed742010-05-06 08:58:33 +00004651 // If the signed range is non-negative, -Wsign-compare won't fire,
4652 // but we should still check for comparisons which are always true
4653 // or false.
4654 if (signedRange.NonNegative)
4655 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004656
4657 // For (in)equality comparisons, if the unsigned operand is a
4658 // constant which cannot collide with a overflowed signed operand,
4659 // then reinterpreting the signed operand as unsigned will not
4660 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00004661 if (E->isEqualityOp()) {
4662 unsigned comparisonWidth = S.Context.getIntWidth(T);
4663 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00004664
John McCall323ed742010-05-06 08:58:33 +00004665 // We should never be unable to prove that the unsigned operand is
4666 // non-negative.
4667 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
4668
4669 if (unsignedRange.Width < comparisonWidth)
4670 return;
4671 }
4672
Douglas Gregor6d3b93d2012-05-01 01:53:49 +00004673 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
4674 S.PDiag(diag::warn_mixed_sign_comparison)
4675 << LHS->getType() << RHS->getType()
4676 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallba26e582010-01-04 23:21:16 +00004677}
4678
John McCall15d7d122010-11-11 03:21:53 +00004679/// Analyzes an attempt to assign the given value to a bitfield.
4680///
4681/// Returns true if there was something fishy about the attempt.
Ted Kremenek0692a192012-01-31 05:37:37 +00004682static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
4683 SourceLocation InitLoc) {
John McCall15d7d122010-11-11 03:21:53 +00004684 assert(Bitfield->isBitField());
4685 if (Bitfield->isInvalidDecl())
4686 return false;
4687
John McCall91b60142010-11-11 05:33:51 +00004688 // White-list bool bitfields.
4689 if (Bitfield->getType()->isBooleanType())
4690 return false;
4691
Douglas Gregor46ff3032011-02-04 13:09:01 +00004692 // Ignore value- or type-dependent expressions.
4693 if (Bitfield->getBitWidth()->isValueDependent() ||
4694 Bitfield->getBitWidth()->isTypeDependent() ||
4695 Init->isValueDependent() ||
4696 Init->isTypeDependent())
4697 return false;
4698
John McCall15d7d122010-11-11 03:21:53 +00004699 Expr *OriginalInit = Init->IgnoreParenImpCasts();
4700
Richard Smith80d4b552011-12-28 19:48:30 +00004701 llvm::APSInt Value;
4702 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall15d7d122010-11-11 03:21:53 +00004703 return false;
4704
John McCall15d7d122010-11-11 03:21:53 +00004705 unsigned OriginalWidth = Value.getBitWidth();
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004706 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall15d7d122010-11-11 03:21:53 +00004707
4708 if (OriginalWidth <= FieldWidth)
4709 return false;
4710
Eli Friedman3a643af2012-01-26 23:11:39 +00004711 // Compute the value which the bitfield will contain.
Jay Foad9f71a8f2010-12-07 08:25:34 +00004712 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedman3a643af2012-01-26 23:11:39 +00004713 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall15d7d122010-11-11 03:21:53 +00004714
Eli Friedman3a643af2012-01-26 23:11:39 +00004715 // Check whether the stored value is equal to the original value.
4716 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieue1ecdc12012-07-23 20:21:35 +00004717 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall15d7d122010-11-11 03:21:53 +00004718 return false;
4719
Eli Friedman3a643af2012-01-26 23:11:39 +00004720 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedman34ff0622012-02-02 00:40:20 +00004721 // therefore don't strictly fit into a signed bitfield of width 1.
4722 if (FieldWidth == 1 && Value == 1)
Eli Friedman3a643af2012-01-26 23:11:39 +00004723 return false;
4724
John McCall15d7d122010-11-11 03:21:53 +00004725 std::string PrettyValue = Value.toString(10);
4726 std::string PrettyTrunc = TruncatedValue.toString(10);
4727
4728 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
4729 << PrettyValue << PrettyTrunc << OriginalInit->getType()
4730 << Init->getSourceRange();
4731
4732 return true;
4733}
4734
John McCallbeb22aa2010-11-09 23:24:47 +00004735/// Analyze the given simple or compound assignment for warning-worthy
4736/// operations.
Ted Kremenek0692a192012-01-31 05:37:37 +00004737static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCallbeb22aa2010-11-09 23:24:47 +00004738 // Just recurse on the LHS.
4739 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4740
4741 // We want to recurse on the RHS as normal unless we're assigning to
4742 // a bitfield.
John McCall993f43f2013-05-06 21:39:12 +00004743 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00004744 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall15d7d122010-11-11 03:21:53 +00004745 E->getOperatorLoc())) {
4746 // Recurse, ignoring any implicit conversions on the RHS.
4747 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
4748 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00004749 }
4750 }
4751
4752 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
4753}
4754
John McCall51313c32010-01-04 23:31:57 +00004755/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00004756static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00004757 SourceLocation CContext, unsigned diag,
4758 bool pruneControlFlow = false) {
4759 if (pruneControlFlow) {
4760 S.DiagRuntimeBehavior(E->getExprLoc(), E,
4761 S.PDiag(diag)
4762 << SourceType << T << E->getSourceRange()
4763 << SourceRange(CContext));
4764 return;
4765 }
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004766 S.Diag(E->getExprLoc(), diag)
4767 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
4768}
4769
Chandler Carruthe1b02e02011-04-05 06:47:57 +00004770/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00004771static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00004772 SourceLocation CContext, unsigned diag,
4773 bool pruneControlFlow = false) {
4774 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruthe1b02e02011-04-05 06:47:57 +00004775}
4776
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004777/// Diagnose an implicit cast from a literal expression. Does not warn when the
4778/// cast wouldn't lose information.
Chandler Carruthf65076e2011-04-10 08:36:24 +00004779void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
4780 SourceLocation CContext) {
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004781 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruthf65076e2011-04-10 08:36:24 +00004782 bool isExact = false;
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004783 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00004784 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
4785 T->hasUnsignedIntegerRepresentation());
4786 if (Value.convertToInteger(IntegerValue,
Chandler Carruthf65076e2011-04-10 08:36:24 +00004787 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004788 == llvm::APFloat::opOK && isExact)
Chandler Carruthf65076e2011-04-10 08:36:24 +00004789 return;
4790
David Blaikiebe0ee872012-05-15 16:56:36 +00004791 SmallString<16> PrettySourceValue;
4792 Value.toString(PrettySourceValue);
David Blaikiede7e7b82012-05-15 17:18:27 +00004793 SmallString<16> PrettyTargetValue;
David Blaikiebe0ee872012-05-15 16:56:36 +00004794 if (T->isSpecificBuiltinType(BuiltinType::Bool))
4795 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
4796 else
David Blaikiede7e7b82012-05-15 17:18:27 +00004797 IntegerValue.toString(PrettyTargetValue);
David Blaikiebe0ee872012-05-15 16:56:36 +00004798
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004799 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikiebe0ee872012-05-15 16:56:36 +00004800 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
4801 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruthf65076e2011-04-10 08:36:24 +00004802}
4803
John McCall091f23f2010-11-09 22:22:12 +00004804std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
4805 if (!Range.Width) return "0";
4806
4807 llvm::APSInt ValueInRange = Value;
4808 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00004809 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00004810 return ValueInRange.toString(10);
4811}
4812
Hans Wennborg88617a22012-08-28 15:44:30 +00004813static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
4814 if (!isa<ImplicitCastExpr>(Ex))
4815 return false;
4816
4817 Expr *InnerE = Ex->IgnoreParenImpCasts();
4818 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
4819 const Type *Source =
4820 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
4821 if (Target->isDependentType())
4822 return false;
4823
4824 const BuiltinType *FloatCandidateBT =
4825 dyn_cast<BuiltinType>(ToBool ? Source : Target);
4826 const Type *BoolCandidateType = ToBool ? Target : Source;
4827
4828 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
4829 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
4830}
4831
4832void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
4833 SourceLocation CC) {
4834 unsigned NumArgs = TheCall->getNumArgs();
4835 for (unsigned i = 0; i < NumArgs; ++i) {
4836 Expr *CurrA = TheCall->getArg(i);
4837 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
4838 continue;
4839
4840 bool IsSwapped = ((i > 0) &&
4841 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
4842 IsSwapped |= ((i < (NumArgs - 1)) &&
4843 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
4844 if (IsSwapped) {
4845 // Warn on this floating-point to bool conversion.
4846 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
4847 CurrA->getType(), CC,
4848 diag::warn_impcast_floating_point_to_bool);
4849 }
4850 }
4851}
4852
John McCall323ed742010-05-06 08:58:33 +00004853void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00004854 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00004855 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00004856
John McCall323ed742010-05-06 08:58:33 +00004857 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
4858 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
4859 if (Source == Target) return;
4860 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00004861
Chandler Carruth108f7562011-07-26 05:40:03 +00004862 // If the conversion context location is invalid don't complain. We also
4863 // don't want to emit a warning if the issue occurs from the expansion of
4864 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
4865 // delay this check as long as possible. Once we detect we are in that
4866 // scenario, we just return.
Ted Kremenekef9ff882011-03-10 20:03:42 +00004867 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00004868 return;
4869
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004870 // Diagnose implicit casts to bool.
4871 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
4872 if (isa<StringLiteral>(E))
4873 // Warn on string literal to bool. Checks for string literals in logical
4874 // expressions, for instances, assert(0 && "error here"), is prevented
4875 // by a check in AnalyzeImplicitConversions().
4876 return DiagnoseImpCast(S, E, T, CC,
4877 diag::warn_impcast_string_literal_to_bool);
Lang Hamese14ca9f2011-12-05 20:49:50 +00004878 if (Source->isFunctionType()) {
4879 // Warn on function to bool. Checks free functions and static member
4880 // functions. Weakly imported functions are excluded from the check,
4881 // since it's common to test their value to check whether the linker
4882 // found a definition for them.
4883 ValueDecl *D = 0;
4884 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
4885 D = R->getDecl();
4886 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
4887 D = M->getMemberDecl();
4888 }
4889
4890 if (D && !D->isWeak()) {
Richard Trieu26b45d82011-12-06 04:48:01 +00004891 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
4892 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
4893 << F << E->getSourceRange() << SourceRange(CC);
David Blaikie2def7732011-12-09 21:42:37 +00004894 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
4895 << FixItHint::CreateInsertion(E->getExprLoc(), "&");
4896 QualType ReturnType;
4897 UnresolvedSet<4> NonTemplateOverloads;
David Blaikiec8fa5252013-06-21 23:54:45 +00004898 S.tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
David Blaikie2def7732011-12-09 21:42:37 +00004899 if (!ReturnType.isNull()
4900 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
4901 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
4902 << FixItHint::CreateInsertion(
4903 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu26b45d82011-12-06 04:48:01 +00004904 return;
4905 }
Lang Hamese14ca9f2011-12-05 20:49:50 +00004906 }
4907 }
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004908 }
John McCall51313c32010-01-04 23:31:57 +00004909
4910 // Strip vector types.
4911 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004912 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004913 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004914 return;
John McCallb4eb64d2010-10-08 02:01:28 +00004915 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004916 }
Chris Lattnerb792b302011-06-14 04:51:15 +00004917
4918 // If the vector cast is cast between two vectors of the same size, it is
4919 // a bitcast, not a conversion.
4920 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
4921 return;
John McCall51313c32010-01-04 23:31:57 +00004922
4923 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
4924 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
4925 }
4926
4927 // Strip complex types.
4928 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004929 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004930 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004931 return;
4932
John McCallb4eb64d2010-10-08 02:01:28 +00004933 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004934 }
John McCall51313c32010-01-04 23:31:57 +00004935
4936 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
4937 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
4938 }
4939
4940 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
4941 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
4942
4943 // If the source is floating point...
4944 if (SourceBT && SourceBT->isFloatingPoint()) {
4945 // ...and the target is floating point...
4946 if (TargetBT && TargetBT->isFloatingPoint()) {
4947 // ...then warn if we're dropping FP rank.
4948
4949 // Builtin FP kinds are ordered by increasing FP rank.
4950 if (SourceBT->getKind() > TargetBT->getKind()) {
4951 // Don't warn about float constants that are precisely
4952 // representable in the target type.
4953 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00004954 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00004955 // Value might be a float, a float vector, or a float complex.
4956 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00004957 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
4958 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00004959 return;
4960 }
4961
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004962 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004963 return;
4964
John McCallb4eb64d2010-10-08 02:01:28 +00004965 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00004966 }
4967 return;
4968 }
4969
Ted Kremenekef9ff882011-03-10 20:03:42 +00004970 // If the target is integral, always warn.
David Blaikiebe0ee872012-05-15 16:56:36 +00004971 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004972 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004973 return;
4974
Chandler Carrutha5b93322011-02-17 11:05:49 +00004975 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay634c8af2011-09-08 22:30:47 +00004976 // We also want to warn on, e.g., "int i = -1.234"
4977 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
4978 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
4979 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
4980
Chandler Carruthf65076e2011-04-10 08:36:24 +00004981 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
4982 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00004983 } else {
4984 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
4985 }
4986 }
John McCall51313c32010-01-04 23:31:57 +00004987
Hans Wennborg88617a22012-08-28 15:44:30 +00004988 // If the target is bool, warn if expr is a function or method call.
4989 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
4990 isa<CallExpr>(E)) {
4991 // Check last argument of function call to see if it is an
4992 // implicit cast from a type matching the type the result
4993 // is being cast to.
4994 CallExpr *CEx = cast<CallExpr>(E);
4995 unsigned NumArgs = CEx->getNumArgs();
4996 if (NumArgs > 0) {
4997 Expr *LastA = CEx->getArg(NumArgs - 1);
4998 Expr *InnerE = LastA->IgnoreParenImpCasts();
4999 const Type *InnerType =
5000 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5001 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
5002 // Warn on this floating-point to bool conversion
5003 DiagnoseImpCast(S, E, T, CC,
5004 diag::warn_impcast_floating_point_to_bool);
5005 }
5006 }
5007 }
John McCall51313c32010-01-04 23:31:57 +00005008 return;
5009 }
5010
Richard Trieu1838ca52011-05-29 19:59:02 +00005011 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
David Blaikieb26331b2012-06-19 21:19:06 +00005012 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
David Blaikiee81b43b2012-11-08 00:41:20 +00005013 && !Target->isBlockPointerType() && !Target->isMemberPointerType()
David Blaikie896c7dd2013-02-16 00:56:22 +00005014 && Target->isScalarType() && !Target->isNullPtrType()) {
David Blaikieb1360492012-03-16 20:30:12 +00005015 SourceLocation Loc = E->getSourceRange().getBegin();
5016 if (Loc.isMacroID())
5017 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
David Blaikie9fb1ac52012-05-15 21:57:38 +00005018 if (!Loc.isMacroID() || CC.isMacroID())
5019 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
5020 << T << clang::SourceRange(CC)
5021 << FixItHint::CreateReplacement(Loc, S.getFixItZeroLiteralForType(T));
Richard Trieu1838ca52011-05-29 19:59:02 +00005022 }
5023
David Blaikieb26331b2012-06-19 21:19:06 +00005024 if (!Source->isIntegerType() || !Target->isIntegerType())
5025 return;
5026
David Blaikiebe0ee872012-05-15 16:56:36 +00005027 // TODO: remove this early return once the false positives for constant->bool
5028 // in templates, macros, etc, are reduced or removed.
5029 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
5030 return;
5031
John McCall323ed742010-05-06 08:58:33 +00005032 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00005033 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00005034
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005035 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer25ffbef2013-03-28 19:07:11 +00005036 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005037 // TODO: this should happen for bitfield stores, too.
5038 llvm::APSInt Value(32);
5039 if (E->isIntegerConstantExpr(Value, S.Context)) {
5040 if (S.SourceMgr.isInSystemMacro(CC))
5041 return;
5042
John McCall091f23f2010-11-09 22:22:12 +00005043 std::string PrettySourceValue = Value.toString(10);
5044 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005045
Ted Kremenek5e745da2011-10-22 02:37:33 +00005046 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5047 S.PDiag(diag::warn_impcast_integer_precision_constant)
5048 << PrettySourceValue << PrettyTargetValue
5049 << E->getType() << T << E->getSourceRange()
5050 << clang::SourceRange(CC));
John McCall091f23f2010-11-09 22:22:12 +00005051 return;
5052 }
5053
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005054 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
5055 if (S.SourceMgr.isInSystemMacro(CC))
5056 return;
5057
David Blaikie37050842012-04-12 22:40:54 +00005058 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaksc36bedc2012-02-01 19:08:57 +00005059 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
5060 /* pruneControlFlow */ true);
John McCallb4eb64d2010-10-08 02:01:28 +00005061 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00005062 }
5063
5064 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
5065 (!TargetRange.NonNegative && SourceRange.NonNegative &&
5066 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00005067
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005068 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005069 return;
5070
John McCall323ed742010-05-06 08:58:33 +00005071 unsigned DiagID = diag::warn_impcast_integer_sign;
5072
5073 // Traditionally, gcc has warned about this under -Wsign-compare.
5074 // We also want to warn about it in -Wconversion.
5075 // So if -Wconversion is off, use a completely identical diagnostic
5076 // in the sign-compare group.
5077 // The conditional-checking code will
5078 if (ICContext) {
5079 DiagID = diag::warn_impcast_integer_sign_conditional;
5080 *ICContext = true;
5081 }
5082
John McCallb4eb64d2010-10-08 02:01:28 +00005083 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00005084 }
5085
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005086 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005087 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
5088 // type, to give us better diagnostics.
5089 QualType SourceType = E->getType();
David Blaikie4e4d0842012-03-11 07:00:24 +00005090 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005091 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5092 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
5093 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
5094 SourceType = S.Context.getTypeDeclType(Enum);
5095 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
5096 }
5097 }
5098
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005099 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
5100 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall83972f12013-03-09 00:54:27 +00005101 if (SourceEnum->getDecl()->hasNameForLinkage() &&
5102 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00005103 SourceEnum != TargetEnum) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005104 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005105 return;
5106
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005107 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005108 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00005109 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005110
John McCall51313c32010-01-04 23:31:57 +00005111 return;
5112}
5113
David Blaikie9fb1ac52012-05-15 21:57:38 +00005114void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5115 SourceLocation CC, QualType T);
John McCall323ed742010-05-06 08:58:33 +00005116
5117void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00005118 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00005119 E = E->IgnoreParenImpCasts();
5120
5121 if (isa<ConditionalOperator>(E))
David Blaikie9fb1ac52012-05-15 21:57:38 +00005122 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCall323ed742010-05-06 08:58:33 +00005123
John McCallb4eb64d2010-10-08 02:01:28 +00005124 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005125 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00005126 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00005127 return;
5128}
5129
David Blaikie9fb1ac52012-05-15 21:57:38 +00005130void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5131 SourceLocation CC, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00005132 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00005133
5134 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00005135 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
5136 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00005137
5138 // If -Wconversion would have warned about either of the candidates
5139 // for a signedness conversion to the context type...
5140 if (!Suspicious) return;
5141
5142 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00005143 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
5144 CC))
John McCall323ed742010-05-06 08:58:33 +00005145 return;
5146
John McCall323ed742010-05-06 08:58:33 +00005147 // ...then check whether it would have warned about either of the
5148 // candidates for a signedness conversion to the condition type.
Richard Trieu52541612011-07-21 02:46:28 +00005149 if (E->getType() == T) return;
5150
5151 Suspicious = false;
5152 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
5153 E->getType(), CC, &Suspicious);
5154 if (!Suspicious)
5155 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00005156 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00005157}
5158
5159/// AnalyzeImplicitConversions - Find and report any interesting
5160/// implicit conversions in the given expression. There are a couple
5161/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00005162void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00005163 QualType T = OrigE->getType();
5164 Expr *E = OrigE->IgnoreParenImpCasts();
5165
Douglas Gregorf8b6e152011-10-10 17:38:18 +00005166 if (E->isTypeDependent() || E->isValueDependent())
5167 return;
5168
John McCall323ed742010-05-06 08:58:33 +00005169 // For conditional operators, we analyze the arguments as if they
5170 // were being fed directly into the output.
5171 if (isa<ConditionalOperator>(E)) {
5172 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie9fb1ac52012-05-15 21:57:38 +00005173 CheckConditionalOperator(S, CO, CC, T);
John McCall323ed742010-05-06 08:58:33 +00005174 return;
5175 }
5176
Hans Wennborg88617a22012-08-28 15:44:30 +00005177 // Check implicit argument conversions for function calls.
5178 if (CallExpr *Call = dyn_cast<CallExpr>(E))
5179 CheckImplicitArgumentConversions(S, Call, CC);
5180
John McCall323ed742010-05-06 08:58:33 +00005181 // Go ahead and check any implicit conversions we might have skipped.
5182 // The non-canonical typecheck is just an optimization;
5183 // CheckImplicitConversion will filter out dead implicit conversions.
5184 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00005185 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00005186
5187 // Now continue drilling into this expression.
Fariborz Jahanian6f2a9fa2013-05-15 19:03:04 +00005188
5189 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahaniana1bfe1c2013-05-15 22:25:03 +00005190 if (POE->getResultExpr())
5191 E = POE->getResultExpr();
Fariborz Jahanian6f2a9fa2013-05-15 19:03:04 +00005192 }
5193
Fariborz Jahaniana1bfe1c2013-05-15 22:25:03 +00005194 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5195 return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
5196
John McCall323ed742010-05-06 08:58:33 +00005197 // Skip past explicit casts.
5198 if (isa<ExplicitCastExpr>(E)) {
5199 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00005200 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005201 }
5202
John McCallbeb22aa2010-11-09 23:24:47 +00005203 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5204 // Do a somewhat different check with comparison operators.
5205 if (BO->isComparisonOp())
5206 return AnalyzeComparison(S, BO);
5207
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005208 // And with simple assignments.
5209 if (BO->getOpcode() == BO_Assign)
John McCallbeb22aa2010-11-09 23:24:47 +00005210 return AnalyzeAssignment(S, BO);
5211 }
John McCall323ed742010-05-06 08:58:33 +00005212
5213 // These break the otherwise-useful invariant below. Fortunately,
5214 // we don't really need to recurse into them, because any internal
5215 // expressions should have been analyzed already when they were
5216 // built into statements.
5217 if (isa<StmtExpr>(E)) return;
5218
5219 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005220 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00005221
5222 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00005223 CC = E->getExprLoc();
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005224 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
5225 bool IsLogicalOperator = BO && BO->isLogicalOp();
5226 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor54042f12012-02-09 10:18:50 +00005227 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor503384f2012-02-09 00:47:04 +00005228 if (!ChildExpr)
5229 continue;
5230
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005231 if (IsLogicalOperator &&
5232 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
5233 // Ignore checking string literals that are in logical operators.
5234 continue;
5235 AnalyzeImplicitConversions(S, ChildExpr, CC);
5236 }
John McCall323ed742010-05-06 08:58:33 +00005237}
5238
5239} // end anonymous namespace
5240
5241/// Diagnoses "dangerous" implicit conversions within the given
5242/// expression (which is a full expression). Implements -Wconversion
5243/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00005244///
5245/// \param CC the "context" location of the implicit conversion, i.e.
5246/// the most location of the syntactic entity requiring the implicit
5247/// conversion
5248void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00005249 // Don't diagnose in unevaluated contexts.
David Blaikie71f55f72012-08-06 22:47:24 +00005250 if (isUnevaluatedContext())
John McCall323ed742010-05-06 08:58:33 +00005251 return;
5252
5253 // Don't diagnose for value- or type-dependent expressions.
5254 if (E->isTypeDependent() || E->isValueDependent())
5255 return;
5256
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005257 // Check for array bounds violations in cases where the check isn't triggered
5258 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
5259 // ArraySubscriptExpr is on the RHS of a variable initialization.
5260 CheckArrayAccess(E);
5261
John McCallb4eb64d2010-10-08 02:01:28 +00005262 // This is not the right CC for (e.g.) a variable initialization.
5263 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005264}
5265
Fariborz Jahanianad48a502013-01-24 22:11:45 +00005266/// Diagnose when expression is an integer constant expression and its evaluation
5267/// results in integer overflow
5268void Sema::CheckForIntOverflow (Expr *E) {
Fariborz Jahanian1fd8d462013-03-15 20:47:07 +00005269 if (isa<BinaryOperator>(E->IgnoreParens())) {
Fariborz Jahanianad48a502013-01-24 22:11:45 +00005270 llvm::SmallVector<PartialDiagnosticAt, 4> Diags;
5271 E->EvaluateForOverflow(Context, &Diags);
5272 }
5273}
5274
Richard Smith6c3af3d2013-01-17 01:17:56 +00005275namespace {
5276/// \brief Visitor for expressions which looks for unsequenced operations on the
5277/// same object.
5278class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smith0c0b3902013-06-30 10:40:20 +00005279 typedef EvaluatedExprVisitor<SequenceChecker> Base;
5280
Richard Smith6c3af3d2013-01-17 01:17:56 +00005281 /// \brief A tree of sequenced regions within an expression. Two regions are
5282 /// unsequenced if one is an ancestor or a descendent of the other. When we
5283 /// finish processing an expression with sequencing, such as a comma
5284 /// expression, we fold its tree nodes into its parent, since they are
5285 /// unsequenced with respect to nodes we will visit later.
5286 class SequenceTree {
5287 struct Value {
5288 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
5289 unsigned Parent : 31;
5290 bool Merged : 1;
5291 };
5292 llvm::SmallVector<Value, 8> Values;
5293
5294 public:
5295 /// \brief A region within an expression which may be sequenced with respect
5296 /// to some other region.
5297 class Seq {
5298 explicit Seq(unsigned N) : Index(N) {}
5299 unsigned Index;
5300 friend class SequenceTree;
5301 public:
5302 Seq() : Index(0) {}
5303 };
5304
5305 SequenceTree() { Values.push_back(Value(0)); }
5306 Seq root() const { return Seq(0); }
5307
5308 /// \brief Create a new sequence of operations, which is an unsequenced
5309 /// subset of \p Parent. This sequence of operations is sequenced with
5310 /// respect to other children of \p Parent.
5311 Seq allocate(Seq Parent) {
5312 Values.push_back(Value(Parent.Index));
5313 return Seq(Values.size() - 1);
5314 }
5315
5316 /// \brief Merge a sequence of operations into its parent.
5317 void merge(Seq S) {
5318 Values[S.Index].Merged = true;
5319 }
5320
5321 /// \brief Determine whether two operations are unsequenced. This operation
5322 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
5323 /// should have been merged into its parent as appropriate.
5324 bool isUnsequenced(Seq Cur, Seq Old) {
5325 unsigned C = representative(Cur.Index);
5326 unsigned Target = representative(Old.Index);
5327 while (C >= Target) {
5328 if (C == Target)
5329 return true;
5330 C = Values[C].Parent;
5331 }
5332 return false;
5333 }
5334
5335 private:
5336 /// \brief Pick a representative for a sequence.
5337 unsigned representative(unsigned K) {
5338 if (Values[K].Merged)
5339 // Perform path compression as we go.
5340 return Values[K].Parent = representative(Values[K].Parent);
5341 return K;
5342 }
5343 };
5344
5345 /// An object for which we can track unsequenced uses.
5346 typedef NamedDecl *Object;
5347
5348 /// Different flavors of object usage which we track. We only track the
5349 /// least-sequenced usage of each kind.
5350 enum UsageKind {
5351 /// A read of an object. Multiple unsequenced reads are OK.
5352 UK_Use,
5353 /// A modification of an object which is sequenced before the value
Richard Smith418dd3e2013-06-26 23:16:51 +00005354 /// computation of the expression, such as ++n in C++.
Richard Smith6c3af3d2013-01-17 01:17:56 +00005355 UK_ModAsValue,
5356 /// A modification of an object which is not sequenced before the value
5357 /// computation of the expression, such as n++.
5358 UK_ModAsSideEffect,
5359
5360 UK_Count = UK_ModAsSideEffect + 1
5361 };
5362
5363 struct Usage {
5364 Usage() : Use(0), Seq() {}
5365 Expr *Use;
5366 SequenceTree::Seq Seq;
5367 };
5368
5369 struct UsageInfo {
5370 UsageInfo() : Diagnosed(false) {}
5371 Usage Uses[UK_Count];
5372 /// Have we issued a diagnostic for this variable already?
5373 bool Diagnosed;
5374 };
5375 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
5376
5377 Sema &SemaRef;
5378 /// Sequenced regions within the expression.
5379 SequenceTree Tree;
5380 /// Declaration modifications and references which we have seen.
5381 UsageInfoMap UsageMap;
5382 /// The region we are currently within.
5383 SequenceTree::Seq Region;
5384 /// Filled in with declarations which were modified as a side-effect
5385 /// (that is, post-increment operations).
5386 llvm::SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smith1a2dcd52013-01-17 23:18:09 +00005387 /// Expressions to check later. We defer checking these to reduce
5388 /// stack usage.
5389 llvm::SmallVectorImpl<Expr*> &WorkList;
Richard Smith6c3af3d2013-01-17 01:17:56 +00005390
5391 /// RAII object wrapping the visitation of a sequenced subexpression of an
5392 /// expression. At the end of this process, the side-effects of the evaluation
5393 /// become sequenced with respect to the value computation of the result, so
5394 /// we downgrade any UK_ModAsSideEffect within the evaluation to
5395 /// UK_ModAsValue.
5396 struct SequencedSubexpression {
5397 SequencedSubexpression(SequenceChecker &Self)
5398 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
5399 Self.ModAsSideEffect = &ModAsSideEffect;
5400 }
5401 ~SequencedSubexpression() {
5402 for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) {
5403 UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first];
5404 U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second;
5405 Self.addUsage(U, ModAsSideEffect[I].first,
5406 ModAsSideEffect[I].second.Use, UK_ModAsValue);
5407 }
5408 Self.ModAsSideEffect = OldModAsSideEffect;
5409 }
5410
5411 SequenceChecker &Self;
5412 llvm::SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
5413 llvm::SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
5414 };
5415
Richard Smith67470052013-06-20 22:21:56 +00005416 /// RAII object wrapping the visitation of a subexpression which we might
5417 /// choose to evaluate as a constant. If any subexpression is evaluated and
5418 /// found to be non-constant, this allows us to suppress the evaluation of
5419 /// the outer expression.
5420 class EvaluationTracker {
5421 public:
5422 EvaluationTracker(SequenceChecker &Self)
5423 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
5424 Self.EvalTracker = this;
5425 }
5426 ~EvaluationTracker() {
5427 Self.EvalTracker = Prev;
5428 if (Prev)
5429 Prev->EvalOK &= EvalOK;
5430 }
5431
5432 bool evaluate(const Expr *E, bool &Result) {
5433 if (!EvalOK || E->isValueDependent())
5434 return false;
5435 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
5436 return EvalOK;
5437 }
5438
5439 private:
5440 SequenceChecker &Self;
5441 EvaluationTracker *Prev;
5442 bool EvalOK;
5443 } *EvalTracker;
5444
Richard Smith6c3af3d2013-01-17 01:17:56 +00005445 /// \brief Find the object which is produced by the specified expression,
5446 /// if any.
5447 Object getObject(Expr *E, bool Mod) const {
5448 E = E->IgnoreParenCasts();
5449 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5450 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
5451 return getObject(UO->getSubExpr(), Mod);
5452 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5453 if (BO->getOpcode() == BO_Comma)
5454 return getObject(BO->getRHS(), Mod);
5455 if (Mod && BO->isAssignmentOp())
5456 return getObject(BO->getLHS(), Mod);
5457 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
5458 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
5459 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
5460 return ME->getMemberDecl();
5461 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5462 // FIXME: If this is a reference, map through to its value.
5463 return DRE->getDecl();
5464 return 0;
5465 }
5466
5467 /// \brief Note that an object was modified or used by an expression.
5468 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
5469 Usage &U = UI.Uses[UK];
5470 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
5471 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
5472 ModAsSideEffect->push_back(std::make_pair(O, U));
5473 U.Use = Ref;
5474 U.Seq = Region;
5475 }
5476 }
5477 /// \brief Check whether a modification or use conflicts with a prior usage.
5478 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
5479 bool IsModMod) {
5480 if (UI.Diagnosed)
5481 return;
5482
5483 const Usage &U = UI.Uses[OtherKind];
5484 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
5485 return;
5486
5487 Expr *Mod = U.Use;
5488 Expr *ModOrUse = Ref;
5489 if (OtherKind == UK_Use)
5490 std::swap(Mod, ModOrUse);
5491
5492 SemaRef.Diag(Mod->getExprLoc(),
5493 IsModMod ? diag::warn_unsequenced_mod_mod
5494 : diag::warn_unsequenced_mod_use)
5495 << O << SourceRange(ModOrUse->getExprLoc());
5496 UI.Diagnosed = true;
5497 }
5498
5499 void notePreUse(Object O, Expr *Use) {
5500 UsageInfo &U = UsageMap[O];
5501 // Uses conflict with other modifications.
5502 checkUsage(O, U, Use, UK_ModAsValue, false);
5503 }
5504 void notePostUse(Object O, Expr *Use) {
5505 UsageInfo &U = UsageMap[O];
5506 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
5507 addUsage(U, O, Use, UK_Use);
5508 }
5509
5510 void notePreMod(Object O, Expr *Mod) {
5511 UsageInfo &U = UsageMap[O];
5512 // Modifications conflict with other modifications and with uses.
5513 checkUsage(O, U, Mod, UK_ModAsValue, true);
5514 checkUsage(O, U, Mod, UK_Use, false);
5515 }
5516 void notePostMod(Object O, Expr *Use, UsageKind UK) {
5517 UsageInfo &U = UsageMap[O];
5518 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
5519 addUsage(U, O, Use, UK);
5520 }
5521
5522public:
Richard Smith1a2dcd52013-01-17 23:18:09 +00005523 SequenceChecker(Sema &S, Expr *E,
5524 llvm::SmallVectorImpl<Expr*> &WorkList)
Richard Smith0c0b3902013-06-30 10:40:20 +00005525 : Base(S.Context), SemaRef(S), Region(Tree.root()),
5526 ModAsSideEffect(0), WorkList(WorkList), EvalTracker(0) {
Richard Smith6c3af3d2013-01-17 01:17:56 +00005527 Visit(E);
5528 }
5529
5530 void VisitStmt(Stmt *S) {
5531 // Skip all statements which aren't expressions for now.
5532 }
5533
5534 void VisitExpr(Expr *E) {
5535 // By default, just recurse to evaluated subexpressions.
Richard Smith0c0b3902013-06-30 10:40:20 +00005536 Base::VisitStmt(E);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005537 }
5538
5539 void VisitCastExpr(CastExpr *E) {
5540 Object O = Object();
5541 if (E->getCastKind() == CK_LValueToRValue)
5542 O = getObject(E->getSubExpr(), false);
5543
5544 if (O)
5545 notePreUse(O, E);
5546 VisitExpr(E);
5547 if (O)
5548 notePostUse(O, E);
5549 }
5550
5551 void VisitBinComma(BinaryOperator *BO) {
5552 // C++11 [expr.comma]p1:
5553 // Every value computation and side effect associated with the left
5554 // expression is sequenced before every value computation and side
5555 // effect associated with the right expression.
5556 SequenceTree::Seq LHS = Tree.allocate(Region);
5557 SequenceTree::Seq RHS = Tree.allocate(Region);
5558 SequenceTree::Seq OldRegion = Region;
5559
5560 {
5561 SequencedSubexpression SeqLHS(*this);
5562 Region = LHS;
5563 Visit(BO->getLHS());
5564 }
5565
5566 Region = RHS;
5567 Visit(BO->getRHS());
5568
5569 Region = OldRegion;
5570
5571 // Forget that LHS and RHS are sequenced. They are both unsequenced
5572 // with respect to other stuff.
5573 Tree.merge(LHS);
5574 Tree.merge(RHS);
5575 }
5576
5577 void VisitBinAssign(BinaryOperator *BO) {
5578 // The modification is sequenced after the value computation of the LHS
5579 // and RHS, so check it before inspecting the operands and update the
5580 // map afterwards.
5581 Object O = getObject(BO->getLHS(), true);
5582 if (!O)
5583 return VisitExpr(BO);
5584
5585 notePreMod(O, BO);
5586
5587 // C++11 [expr.ass]p7:
5588 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
5589 // only once.
5590 //
5591 // Therefore, for a compound assignment operator, O is considered used
5592 // everywhere except within the evaluation of E1 itself.
5593 if (isa<CompoundAssignOperator>(BO))
5594 notePreUse(O, BO);
5595
5596 Visit(BO->getLHS());
5597
5598 if (isa<CompoundAssignOperator>(BO))
5599 notePostUse(O, BO);
5600
5601 Visit(BO->getRHS());
5602
Richard Smith418dd3e2013-06-26 23:16:51 +00005603 // C++11 [expr.ass]p1:
5604 // the assignment is sequenced [...] before the value computation of the
5605 // assignment expression.
5606 // C11 6.5.16/3 has no such rule.
5607 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
5608 : UK_ModAsSideEffect);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005609 }
5610 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
5611 VisitBinAssign(CAO);
5612 }
5613
5614 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
5615 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
5616 void VisitUnaryPreIncDec(UnaryOperator *UO) {
5617 Object O = getObject(UO->getSubExpr(), true);
5618 if (!O)
5619 return VisitExpr(UO);
5620
5621 notePreMod(O, UO);
5622 Visit(UO->getSubExpr());
Richard Smith418dd3e2013-06-26 23:16:51 +00005623 // C++11 [expr.pre.incr]p1:
5624 // the expression ++x is equivalent to x+=1
5625 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
5626 : UK_ModAsSideEffect);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005627 }
5628
5629 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
5630 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
5631 void VisitUnaryPostIncDec(UnaryOperator *UO) {
5632 Object O = getObject(UO->getSubExpr(), true);
5633 if (!O)
5634 return VisitExpr(UO);
5635
5636 notePreMod(O, UO);
5637 Visit(UO->getSubExpr());
5638 notePostMod(O, UO, UK_ModAsSideEffect);
5639 }
5640
5641 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
5642 void VisitBinLOr(BinaryOperator *BO) {
5643 // The side-effects of the LHS of an '&&' are sequenced before the
5644 // value computation of the RHS, and hence before the value computation
5645 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
5646 // as if they were unconditionally sequenced.
Richard Smith67470052013-06-20 22:21:56 +00005647 EvaluationTracker Eval(*this);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005648 {
5649 SequencedSubexpression Sequenced(*this);
5650 Visit(BO->getLHS());
5651 }
5652
5653 bool Result;
Richard Smith67470052013-06-20 22:21:56 +00005654 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith995e4a72013-01-17 22:06:26 +00005655 if (!Result)
5656 Visit(BO->getRHS());
5657 } else {
5658 // Check for unsequenced operations in the RHS, treating it as an
5659 // entirely separate evaluation.
5660 //
5661 // FIXME: If there are operations in the RHS which are unsequenced
5662 // with respect to operations outside the RHS, and those operations
5663 // are unconditionally evaluated, diagnose them.
Richard Smith1a2dcd52013-01-17 23:18:09 +00005664 WorkList.push_back(BO->getRHS());
Richard Smith995e4a72013-01-17 22:06:26 +00005665 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00005666 }
5667 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith67470052013-06-20 22:21:56 +00005668 EvaluationTracker Eval(*this);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005669 {
5670 SequencedSubexpression Sequenced(*this);
5671 Visit(BO->getLHS());
5672 }
5673
5674 bool Result;
Richard Smith67470052013-06-20 22:21:56 +00005675 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith995e4a72013-01-17 22:06:26 +00005676 if (Result)
5677 Visit(BO->getRHS());
5678 } else {
Richard Smith1a2dcd52013-01-17 23:18:09 +00005679 WorkList.push_back(BO->getRHS());
Richard Smith995e4a72013-01-17 22:06:26 +00005680 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00005681 }
5682
5683 // Only visit the condition, unless we can be sure which subexpression will
5684 // be chosen.
5685 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith67470052013-06-20 22:21:56 +00005686 EvaluationTracker Eval(*this);
Richard Smith418dd3e2013-06-26 23:16:51 +00005687 {
5688 SequencedSubexpression Sequenced(*this);
5689 Visit(CO->getCond());
5690 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00005691
5692 bool Result;
Richard Smith67470052013-06-20 22:21:56 +00005693 if (Eval.evaluate(CO->getCond(), Result))
Richard Smith6c3af3d2013-01-17 01:17:56 +00005694 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith995e4a72013-01-17 22:06:26 +00005695 else {
Richard Smith1a2dcd52013-01-17 23:18:09 +00005696 WorkList.push_back(CO->getTrueExpr());
5697 WorkList.push_back(CO->getFalseExpr());
Richard Smith995e4a72013-01-17 22:06:26 +00005698 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00005699 }
5700
Richard Smith0c0b3902013-06-30 10:40:20 +00005701 void VisitCallExpr(CallExpr *CE) {
5702 // C++11 [intro.execution]p15:
5703 // When calling a function [...], every value computation and side effect
5704 // associated with any argument expression, or with the postfix expression
5705 // designating the called function, is sequenced before execution of every
5706 // expression or statement in the body of the function [and thus before
5707 // the value computation of its result].
5708 SequencedSubexpression Sequenced(*this);
5709 Base::VisitCallExpr(CE);
5710
5711 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
5712 }
5713
Richard Smith6c3af3d2013-01-17 01:17:56 +00005714 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smith0c0b3902013-06-30 10:40:20 +00005715 // This is a call, so all subexpressions are sequenced before the result.
5716 SequencedSubexpression Sequenced(*this);
5717
Richard Smith6c3af3d2013-01-17 01:17:56 +00005718 if (!CCE->isListInitialization())
5719 return VisitExpr(CCE);
5720
5721 // In C++11, list initializations are sequenced.
5722 llvm::SmallVector<SequenceTree::Seq, 32> Elts;
5723 SequenceTree::Seq Parent = Region;
5724 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
5725 E = CCE->arg_end();
5726 I != E; ++I) {
5727 Region = Tree.allocate(Parent);
5728 Elts.push_back(Region);
5729 Visit(*I);
5730 }
5731
5732 // Forget that the initializers are sequenced.
5733 Region = Parent;
5734 for (unsigned I = 0; I < Elts.size(); ++I)
5735 Tree.merge(Elts[I]);
5736 }
5737
5738 void VisitInitListExpr(InitListExpr *ILE) {
5739 if (!SemaRef.getLangOpts().CPlusPlus11)
5740 return VisitExpr(ILE);
5741
5742 // In C++11, list initializations are sequenced.
5743 llvm::SmallVector<SequenceTree::Seq, 32> Elts;
5744 SequenceTree::Seq Parent = Region;
5745 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
5746 Expr *E = ILE->getInit(I);
5747 if (!E) continue;
5748 Region = Tree.allocate(Parent);
5749 Elts.push_back(Region);
5750 Visit(E);
5751 }
5752
5753 // Forget that the initializers are sequenced.
5754 Region = Parent;
5755 for (unsigned I = 0; I < Elts.size(); ++I)
5756 Tree.merge(Elts[I]);
5757 }
5758};
5759}
5760
5761void Sema::CheckUnsequencedOperations(Expr *E) {
Richard Smith1a2dcd52013-01-17 23:18:09 +00005762 llvm::SmallVector<Expr*, 8> WorkList;
5763 WorkList.push_back(E);
5764 while (!WorkList.empty()) {
5765 Expr *Item = WorkList.back();
5766 WorkList.pop_back();
5767 SequenceChecker(*this, Item, WorkList);
5768 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00005769}
5770
Fariborz Jahanianad48a502013-01-24 22:11:45 +00005771void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
5772 bool IsConstexpr) {
Richard Smith6c3af3d2013-01-17 01:17:56 +00005773 CheckImplicitConversions(E, CheckLoc);
5774 CheckUnsequencedOperations(E);
Fariborz Jahanianad48a502013-01-24 22:11:45 +00005775 if (!IsConstexpr && !E->isValueDependent())
5776 CheckForIntOverflow(E);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005777}
5778
John McCall15d7d122010-11-11 03:21:53 +00005779void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
5780 FieldDecl *BitField,
5781 Expr *Init) {
5782 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
5783}
5784
Mike Stumpf8c49212010-01-21 03:59:47 +00005785/// CheckParmsForFunctionDef - Check that the parameters of the given
5786/// function are appropriate for the definition of a function. This
5787/// takes care of any checks that cannot be performed on the
5788/// declaration itself, e.g., that the types of each of the function
5789/// parameters are complete.
Reid Kleckner8c0501c2013-06-24 14:38:26 +00005790bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
5791 ParmVarDecl *const *PEnd,
Douglas Gregor82aa7132010-11-01 18:37:59 +00005792 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00005793 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00005794 for (; P != PEnd; ++P) {
5795 ParmVarDecl *Param = *P;
5796
Mike Stumpf8c49212010-01-21 03:59:47 +00005797 // C99 6.7.5.3p4: the parameters in a parameter type list in a
5798 // function declarator that is part of a function definition of
5799 // that function shall not have incomplete type.
5800 //
5801 // This is also C++ [dcl.fct]p6.
5802 if (!Param->isInvalidDecl() &&
5803 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00005804 diag::err_typecheck_decl_incomplete_type)) {
Mike Stumpf8c49212010-01-21 03:59:47 +00005805 Param->setInvalidDecl();
5806 HasInvalidParm = true;
5807 }
5808
5809 // C99 6.9.1p5: If the declarator includes a parameter type list, the
5810 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00005811 if (CheckParameterNames &&
5812 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00005813 !Param->isImplicit() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00005814 !getLangOpts().CPlusPlus)
Mike Stumpf8c49212010-01-21 03:59:47 +00005815 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00005816
5817 // C99 6.7.5.3p12:
5818 // If the function declarator is not part of a definition of that
5819 // function, parameters may have incomplete type and may use the [*]
5820 // notation in their sequences of declarator specifiers to specify
5821 // variable length array types.
5822 QualType PType = Param->getOriginalType();
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00005823 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigd17e3402010-02-01 05:02:49 +00005824 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitfc093362013-03-01 21:41:22 +00005825 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigd17e3402010-02-01 05:02:49 +00005826 // information is added for it.
5827 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00005828 break;
Sam Weinigd17e3402010-02-01 05:02:49 +00005829 }
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00005830 PType= AT->getElementType();
Sam Weinigd17e3402010-02-01 05:02:49 +00005831 }
Reid Kleckner9b601952013-06-21 12:45:15 +00005832
5833 // MSVC destroys objects passed by value in the callee. Therefore a
5834 // function definition which takes such a parameter must be able to call the
5835 // object's destructor.
5836 if (getLangOpts().CPlusPlus &&
5837 Context.getTargetInfo().getCXXABI().isArgumentDestroyedByCallee()) {
5838 if (const RecordType *RT = Param->getType()->getAs<RecordType>())
5839 FinalizeVarWithDestructor(Param, RT);
5840 }
Mike Stumpf8c49212010-01-21 03:59:47 +00005841 }
5842
5843 return HasInvalidParm;
5844}
John McCallb7f4ffe2010-08-12 21:44:57 +00005845
5846/// CheckCastAlign - Implements -Wcast-align, which warns when a
5847/// pointer cast increases the alignment requirements.
5848void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
5849 // This is actually a lot of work to potentially be doing on every
5850 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00005851 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
5852 TRange.getBegin())
David Blaikied6471f72011-09-25 23:23:43 +00005853 == DiagnosticsEngine::Ignored)
John McCallb7f4ffe2010-08-12 21:44:57 +00005854 return;
5855
5856 // Ignore dependent types.
5857 if (T->isDependentType() || Op->getType()->isDependentType())
5858 return;
5859
5860 // Require that the destination be a pointer type.
5861 const PointerType *DestPtr = T->getAs<PointerType>();
5862 if (!DestPtr) return;
5863
5864 // If the destination has alignment 1, we're done.
5865 QualType DestPointee = DestPtr->getPointeeType();
5866 if (DestPointee->isIncompleteType()) return;
5867 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
5868 if (DestAlign.isOne()) return;
5869
5870 // Require that the source be a pointer type.
5871 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
5872 if (!SrcPtr) return;
5873 QualType SrcPointee = SrcPtr->getPointeeType();
5874
5875 // Whitelist casts from cv void*. We already implicitly
5876 // whitelisted casts to cv void*, since they have alignment 1.
5877 // Also whitelist casts involving incomplete types, which implicitly
5878 // includes 'void'.
5879 if (SrcPointee->isIncompleteType()) return;
5880
5881 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
5882 if (SrcAlign >= DestAlign) return;
5883
5884 Diag(TRange.getBegin(), diag::warn_cast_align)
5885 << Op->getType() << T
5886 << static_cast<unsigned>(SrcAlign.getQuantity())
5887 << static_cast<unsigned>(DestAlign.getQuantity())
5888 << TRange << Op->getSourceRange();
5889}
5890
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005891static const Type* getElementType(const Expr *BaseExpr) {
5892 const Type* EltType = BaseExpr->getType().getTypePtr();
5893 if (EltType->isAnyPointerType())
5894 return EltType->getPointeeType().getTypePtr();
5895 else if (EltType->isArrayType())
5896 return EltType->getBaseElementTypeUnsafe();
5897 return EltType;
5898}
5899
Chandler Carruthc2684342011-08-05 09:10:50 +00005900/// \brief Check whether this array fits the idiom of a size-one tail padded
5901/// array member of a struct.
5902///
5903/// We avoid emitting out-of-bounds access warnings for such arrays as they are
5904/// commonly used to emulate flexible arrays in C89 code.
5905static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
5906 const NamedDecl *ND) {
5907 if (Size != 1 || !ND) return false;
5908
5909 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
5910 if (!FD) return false;
5911
5912 // Don't consider sizes resulting from macro expansions or template argument
5913 // substitution to form C89 tail-padded arrays.
Sean Callanand2cf3482012-05-04 18:22:53 +00005914
5915 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00005916 while (TInfo) {
5917 TypeLoc TL = TInfo->getTypeLoc();
5918 // Look through typedefs.
David Blaikie39e6ab42013-02-18 22:06:02 +00005919 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
5920 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00005921 TInfo = TDL->getTypeSourceInfo();
5922 continue;
5923 }
David Blaikie39e6ab42013-02-18 22:06:02 +00005924 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
5925 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier5e253012013-02-06 00:58:34 +00005926 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
5927 return false;
5928 }
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00005929 break;
Sean Callanand2cf3482012-05-04 18:22:53 +00005930 }
Chandler Carruthc2684342011-08-05 09:10:50 +00005931
5932 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gay381711c2011-11-29 22:43:53 +00005933 if (!RD) return false;
5934 if (RD->isUnion()) return false;
5935 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
5936 if (!CRD->isStandardLayout()) return false;
5937 }
Chandler Carruthc2684342011-08-05 09:10:50 +00005938
Benjamin Kramer22d4fed2011-08-06 03:04:42 +00005939 // See if this is the last field decl in the record.
5940 const Decl *D = FD;
5941 while ((D = D->getNextDeclInContext()))
5942 if (isa<FieldDecl>(D))
5943 return false;
5944 return true;
Chandler Carruthc2684342011-08-05 09:10:50 +00005945}
5946
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005947void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005948 const ArraySubscriptExpr *ASE,
Richard Smith25b009a2011-12-16 19:31:14 +00005949 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman92b670e2012-02-27 21:21:40 +00005950 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005951 if (IndexExpr->isValueDependent())
5952 return;
5953
Matt Beaumont-Gay8ef8f432011-12-12 22:35:02 +00005954 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005955 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00005956 const ConstantArrayType *ArrayTy =
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005957 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00005958 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00005959 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00005960
Chandler Carruth34064582011-02-17 20:55:08 +00005961 llvm::APSInt index;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005962 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00005963 return;
Richard Smith25b009a2011-12-16 19:31:14 +00005964 if (IndexNegated)
5965 index = -index;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00005966
Chandler Carruthba447122011-08-05 08:07:29 +00005967 const NamedDecl *ND = NULL;
Chandler Carruthba447122011-08-05 08:07:29 +00005968 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
5969 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruthc2684342011-08-05 09:10:50 +00005970 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruthba447122011-08-05 08:07:29 +00005971 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruthba447122011-08-05 08:07:29 +00005972
Ted Kremenek9e060ca2011-02-23 23:06:04 +00005973 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00005974 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00005975 if (!size.isStrictlyPositive())
5976 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005977
5978 const Type* BaseType = getElementType(BaseExpr);
Nico Weberde5998f2011-09-17 22:59:41 +00005979 if (BaseType != EffectiveType) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005980 // Make sure we're comparing apples to apples when comparing index to size
5981 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
5982 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhraind10f4bc2011-08-10 19:47:25 +00005983 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhrain18f16972011-08-10 18:49:28 +00005984 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005985 if (ptrarith_typesize != array_typesize) {
5986 // There's a cast to a different size type involved
5987 uint64_t ratio = array_typesize / ptrarith_typesize;
5988 // TODO: Be smarter about handling cases where array_typesize is not a
5989 // multiple of ptrarith_typesize
5990 if (ptrarith_typesize * ratio == array_typesize)
5991 size *= llvm::APInt(size.getBitWidth(), ratio);
5992 }
5993 }
5994
Chandler Carruth34064582011-02-17 20:55:08 +00005995 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00005996 index = index.zext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00005997 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00005998 size = size.zext(index.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00005999
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006000 // For array subscripting the index must be less than size, but for pointer
6001 // arithmetic also allow the index (offset) to be equal to size since
6002 // computing the next address after the end of the array is legal and
6003 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman92b670e2012-02-27 21:21:40 +00006004 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruthba447122011-08-05 08:07:29 +00006005 return;
6006
6007 // Also don't warn for arrays of size 1 which are members of some
6008 // structure. These are often used to approximate flexible arrays in C89
6009 // code.
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006010 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00006011 return;
Chandler Carruth34064582011-02-17 20:55:08 +00006012
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006013 // Suppress the warning if the subscript expression (as identified by the
6014 // ']' location) and the index expression are both from macro expansions
6015 // within a system header.
6016 if (ASE) {
6017 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
6018 ASE->getRBracketLoc());
6019 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
6020 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
6021 IndexExpr->getLocStart());
6022 if (SourceMgr.isFromSameFile(RBracketLoc, IndexLoc))
6023 return;
6024 }
6025 }
6026
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006027 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006028 if (ASE)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006029 DiagID = diag::warn_array_index_exceeds_bounds;
6030
6031 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6032 PDiag(DiagID) << index.toString(10, true)
6033 << size.toString(10, true)
6034 << (unsigned)size.getLimitedValue(~0U)
6035 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00006036 } else {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006037 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006038 if (!ASE) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006039 DiagID = diag::warn_ptr_arith_precedes_bounds;
6040 if (index.isNegative()) index = -index;
6041 }
6042
6043 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6044 PDiag(DiagID) << index.toString(10, true)
6045 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00006046 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00006047
Matt Beaumont-Gaycfbc5b52011-11-29 19:27:11 +00006048 if (!ND) {
6049 // Try harder to find a NamedDecl to point at in the note.
6050 while (const ArraySubscriptExpr *ASE =
6051 dyn_cast<ArraySubscriptExpr>(BaseExpr))
6052 BaseExpr = ASE->getBase()->IgnoreParenCasts();
6053 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
6054 ND = dyn_cast<NamedDecl>(DRE->getDecl());
6055 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
6056 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
6057 }
6058
Chandler Carruth35001ca2011-02-17 21:10:52 +00006059 if (ND)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006060 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
6061 PDiag(diag::note_array_index_out_of_bounds)
6062 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00006063}
6064
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006065void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006066 int AllowOnePastEnd = 0;
6067 while (expr) {
6068 expr = expr->IgnoreParenImpCasts();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006069 switch (expr->getStmtClass()) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006070 case Stmt::ArraySubscriptExprClass: {
6071 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006072 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006073 AllowOnePastEnd > 0);
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006074 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006075 }
6076 case Stmt::UnaryOperatorClass: {
6077 // Only unwrap the * and & unary operators
6078 const UnaryOperator *UO = cast<UnaryOperator>(expr);
6079 expr = UO->getSubExpr();
6080 switch (UO->getOpcode()) {
6081 case UO_AddrOf:
6082 AllowOnePastEnd++;
6083 break;
6084 case UO_Deref:
6085 AllowOnePastEnd--;
6086 break;
6087 default:
6088 return;
6089 }
6090 break;
6091 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006092 case Stmt::ConditionalOperatorClass: {
6093 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
6094 if (const Expr *lhs = cond->getLHS())
6095 CheckArrayAccess(lhs);
6096 if (const Expr *rhs = cond->getRHS())
6097 CheckArrayAccess(rhs);
6098 return;
6099 }
6100 default:
6101 return;
6102 }
Peter Collingbournef111d932011-04-15 00:35:48 +00006103 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006104}
John McCallf85e1932011-06-15 23:02:42 +00006105
6106//===--- CHECK: Objective-C retain cycles ----------------------------------//
6107
6108namespace {
6109 struct RetainCycleOwner {
6110 RetainCycleOwner() : Variable(0), Indirect(false) {}
6111 VarDecl *Variable;
6112 SourceRange Range;
6113 SourceLocation Loc;
6114 bool Indirect;
6115
6116 void setLocsFrom(Expr *e) {
6117 Loc = e->getExprLoc();
6118 Range = e->getSourceRange();
6119 }
6120 };
6121}
6122
6123/// Consider whether capturing the given variable can possibly lead to
6124/// a retain cycle.
6125static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledruf3477c12012-09-27 10:16:10 +00006126 // In ARC, it's captured strongly iff the variable has __strong
John McCallf85e1932011-06-15 23:02:42 +00006127 // lifetime. In MRR, it's captured strongly if the variable is
6128 // __block and has an appropriate type.
6129 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
6130 return false;
6131
6132 owner.Variable = var;
Jordan Rosee10f4d32012-09-15 02:48:31 +00006133 if (ref)
6134 owner.setLocsFrom(ref);
John McCallf85e1932011-06-15 23:02:42 +00006135 return true;
6136}
6137
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006138static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCallf85e1932011-06-15 23:02:42 +00006139 while (true) {
6140 e = e->IgnoreParens();
6141 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
6142 switch (cast->getCastKind()) {
6143 case CK_BitCast:
6144 case CK_LValueBitCast:
6145 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00006146 case CK_ARCReclaimReturnedObject:
John McCallf85e1932011-06-15 23:02:42 +00006147 e = cast->getSubExpr();
6148 continue;
6149
John McCallf85e1932011-06-15 23:02:42 +00006150 default:
6151 return false;
6152 }
6153 }
6154
6155 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
6156 ObjCIvarDecl *ivar = ref->getDecl();
6157 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
6158 return false;
6159
6160 // Try to find a retain cycle in the base.
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006161 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCallf85e1932011-06-15 23:02:42 +00006162 return false;
6163
6164 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
6165 owner.Indirect = true;
6166 return true;
6167 }
6168
6169 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
6170 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
6171 if (!var) return false;
6172 return considerVariable(var, ref, owner);
6173 }
6174
John McCallf85e1932011-06-15 23:02:42 +00006175 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
6176 if (member->isArrow()) return false;
6177
6178 // Don't count this as an indirect ownership.
6179 e = member->getBase();
6180 continue;
6181 }
6182
John McCall4b9c2d22011-11-06 09:01:30 +00006183 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
6184 // Only pay attention to pseudo-objects on property references.
6185 ObjCPropertyRefExpr *pre
6186 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
6187 ->IgnoreParens());
6188 if (!pre) return false;
6189 if (pre->isImplicitProperty()) return false;
6190 ObjCPropertyDecl *property = pre->getExplicitProperty();
6191 if (!property->isRetaining() &&
6192 !(property->getPropertyIvarDecl() &&
6193 property->getPropertyIvarDecl()->getType()
6194 .getObjCLifetime() == Qualifiers::OCL_Strong))
6195 return false;
6196
6197 owner.Indirect = true;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006198 if (pre->isSuperReceiver()) {
6199 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
6200 if (!owner.Variable)
6201 return false;
6202 owner.Loc = pre->getLocation();
6203 owner.Range = pre->getSourceRange();
6204 return true;
6205 }
John McCall4b9c2d22011-11-06 09:01:30 +00006206 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
6207 ->getSourceExpr());
6208 continue;
6209 }
6210
John McCallf85e1932011-06-15 23:02:42 +00006211 // Array ivars?
6212
6213 return false;
6214 }
6215}
6216
6217namespace {
6218 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
6219 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
6220 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
6221 Variable(variable), Capturer(0) {}
6222
6223 VarDecl *Variable;
6224 Expr *Capturer;
6225
6226 void VisitDeclRefExpr(DeclRefExpr *ref) {
6227 if (ref->getDecl() == Variable && !Capturer)
6228 Capturer = ref;
6229 }
6230
John McCallf85e1932011-06-15 23:02:42 +00006231 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
6232 if (Capturer) return;
6233 Visit(ref->getBase());
6234 if (Capturer && ref->isFreeIvar())
6235 Capturer = ref;
6236 }
6237
6238 void VisitBlockExpr(BlockExpr *block) {
6239 // Look inside nested blocks
6240 if (block->getBlockDecl()->capturesVariable(Variable))
6241 Visit(block->getBlockDecl()->getBody());
6242 }
Fariborz Jahanian7e2e4c32012-08-31 20:04:47 +00006243
6244 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
6245 if (Capturer) return;
6246 if (OVE->getSourceExpr())
6247 Visit(OVE->getSourceExpr());
6248 }
John McCallf85e1932011-06-15 23:02:42 +00006249 };
6250}
6251
6252/// Check whether the given argument is a block which captures a
6253/// variable.
6254static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
6255 assert(owner.Variable && owner.Loc.isValid());
6256
6257 e = e->IgnoreParenCasts();
Jordan Rose1fac58a2012-09-17 17:54:30 +00006258
6259 // Look through [^{...} copy] and Block_copy(^{...}).
6260 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
6261 Selector Cmd = ME->getSelector();
6262 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
6263 e = ME->getInstanceReceiver();
6264 if (!e)
6265 return 0;
6266 e = e->IgnoreParenCasts();
6267 }
6268 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
6269 if (CE->getNumArgs() == 1) {
6270 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekd13eff62012-10-02 04:36:54 +00006271 if (Fn) {
6272 const IdentifierInfo *FnI = Fn->getIdentifier();
6273 if (FnI && FnI->isStr("_Block_copy")) {
6274 e = CE->getArg(0)->IgnoreParenCasts();
6275 }
6276 }
Jordan Rose1fac58a2012-09-17 17:54:30 +00006277 }
6278 }
6279
John McCallf85e1932011-06-15 23:02:42 +00006280 BlockExpr *block = dyn_cast<BlockExpr>(e);
6281 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
6282 return 0;
6283
6284 FindCaptureVisitor visitor(S.Context, owner.Variable);
6285 visitor.Visit(block->getBlockDecl()->getBody());
6286 return visitor.Capturer;
6287}
6288
6289static void diagnoseRetainCycle(Sema &S, Expr *capturer,
6290 RetainCycleOwner &owner) {
6291 assert(capturer);
6292 assert(owner.Variable && owner.Loc.isValid());
6293
6294 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
6295 << owner.Variable << capturer->getSourceRange();
6296 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
6297 << owner.Indirect << owner.Range;
6298}
6299
6300/// Check for a keyword selector that starts with the word 'add' or
6301/// 'set'.
6302static bool isSetterLikeSelector(Selector sel) {
6303 if (sel.isUnarySelector()) return false;
6304
Chris Lattner5f9e2722011-07-23 10:55:15 +00006305 StringRef str = sel.getNameForSlot(0);
John McCallf85e1932011-06-15 23:02:42 +00006306 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00006307 if (str.startswith("set"))
John McCallf85e1932011-06-15 23:02:42 +00006308 str = str.substr(3);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00006309 else if (str.startswith("add")) {
6310 // Specially whitelist 'addOperationWithBlock:'.
6311 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
6312 return false;
6313 str = str.substr(3);
6314 }
John McCallf85e1932011-06-15 23:02:42 +00006315 else
6316 return false;
6317
6318 if (str.empty()) return true;
Jordan Rose3f6f51e2013-02-08 22:30:41 +00006319 return !isLowercase(str.front());
John McCallf85e1932011-06-15 23:02:42 +00006320}
6321
6322/// Check a message send to see if it's likely to cause a retain cycle.
6323void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
6324 // Only check instance methods whose selector looks like a setter.
6325 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
6326 return;
6327
6328 // Try to find a variable that the receiver is strongly owned by.
6329 RetainCycleOwner owner;
6330 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006331 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCallf85e1932011-06-15 23:02:42 +00006332 return;
6333 } else {
6334 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
6335 owner.Variable = getCurMethodDecl()->getSelfDecl();
6336 owner.Loc = msg->getSuperLoc();
6337 owner.Range = msg->getSuperLoc();
6338 }
6339
6340 // Check whether the receiver is captured by any of the arguments.
6341 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
6342 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
6343 return diagnoseRetainCycle(*this, capturer, owner);
6344}
6345
6346/// Check a property assign to see if it's likely to cause a retain cycle.
6347void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
6348 RetainCycleOwner owner;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006349 if (!findRetainCycleOwner(*this, receiver, owner))
John McCallf85e1932011-06-15 23:02:42 +00006350 return;
6351
6352 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
6353 diagnoseRetainCycle(*this, capturer, owner);
6354}
6355
Jordan Rosee10f4d32012-09-15 02:48:31 +00006356void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
6357 RetainCycleOwner Owner;
6358 if (!considerVariable(Var, /*DeclRefExpr=*/0, Owner))
6359 return;
6360
6361 // Because we don't have an expression for the variable, we have to set the
6362 // location explicitly here.
6363 Owner.Loc = Var->getLocation();
6364 Owner.Range = Var->getSourceRange();
6365
6366 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
6367 diagnoseRetainCycle(*this, Capturer, Owner);
6368}
6369
Ted Kremenek9d084012012-12-21 08:04:28 +00006370static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
6371 Expr *RHS, bool isProperty) {
6372 // Check if RHS is an Objective-C object literal, which also can get
6373 // immediately zapped in a weak reference. Note that we explicitly
6374 // allow ObjCStringLiterals, since those are designed to never really die.
6375 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenekf530ff72012-12-21 21:59:39 +00006376
Ted Kremenekd3292c82012-12-21 22:46:35 +00006377 // This enum needs to match with the 'select' in
6378 // warn_objc_arc_literal_assign (off-by-1).
6379 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
6380 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
6381 return false;
Ted Kremenekf530ff72012-12-21 21:59:39 +00006382
6383 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenekd3292c82012-12-21 22:46:35 +00006384 << (unsigned) Kind
Ted Kremenek9d084012012-12-21 08:04:28 +00006385 << (isProperty ? 0 : 1)
6386 << RHS->getSourceRange();
Ted Kremenekf530ff72012-12-21 21:59:39 +00006387
6388 return true;
Ted Kremenek9d084012012-12-21 08:04:28 +00006389}
6390
Ted Kremenekb29b30f2012-12-21 19:45:30 +00006391static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
6392 Qualifiers::ObjCLifetime LT,
6393 Expr *RHS, bool isProperty) {
6394 // Strip off any implicit cast added to get to the one ARC-specific.
6395 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
6396 if (cast->getCastKind() == CK_ARCConsumeObject) {
6397 S.Diag(Loc, diag::warn_arc_retained_assign)
6398 << (LT == Qualifiers::OCL_ExplicitNone)
6399 << (isProperty ? 0 : 1)
6400 << RHS->getSourceRange();
6401 return true;
6402 }
6403 RHS = cast->getSubExpr();
6404 }
6405
6406 if (LT == Qualifiers::OCL_Weak &&
6407 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
6408 return true;
6409
6410 return false;
6411}
6412
Ted Kremenekb1ea5102012-12-21 08:04:20 +00006413bool Sema::checkUnsafeAssigns(SourceLocation Loc,
6414 QualType LHS, Expr *RHS) {
6415 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
6416
6417 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
6418 return false;
6419
6420 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
6421 return true;
6422
6423 return false;
6424}
6425
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006426void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
6427 Expr *LHS, Expr *RHS) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006428 QualType LHSType;
6429 // PropertyRef on LHS type need be directly obtained from
6430 // its declaration as it has a PsuedoType.
6431 ObjCPropertyRefExpr *PRE
6432 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
6433 if (PRE && !PRE->isImplicitProperty()) {
6434 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
6435 if (PD)
6436 LHSType = PD->getType();
6437 }
6438
6439 if (LHSType.isNull())
6440 LHSType = LHS->getType();
Jordan Rose7a270482012-09-28 22:21:35 +00006441
6442 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
6443
6444 if (LT == Qualifiers::OCL_Weak) {
6445 DiagnosticsEngine::Level Level =
6446 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
6447 if (Level != DiagnosticsEngine::Ignored)
6448 getCurFunction()->markSafeWeakUse(LHS);
6449 }
6450
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006451 if (checkUnsafeAssigns(Loc, LHSType, RHS))
6452 return;
Jordan Rose7a270482012-09-28 22:21:35 +00006453
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006454 // FIXME. Check for other life times.
6455 if (LT != Qualifiers::OCL_None)
6456 return;
6457
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006458 if (PRE) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006459 if (PRE->isImplicitProperty())
6460 return;
6461 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
6462 if (!PD)
6463 return;
6464
Bill Wendlingad017fa2012-12-20 19:22:21 +00006465 unsigned Attributes = PD->getPropertyAttributes();
6466 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006467 // when 'assign' attribute was not explicitly specified
6468 // by user, ignore it and rely on property type itself
6469 // for lifetime info.
6470 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
6471 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
6472 LHSType->isObjCRetainableType())
6473 return;
6474
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006475 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00006476 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006477 Diag(Loc, diag::warn_arc_retained_property_assign)
6478 << RHS->getSourceRange();
6479 return;
6480 }
6481 RHS = cast->getSubExpr();
6482 }
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006483 }
Bill Wendlingad017fa2012-12-20 19:22:21 +00006484 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb1ea5102012-12-21 08:04:20 +00006485 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
6486 return;
Fariborz Jahanianbd2e27e2012-07-06 21:09:27 +00006487 }
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006488 }
6489}
Dmitri Gribenko625bb562012-02-14 22:14:32 +00006490
6491//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
6492
6493namespace {
6494bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
6495 SourceLocation StmtLoc,
6496 const NullStmt *Body) {
6497 // Do not warn if the body is a macro that expands to nothing, e.g:
6498 //
6499 // #define CALL(x)
6500 // if (condition)
6501 // CALL(0);
6502 //
6503 if (Body->hasLeadingEmptyMacro())
6504 return false;
6505
6506 // Get line numbers of statement and body.
6507 bool StmtLineInvalid;
6508 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
6509 &StmtLineInvalid);
6510 if (StmtLineInvalid)
6511 return false;
6512
6513 bool BodyLineInvalid;
6514 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
6515 &BodyLineInvalid);
6516 if (BodyLineInvalid)
6517 return false;
6518
6519 // Warn if null statement and body are on the same line.
6520 if (StmtLine != BodyLine)
6521 return false;
6522
6523 return true;
6524}
6525} // Unnamed namespace
6526
6527void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
6528 const Stmt *Body,
6529 unsigned DiagID) {
6530 // Since this is a syntactic check, don't emit diagnostic for template
6531 // instantiations, this just adds noise.
6532 if (CurrentInstantiationScope)
6533 return;
6534
6535 // The body should be a null statement.
6536 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
6537 if (!NBody)
6538 return;
6539
6540 // Do the usual checks.
6541 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
6542 return;
6543
6544 Diag(NBody->getSemiLoc(), DiagID);
6545 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
6546}
6547
6548void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
6549 const Stmt *PossibleBody) {
6550 assert(!CurrentInstantiationScope); // Ensured by caller
6551
6552 SourceLocation StmtLoc;
6553 const Stmt *Body;
6554 unsigned DiagID;
6555 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
6556 StmtLoc = FS->getRParenLoc();
6557 Body = FS->getBody();
6558 DiagID = diag::warn_empty_for_body;
6559 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
6560 StmtLoc = WS->getCond()->getSourceRange().getEnd();
6561 Body = WS->getBody();
6562 DiagID = diag::warn_empty_while_body;
6563 } else
6564 return; // Neither `for' nor `while'.
6565
6566 // The body should be a null statement.
6567 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
6568 if (!NBody)
6569 return;
6570
6571 // Skip expensive checks if diagnostic is disabled.
6572 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
6573 DiagnosticsEngine::Ignored)
6574 return;
6575
6576 // Do the usual checks.
6577 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
6578 return;
6579
6580 // `for(...);' and `while(...);' are popular idioms, so in order to keep
6581 // noise level low, emit diagnostics only if for/while is followed by a
6582 // CompoundStmt, e.g.:
6583 // for (int i = 0; i < n; i++);
6584 // {
6585 // a(i);
6586 // }
6587 // or if for/while is followed by a statement with more indentation
6588 // than for/while itself:
6589 // for (int i = 0; i < n; i++);
6590 // a(i);
6591 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
6592 if (!ProbableTypo) {
6593 bool BodyColInvalid;
6594 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
6595 PossibleBody->getLocStart(),
6596 &BodyColInvalid);
6597 if (BodyColInvalid)
6598 return;
6599
6600 bool StmtColInvalid;
6601 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
6602 S->getLocStart(),
6603 &StmtColInvalid);
6604 if (StmtColInvalid)
6605 return;
6606
6607 if (BodyCol > StmtCol)
6608 ProbableTypo = true;
6609 }
6610
6611 if (ProbableTypo) {
6612 Diag(NBody->getSemiLoc(), DiagID);
6613 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
6614 }
6615}
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00006616
6617//===--- Layout compatibility ----------------------------------------------//
6618
6619namespace {
6620
6621bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
6622
6623/// \brief Check if two enumeration types are layout-compatible.
6624bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
6625 // C++11 [dcl.enum] p8:
6626 // Two enumeration types are layout-compatible if they have the same
6627 // underlying type.
6628 return ED1->isComplete() && ED2->isComplete() &&
6629 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
6630}
6631
6632/// \brief Check if two fields are layout-compatible.
6633bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
6634 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
6635 return false;
6636
6637 if (Field1->isBitField() != Field2->isBitField())
6638 return false;
6639
6640 if (Field1->isBitField()) {
6641 // Make sure that the bit-fields are the same length.
6642 unsigned Bits1 = Field1->getBitWidthValue(C);
6643 unsigned Bits2 = Field2->getBitWidthValue(C);
6644
6645 if (Bits1 != Bits2)
6646 return false;
6647 }
6648
6649 return true;
6650}
6651
6652/// \brief Check if two standard-layout structs are layout-compatible.
6653/// (C++11 [class.mem] p17)
6654bool isLayoutCompatibleStruct(ASTContext &C,
6655 RecordDecl *RD1,
6656 RecordDecl *RD2) {
6657 // If both records are C++ classes, check that base classes match.
6658 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
6659 // If one of records is a CXXRecordDecl we are in C++ mode,
6660 // thus the other one is a CXXRecordDecl, too.
6661 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
6662 // Check number of base classes.
6663 if (D1CXX->getNumBases() != D2CXX->getNumBases())
6664 return false;
6665
6666 // Check the base classes.
6667 for (CXXRecordDecl::base_class_const_iterator
6668 Base1 = D1CXX->bases_begin(),
6669 BaseEnd1 = D1CXX->bases_end(),
6670 Base2 = D2CXX->bases_begin();
6671 Base1 != BaseEnd1;
6672 ++Base1, ++Base2) {
6673 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
6674 return false;
6675 }
6676 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
6677 // If only RD2 is a C++ class, it should have zero base classes.
6678 if (D2CXX->getNumBases() > 0)
6679 return false;
6680 }
6681
6682 // Check the fields.
6683 RecordDecl::field_iterator Field2 = RD2->field_begin(),
6684 Field2End = RD2->field_end(),
6685 Field1 = RD1->field_begin(),
6686 Field1End = RD1->field_end();
6687 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
6688 if (!isLayoutCompatible(C, *Field1, *Field2))
6689 return false;
6690 }
6691 if (Field1 != Field1End || Field2 != Field2End)
6692 return false;
6693
6694 return true;
6695}
6696
6697/// \brief Check if two standard-layout unions are layout-compatible.
6698/// (C++11 [class.mem] p18)
6699bool isLayoutCompatibleUnion(ASTContext &C,
6700 RecordDecl *RD1,
6701 RecordDecl *RD2) {
6702 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
6703 for (RecordDecl::field_iterator Field2 = RD2->field_begin(),
6704 Field2End = RD2->field_end();
6705 Field2 != Field2End; ++Field2) {
6706 UnmatchedFields.insert(*Field2);
6707 }
6708
6709 for (RecordDecl::field_iterator Field1 = RD1->field_begin(),
6710 Field1End = RD1->field_end();
6711 Field1 != Field1End; ++Field1) {
6712 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
6713 I = UnmatchedFields.begin(),
6714 E = UnmatchedFields.end();
6715
6716 for ( ; I != E; ++I) {
6717 if (isLayoutCompatible(C, *Field1, *I)) {
6718 bool Result = UnmatchedFields.erase(*I);
6719 (void) Result;
6720 assert(Result);
6721 break;
6722 }
6723 }
6724 if (I == E)
6725 return false;
6726 }
6727
6728 return UnmatchedFields.empty();
6729}
6730
6731bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
6732 if (RD1->isUnion() != RD2->isUnion())
6733 return false;
6734
6735 if (RD1->isUnion())
6736 return isLayoutCompatibleUnion(C, RD1, RD2);
6737 else
6738 return isLayoutCompatibleStruct(C, RD1, RD2);
6739}
6740
6741/// \brief Check if two types are layout-compatible in C++11 sense.
6742bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
6743 if (T1.isNull() || T2.isNull())
6744 return false;
6745
6746 // C++11 [basic.types] p11:
6747 // If two types T1 and T2 are the same type, then T1 and T2 are
6748 // layout-compatible types.
6749 if (C.hasSameType(T1, T2))
6750 return true;
6751
6752 T1 = T1.getCanonicalType().getUnqualifiedType();
6753 T2 = T2.getCanonicalType().getUnqualifiedType();
6754
6755 const Type::TypeClass TC1 = T1->getTypeClass();
6756 const Type::TypeClass TC2 = T2->getTypeClass();
6757
6758 if (TC1 != TC2)
6759 return false;
6760
6761 if (TC1 == Type::Enum) {
6762 return isLayoutCompatible(C,
6763 cast<EnumType>(T1)->getDecl(),
6764 cast<EnumType>(T2)->getDecl());
6765 } else if (TC1 == Type::Record) {
6766 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
6767 return false;
6768
6769 return isLayoutCompatible(C,
6770 cast<RecordType>(T1)->getDecl(),
6771 cast<RecordType>(T2)->getDecl());
6772 }
6773
6774 return false;
6775}
6776}
6777
6778//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
6779
6780namespace {
6781/// \brief Given a type tag expression find the type tag itself.
6782///
6783/// \param TypeExpr Type tag expression, as it appears in user's code.
6784///
6785/// \param VD Declaration of an identifier that appears in a type tag.
6786///
6787/// \param MagicValue Type tag magic value.
6788bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
6789 const ValueDecl **VD, uint64_t *MagicValue) {
6790 while(true) {
6791 if (!TypeExpr)
6792 return false;
6793
6794 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
6795
6796 switch (TypeExpr->getStmtClass()) {
6797 case Stmt::UnaryOperatorClass: {
6798 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
6799 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
6800 TypeExpr = UO->getSubExpr();
6801 continue;
6802 }
6803 return false;
6804 }
6805
6806 case Stmt::DeclRefExprClass: {
6807 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
6808 *VD = DRE->getDecl();
6809 return true;
6810 }
6811
6812 case Stmt::IntegerLiteralClass: {
6813 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
6814 llvm::APInt MagicValueAPInt = IL->getValue();
6815 if (MagicValueAPInt.getActiveBits() <= 64) {
6816 *MagicValue = MagicValueAPInt.getZExtValue();
6817 return true;
6818 } else
6819 return false;
6820 }
6821
6822 case Stmt::BinaryConditionalOperatorClass:
6823 case Stmt::ConditionalOperatorClass: {
6824 const AbstractConditionalOperator *ACO =
6825 cast<AbstractConditionalOperator>(TypeExpr);
6826 bool Result;
6827 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
6828 if (Result)
6829 TypeExpr = ACO->getTrueExpr();
6830 else
6831 TypeExpr = ACO->getFalseExpr();
6832 continue;
6833 }
6834 return false;
6835 }
6836
6837 case Stmt::BinaryOperatorClass: {
6838 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
6839 if (BO->getOpcode() == BO_Comma) {
6840 TypeExpr = BO->getRHS();
6841 continue;
6842 }
6843 return false;
6844 }
6845
6846 default:
6847 return false;
6848 }
6849 }
6850}
6851
6852/// \brief Retrieve the C type corresponding to type tag TypeExpr.
6853///
6854/// \param TypeExpr Expression that specifies a type tag.
6855///
6856/// \param MagicValues Registered magic values.
6857///
6858/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
6859/// kind.
6860///
6861/// \param TypeInfo Information about the corresponding C type.
6862///
6863/// \returns true if the corresponding C type was found.
6864bool GetMatchingCType(
6865 const IdentifierInfo *ArgumentKind,
6866 const Expr *TypeExpr, const ASTContext &Ctx,
6867 const llvm::DenseMap<Sema::TypeTagMagicValue,
6868 Sema::TypeTagData> *MagicValues,
6869 bool &FoundWrongKind,
6870 Sema::TypeTagData &TypeInfo) {
6871 FoundWrongKind = false;
6872
6873 // Variable declaration that has type_tag_for_datatype attribute.
6874 const ValueDecl *VD = NULL;
6875
6876 uint64_t MagicValue;
6877
6878 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
6879 return false;
6880
6881 if (VD) {
6882 for (specific_attr_iterator<TypeTagForDatatypeAttr>
6883 I = VD->specific_attr_begin<TypeTagForDatatypeAttr>(),
6884 E = VD->specific_attr_end<TypeTagForDatatypeAttr>();
6885 I != E; ++I) {
6886 if (I->getArgumentKind() != ArgumentKind) {
6887 FoundWrongKind = true;
6888 return false;
6889 }
6890 TypeInfo.Type = I->getMatchingCType();
6891 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
6892 TypeInfo.MustBeNull = I->getMustBeNull();
6893 return true;
6894 }
6895 return false;
6896 }
6897
6898 if (!MagicValues)
6899 return false;
6900
6901 llvm::DenseMap<Sema::TypeTagMagicValue,
6902 Sema::TypeTagData>::const_iterator I =
6903 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
6904 if (I == MagicValues->end())
6905 return false;
6906
6907 TypeInfo = I->second;
6908 return true;
6909}
6910} // unnamed namespace
6911
6912void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
6913 uint64_t MagicValue, QualType Type,
6914 bool LayoutCompatible,
6915 bool MustBeNull) {
6916 if (!TypeTagForDatatypeMagicValues)
6917 TypeTagForDatatypeMagicValues.reset(
6918 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
6919
6920 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
6921 (*TypeTagForDatatypeMagicValues)[Magic] =
6922 TypeTagData(Type, LayoutCompatible, MustBeNull);
6923}
6924
6925namespace {
6926bool IsSameCharType(QualType T1, QualType T2) {
6927 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
6928 if (!BT1)
6929 return false;
6930
6931 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
6932 if (!BT2)
6933 return false;
6934
6935 BuiltinType::Kind T1Kind = BT1->getKind();
6936 BuiltinType::Kind T2Kind = BT2->getKind();
6937
6938 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
6939 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
6940 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
6941 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
6942}
6943} // unnamed namespace
6944
6945void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
6946 const Expr * const *ExprArgs) {
6947 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
6948 bool IsPointerAttr = Attr->getIsPointer();
6949
6950 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
6951 bool FoundWrongKind;
6952 TypeTagData TypeInfo;
6953 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
6954 TypeTagForDatatypeMagicValues.get(),
6955 FoundWrongKind, TypeInfo)) {
6956 if (FoundWrongKind)
6957 Diag(TypeTagExpr->getExprLoc(),
6958 diag::warn_type_tag_for_datatype_wrong_kind)
6959 << TypeTagExpr->getSourceRange();
6960 return;
6961 }
6962
6963 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
6964 if (IsPointerAttr) {
6965 // Skip implicit cast of pointer to `void *' (as a function argument).
6966 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5a249802012-11-03 16:07:49 +00006967 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkob57ce4e2012-11-03 22:10:18 +00006968 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00006969 ArgumentExpr = ICE->getSubExpr();
6970 }
6971 QualType ArgumentType = ArgumentExpr->getType();
6972
6973 // Passing a `void*' pointer shouldn't trigger a warning.
6974 if (IsPointerAttr && ArgumentType->isVoidPointerType())
6975 return;
6976
6977 if (TypeInfo.MustBeNull) {
6978 // Type tag with matching void type requires a null pointer.
6979 if (!ArgumentExpr->isNullPointerConstant(Context,
6980 Expr::NPC_ValueDependentIsNotNull)) {
6981 Diag(ArgumentExpr->getExprLoc(),
6982 diag::warn_type_safety_null_pointer_required)
6983 << ArgumentKind->getName()
6984 << ArgumentExpr->getSourceRange()
6985 << TypeTagExpr->getSourceRange();
6986 }
6987 return;
6988 }
6989
6990 QualType RequiredType = TypeInfo.Type;
6991 if (IsPointerAttr)
6992 RequiredType = Context.getPointerType(RequiredType);
6993
6994 bool mismatch = false;
6995 if (!TypeInfo.LayoutCompatible) {
6996 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
6997
6998 // C++11 [basic.fundamental] p1:
6999 // Plain char, signed char, and unsigned char are three distinct types.
7000 //
7001 // But we treat plain `char' as equivalent to `signed char' or `unsigned
7002 // char' depending on the current char signedness mode.
7003 if (mismatch)
7004 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
7005 RequiredType->getPointeeType())) ||
7006 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
7007 mismatch = false;
7008 } else
7009 if (IsPointerAttr)
7010 mismatch = !isLayoutCompatible(Context,
7011 ArgumentType->getPointeeType(),
7012 RequiredType->getPointeeType());
7013 else
7014 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
7015
7016 if (mismatch)
7017 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
7018 << ArgumentType << ArgumentKind->getName()
7019 << TypeInfo.LayoutCompatible << RequiredType
7020 << ArgumentExpr->getSourceRange()
7021 << TypeTagExpr->getSourceRange();
7022}