blob: 7498d348920404ae6db437921c8ae3a74bdb5666 [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 McCall5f8d6042011-08-27 01:09:30 +000015#include "clang/Sema/Initialization.h"
Douglas Gregore737f502010-08-12 20:07:10 +000016#include "clang/Sema/Sema.h"
John McCall2d887082010-08-25 22:03:47 +000017#include "clang/Sema/SemaInternal.h"
Eli Friedman276b0612011-10-11 02:20:01 +000018#include "clang/Sema/Initialization.h"
Richard Smith831421f2012-06-25 20:30:08 +000019#include "clang/Sema/Lookup.h"
John McCall781472f2010-08-25 08:40:02 +000020#include "clang/Sema/ScopeInfo.h"
Ted Kremenek826a3452010-07-16 02:11:22 +000021#include "clang/Analysis/Analyses/FormatString.h"
Chris Lattner59907c42007-08-10 20:18:51 +000022#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000023#include "clang/AST/CharUnits.h"
John McCall384aff82010-08-25 07:42:41 +000024#include "clang/AST/DeclCXX.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000025#include "clang/AST/DeclObjC.h"
David Blaikiebe0ee872012-05-15 16:56:36 +000026#include "clang/AST/Expr.h"
Ted Kremenek23245122007-08-20 16:18:38 +000027#include "clang/AST/ExprCXX.h"
Ted Kremenek7ff22b22008-06-16 18:00:42 +000028#include "clang/AST/ExprObjC.h"
John McCallf85e1932011-06-15 23:02:42 +000029#include "clang/AST/EvaluatedExprVisitor.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000030#include "clang/AST/DeclObjC.h"
31#include "clang/AST/StmtCXX.h"
32#include "clang/AST/StmtObjC.h"
Chris Lattner59907c42007-08-10 20:18:51 +000033#include "clang/Lex/Preprocessor.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000034#include "llvm/ADT/BitVector.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000035#include "llvm/ADT/SmallString.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000036#include "llvm/ADT/STLExtras.h"
Tom Care3bfc5f42010-06-09 04:11:11 +000037#include "llvm/Support/raw_ostream.h"
Eric Christopher691ebc32010-04-17 02:26:23 +000038#include "clang/Basic/TargetBuiltins.h"
Nate Begeman26a31422010-06-08 02:47:44 +000039#include "clang/Basic/TargetInfo.h"
Fariborz Jahanian7da71022010-09-07 19:38:13 +000040#include "clang/Basic/ConvertUTF.h"
Zhongxing Xua1f3dba2009-05-20 01:55:10 +000041#include <limits>
Chris Lattner59907c42007-08-10 20:18:51 +000042using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000043using namespace sema;
Chris Lattner59907c42007-08-10 20:18:51 +000044
Chris Lattner60800082009-02-18 17:49:48 +000045SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
46 unsigned ByteNo) const {
Chris Lattner08f92e32010-11-17 07:37:15 +000047 return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +000048 PP.getLangOpts(), PP.getTargetInfo());
Chris Lattner60800082009-02-18 17:49:48 +000049}
50
John McCall8e10f3b2011-02-26 05:39:39 +000051/// Checks that a call expression's argument count is the desired number.
52/// This is useful when doing custom type-checking. Returns true on error.
53static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
54 unsigned argCount = call->getNumArgs();
55 if (argCount == desiredArgCount) return false;
56
57 if (argCount < desiredArgCount)
58 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
59 << 0 /*function call*/ << desiredArgCount << argCount
60 << call->getSourceRange();
61
62 // Highlight all the excess arguments.
63 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
64 call->getArg(argCount - 1)->getLocEnd());
65
66 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
67 << 0 /*function call*/ << desiredArgCount << argCount
68 << call->getArg(1)->getSourceRange();
69}
70
Julien Lerougee5939212012-04-28 17:39:16 +000071/// Check that the first argument to __builtin_annotation is an integer
72/// and the second argument is a non-wide string literal.
73static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
74 if (checkArgCount(S, TheCall, 2))
75 return true;
76
77 // First argument should be an integer.
78 Expr *ValArg = TheCall->getArg(0);
79 QualType Ty = ValArg->getType();
80 if (!Ty->isIntegerType()) {
81 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
82 << ValArg->getSourceRange();
Julien Lerouge77f68bb2011-09-09 22:41:49 +000083 return true;
84 }
Julien Lerougee5939212012-04-28 17:39:16 +000085
86 // Second argument should be a constant string.
87 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
88 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
89 if (!Literal || !Literal->isAscii()) {
90 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
91 << StrArg->getSourceRange();
92 return true;
93 }
94
95 TheCall->setType(Ty);
Julien Lerouge77f68bb2011-09-09 22:41:49 +000096 return false;
97}
98
John McCall60d7b3a2010-08-24 06:29:42 +000099ExprResult
Anders Carlssond406bf02009-08-16 01:56:34 +0000100Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
John McCall60d7b3a2010-08-24 06:29:42 +0000101 ExprResult TheCallResult(Owned(TheCall));
Douglas Gregor2def4832008-11-17 20:34:05 +0000102
Chris Lattner946928f2010-10-01 23:23:24 +0000103 // Find out if any arguments are required to be integer constant expressions.
104 unsigned ICEArguments = 0;
105 ASTContext::GetBuiltinTypeError Error;
106 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
107 if (Error != ASTContext::GE_None)
108 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
109
110 // If any arguments are required to be ICE's, check and diagnose.
111 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
112 // Skip arguments not required to be ICE's.
113 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
114
115 llvm::APSInt Result;
116 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
117 return true;
118 ICEArguments &= ~(1 << ArgNo);
119 }
120
Anders Carlssond406bf02009-08-16 01:56:34 +0000121 switch (BuiltinID) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000122 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000123 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000124 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000125 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000126 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000127 break;
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000128 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000129 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000130 if (SemaBuiltinVAStart(TheCall))
131 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000132 break;
Chris Lattner1b9a0792007-12-20 00:26:33 +0000133 case Builtin::BI__builtin_isgreater:
134 case Builtin::BI__builtin_isgreaterequal:
135 case Builtin::BI__builtin_isless:
136 case Builtin::BI__builtin_islessequal:
137 case Builtin::BI__builtin_islessgreater:
138 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000139 if (SemaBuiltinUnorderedCompare(TheCall))
140 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000141 break;
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000142 case Builtin::BI__builtin_fpclassify:
143 if (SemaBuiltinFPClassification(TheCall, 6))
144 return ExprError();
145 break;
Eli Friedman9ac6f622009-08-31 20:06:00 +0000146 case Builtin::BI__builtin_isfinite:
147 case Builtin::BI__builtin_isinf:
148 case Builtin::BI__builtin_isinf_sign:
149 case Builtin::BI__builtin_isnan:
150 case Builtin::BI__builtin_isnormal:
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000151 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman9ac6f622009-08-31 20:06:00 +0000152 return ExprError();
153 break;
Eli Friedmand38617c2008-05-14 19:38:39 +0000154 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000155 return SemaBuiltinShuffleVector(TheCall);
156 // TheCall will be freed by the smart pointer here, but that's fine, since
157 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000158 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000159 if (SemaBuiltinPrefetch(TheCall))
160 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000161 break;
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000162 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000163 if (SemaBuiltinObjectSize(TheCall))
164 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000165 break;
Eli Friedmand875fed2009-05-03 04:46:36 +0000166 case Builtin::BI__builtin_longjmp:
167 if (SemaBuiltinLongjmp(TheCall))
168 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000169 break;
John McCall8e10f3b2011-02-26 05:39:39 +0000170
171 case Builtin::BI__builtin_classify_type:
172 if (checkArgCount(*this, TheCall, 1)) return true;
173 TheCall->setType(Context.IntTy);
174 break;
Chris Lattner75c29a02010-10-12 17:47:42 +0000175 case Builtin::BI__builtin_constant_p:
John McCall8e10f3b2011-02-26 05:39:39 +0000176 if (checkArgCount(*this, TheCall, 1)) return true;
177 TheCall->setType(Context.IntTy);
Chris Lattner75c29a02010-10-12 17:47:42 +0000178 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000179 case Builtin::BI__sync_fetch_and_add:
Douglas Gregora9766412011-11-28 16:30:08 +0000180 case Builtin::BI__sync_fetch_and_add_1:
181 case Builtin::BI__sync_fetch_and_add_2:
182 case Builtin::BI__sync_fetch_and_add_4:
183 case Builtin::BI__sync_fetch_and_add_8:
184 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000185 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregora9766412011-11-28 16:30:08 +0000186 case Builtin::BI__sync_fetch_and_sub_1:
187 case Builtin::BI__sync_fetch_and_sub_2:
188 case Builtin::BI__sync_fetch_and_sub_4:
189 case Builtin::BI__sync_fetch_and_sub_8:
190 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000191 case Builtin::BI__sync_fetch_and_or:
Douglas Gregora9766412011-11-28 16:30:08 +0000192 case Builtin::BI__sync_fetch_and_or_1:
193 case Builtin::BI__sync_fetch_and_or_2:
194 case Builtin::BI__sync_fetch_and_or_4:
195 case Builtin::BI__sync_fetch_and_or_8:
196 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000197 case Builtin::BI__sync_fetch_and_and:
Douglas Gregora9766412011-11-28 16:30:08 +0000198 case Builtin::BI__sync_fetch_and_and_1:
199 case Builtin::BI__sync_fetch_and_and_2:
200 case Builtin::BI__sync_fetch_and_and_4:
201 case Builtin::BI__sync_fetch_and_and_8:
202 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000203 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregora9766412011-11-28 16:30:08 +0000204 case Builtin::BI__sync_fetch_and_xor_1:
205 case Builtin::BI__sync_fetch_and_xor_2:
206 case Builtin::BI__sync_fetch_and_xor_4:
207 case Builtin::BI__sync_fetch_and_xor_8:
208 case Builtin::BI__sync_fetch_and_xor_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000209 case Builtin::BI__sync_add_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000210 case Builtin::BI__sync_add_and_fetch_1:
211 case Builtin::BI__sync_add_and_fetch_2:
212 case Builtin::BI__sync_add_and_fetch_4:
213 case Builtin::BI__sync_add_and_fetch_8:
214 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000215 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000216 case Builtin::BI__sync_sub_and_fetch_1:
217 case Builtin::BI__sync_sub_and_fetch_2:
218 case Builtin::BI__sync_sub_and_fetch_4:
219 case Builtin::BI__sync_sub_and_fetch_8:
220 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000221 case Builtin::BI__sync_and_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000222 case Builtin::BI__sync_and_and_fetch_1:
223 case Builtin::BI__sync_and_and_fetch_2:
224 case Builtin::BI__sync_and_and_fetch_4:
225 case Builtin::BI__sync_and_and_fetch_8:
226 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000227 case Builtin::BI__sync_or_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000228 case Builtin::BI__sync_or_and_fetch_1:
229 case Builtin::BI__sync_or_and_fetch_2:
230 case Builtin::BI__sync_or_and_fetch_4:
231 case Builtin::BI__sync_or_and_fetch_8:
232 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000233 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000234 case Builtin::BI__sync_xor_and_fetch_1:
235 case Builtin::BI__sync_xor_and_fetch_2:
236 case Builtin::BI__sync_xor_and_fetch_4:
237 case Builtin::BI__sync_xor_and_fetch_8:
238 case Builtin::BI__sync_xor_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000239 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000240 case Builtin::BI__sync_val_compare_and_swap_1:
241 case Builtin::BI__sync_val_compare_and_swap_2:
242 case Builtin::BI__sync_val_compare_and_swap_4:
243 case Builtin::BI__sync_val_compare_and_swap_8:
244 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000245 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000246 case Builtin::BI__sync_bool_compare_and_swap_1:
247 case Builtin::BI__sync_bool_compare_and_swap_2:
248 case Builtin::BI__sync_bool_compare_and_swap_4:
249 case Builtin::BI__sync_bool_compare_and_swap_8:
250 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000251 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregora9766412011-11-28 16:30:08 +0000252 case Builtin::BI__sync_lock_test_and_set_1:
253 case Builtin::BI__sync_lock_test_and_set_2:
254 case Builtin::BI__sync_lock_test_and_set_4:
255 case Builtin::BI__sync_lock_test_and_set_8:
256 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000257 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +0000258 case Builtin::BI__sync_lock_release_1:
259 case Builtin::BI__sync_lock_release_2:
260 case Builtin::BI__sync_lock_release_4:
261 case Builtin::BI__sync_lock_release_8:
262 case Builtin::BI__sync_lock_release_16:
Chris Lattner23aa9c82011-04-09 03:57:26 +0000263 case Builtin::BI__sync_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000264 case Builtin::BI__sync_swap_1:
265 case Builtin::BI__sync_swap_2:
266 case Builtin::BI__sync_swap_4:
267 case Builtin::BI__sync_swap_8:
268 case Builtin::BI__sync_swap_16:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000269 return SemaBuiltinAtomicOverloaded(TheCallResult);
Richard Smithff34d402012-04-12 05:08:17 +0000270#define BUILTIN(ID, TYPE, ATTRS)
271#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
272 case Builtin::BI##ID: \
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000273 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithff34d402012-04-12 05:08:17 +0000274#include "clang/Basic/Builtins.def"
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000275 case Builtin::BI__builtin_annotation:
Julien Lerougee5939212012-04-28 17:39:16 +0000276 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000277 return ExprError();
278 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000279 }
280
281 // Since the target specific builtins for each arch overlap, only check those
282 // of the arch we are compiling for.
283 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000284 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman26a31422010-06-08 02:47:44 +0000285 case llvm::Triple::arm:
286 case llvm::Triple::thumb:
287 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
288 return ExprError();
289 break;
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000290 case llvm::Triple::mips:
291 case llvm::Triple::mipsel:
292 case llvm::Triple::mips64:
293 case llvm::Triple::mips64el:
294 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
295 return ExprError();
296 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000297 default:
298 break;
299 }
300 }
301
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000302 return TheCallResult;
Nate Begeman26a31422010-06-08 02:47:44 +0000303}
304
Nate Begeman61eecf52010-06-14 05:21:25 +0000305// Get the valid immediate range for the specified NEON type code.
306static unsigned RFT(unsigned t, bool shift = false) {
Bob Wilsonda95f732011-11-08 01:16:11 +0000307 NeonTypeFlags Type(t);
308 int IsQuad = Type.isQuad();
309 switch (Type.getEltType()) {
310 case NeonTypeFlags::Int8:
311 case NeonTypeFlags::Poly8:
312 return shift ? 7 : (8 << IsQuad) - 1;
313 case NeonTypeFlags::Int16:
314 case NeonTypeFlags::Poly16:
315 return shift ? 15 : (4 << IsQuad) - 1;
316 case NeonTypeFlags::Int32:
317 return shift ? 31 : (2 << IsQuad) - 1;
318 case NeonTypeFlags::Int64:
319 return shift ? 63 : (1 << IsQuad) - 1;
320 case NeonTypeFlags::Float16:
321 assert(!shift && "cannot shift float types!");
322 return (4 << IsQuad) - 1;
323 case NeonTypeFlags::Float32:
324 assert(!shift && "cannot shift float types!");
325 return (2 << IsQuad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000326 }
David Blaikie7530c032012-01-17 06:56:22 +0000327 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman61eecf52010-06-14 05:21:25 +0000328}
329
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000330/// getNeonEltType - Return the QualType corresponding to the elements of
331/// the vector type specified by the NeonTypeFlags. This is used to check
332/// the pointer arguments for Neon load/store intrinsics.
333static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context) {
334 switch (Flags.getEltType()) {
335 case NeonTypeFlags::Int8:
336 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
337 case NeonTypeFlags::Int16:
338 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
339 case NeonTypeFlags::Int32:
340 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
341 case NeonTypeFlags::Int64:
342 return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy;
343 case NeonTypeFlags::Poly8:
344 return Context.SignedCharTy;
345 case NeonTypeFlags::Poly16:
346 return Context.ShortTy;
347 case NeonTypeFlags::Float16:
348 return Context.UnsignedShortTy;
349 case NeonTypeFlags::Float32:
350 return Context.FloatTy;
351 }
David Blaikie7530c032012-01-17 06:56:22 +0000352 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000353}
354
Nate Begeman26a31422010-06-08 02:47:44 +0000355bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000356 llvm::APSInt Result;
357
Richard Smithf8ee6bc2012-08-14 01:28:02 +0000358 uint64_t mask = 0;
Nate Begeman61eecf52010-06-14 05:21:25 +0000359 unsigned TV = 0;
Bob Wilson46482552011-11-16 21:32:23 +0000360 int PtrArgNum = -1;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000361 bool HasConstPtr = false;
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000362 switch (BuiltinID) {
Nate Begemana23326b2010-06-17 04:17:01 +0000363#define GET_NEON_OVERLOAD_CHECK
364#include "clang/Basic/arm_neon.inc"
365#undef GET_NEON_OVERLOAD_CHECK
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000366 }
367
Nate Begeman0d15c532010-06-13 04:47:52 +0000368 // For NEON intrinsics which are overloaded on vector element type, validate
369 // the immediate which specifies which variant to emit.
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000370 unsigned ImmArg = TheCall->getNumArgs()-1;
Nate Begeman0d15c532010-06-13 04:47:52 +0000371 if (mask) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000372 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
Nate Begeman0d15c532010-06-13 04:47:52 +0000373 return true;
374
Bob Wilsonda95f732011-11-08 01:16:11 +0000375 TV = Result.getLimitedValue(64);
Richard Smithf8ee6bc2012-08-14 01:28:02 +0000376 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
Nate Begeman0d15c532010-06-13 04:47:52 +0000377 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000378 << TheCall->getArg(ImmArg)->getSourceRange();
379 }
380
Bob Wilson46482552011-11-16 21:32:23 +0000381 if (PtrArgNum >= 0) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000382 // Check that pointer arguments have the specified type.
Bob Wilson46482552011-11-16 21:32:23 +0000383 Expr *Arg = TheCall->getArg(PtrArgNum);
384 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
385 Arg = ICE->getSubExpr();
386 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
387 QualType RHSTy = RHS.get()->getType();
388 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context);
389 if (HasConstPtr)
390 EltTy = EltTy.withConst();
391 QualType LHSTy = Context.getPointerType(EltTy);
392 AssignConvertType ConvTy;
393 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
394 if (RHS.isInvalid())
395 return true;
396 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
397 RHS.get(), AA_Assigning))
398 return true;
Nate Begeman0d15c532010-06-13 04:47:52 +0000399 }
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000400
Nate Begeman0d15c532010-06-13 04:47:52 +0000401 // For NEON intrinsics which take an immediate value as part of the
402 // instruction, range check them here.
Nate Begeman61eecf52010-06-14 05:21:25 +0000403 unsigned i = 0, l = 0, u = 0;
Nate Begeman0d15c532010-06-13 04:47:52 +0000404 switch (BuiltinID) {
405 default: return false;
Nate Begemanbb37f502010-07-29 22:48:34 +0000406 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
407 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begeman99c40bb2010-08-03 21:32:34 +0000408 case ARM::BI__builtin_arm_vcvtr_f:
409 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Nate Begemana23326b2010-06-17 04:17:01 +0000410#define GET_NEON_IMMEDIATE_CHECK
411#include "clang/Basic/arm_neon.inc"
412#undef GET_NEON_IMMEDIATE_CHECK
Nate Begeman0d15c532010-06-13 04:47:52 +0000413 };
414
Douglas Gregor592a4232012-06-29 01:05:22 +0000415 // We can't check the value of a dependent argument.
416 if (TheCall->getArg(i)->isTypeDependent() ||
417 TheCall->getArg(i)->isValueDependent())
418 return false;
419
Nate Begeman61eecf52010-06-14 05:21:25 +0000420 // Check that the immediate argument is actually a constant.
Nate Begeman0d15c532010-06-13 04:47:52 +0000421 if (SemaBuiltinConstantArg(TheCall, i, Result))
422 return true;
423
Nate Begeman61eecf52010-06-14 05:21:25 +0000424 // Range check against the upper/lower values for this isntruction.
Nate Begeman0d15c532010-06-13 04:47:52 +0000425 unsigned Val = Result.getZExtValue();
Nate Begeman61eecf52010-06-14 05:21:25 +0000426 if (Val < l || Val > (u + l))
Nate Begeman0d15c532010-06-13 04:47:52 +0000427 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramer476d8b82010-08-11 14:47:12 +0000428 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begeman0d15c532010-06-13 04:47:52 +0000429
Nate Begeman99c40bb2010-08-03 21:32:34 +0000430 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman26a31422010-06-08 02:47:44 +0000431 return false;
Anders Carlssond406bf02009-08-16 01:56:34 +0000432}
Daniel Dunbarde454282008-10-02 18:44:07 +0000433
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000434bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
435 unsigned i = 0, l = 0, u = 0;
436 switch (BuiltinID) {
437 default: return false;
438 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
439 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyanbe22cb82012-08-27 12:29:20 +0000440 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
441 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
442 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
443 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
444 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000445 };
446
447 // We can't check the value of a dependent argument.
448 if (TheCall->getArg(i)->isTypeDependent() ||
449 TheCall->getArg(i)->isValueDependent())
450 return false;
451
452 // Check that the immediate argument is actually a constant.
453 llvm::APSInt Result;
454 if (SemaBuiltinConstantArg(TheCall, i, Result))
455 return true;
456
457 // Range check against the upper/lower values for this instruction.
458 unsigned Val = Result.getZExtValue();
459 if (Val < l || Val > u)
460 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
461 << l << u << TheCall->getArg(i)->getSourceRange();
462
463 return false;
464}
465
Richard Smith831421f2012-06-25 20:30:08 +0000466/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
467/// parameter with the FormatAttr's correct format_idx and firstDataArg.
468/// Returns true when the format fits the function and the FormatStringInfo has
469/// been populated.
470bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
471 FormatStringInfo *FSI) {
472 FSI->HasVAListArg = Format->getFirstArg() == 0;
473 FSI->FormatIdx = Format->getFormatIdx() - 1;
474 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssond406bf02009-08-16 01:56:34 +0000475
Richard Smith831421f2012-06-25 20:30:08 +0000476 // The way the format attribute works in GCC, the implicit this argument
477 // of member functions is counted. However, it doesn't appear in our own
478 // lists, so decrement format_idx in that case.
479 if (IsCXXMember) {
480 if(FSI->FormatIdx == 0)
481 return false;
482 --FSI->FormatIdx;
483 if (FSI->FirstDataArg != 0)
484 --FSI->FirstDataArg;
485 }
486 return true;
487}
Mike Stump1eb44332009-09-09 15:08:12 +0000488
Richard Smith831421f2012-06-25 20:30:08 +0000489/// Handles the checks for format strings, non-POD arguments to vararg
490/// functions, and NULL arguments passed to non-NULL parameters.
491void Sema::checkCall(NamedDecl *FDecl, Expr **Args,
492 unsigned NumArgs,
493 unsigned NumProtoArgs,
494 bool IsMemberFunction,
495 SourceLocation Loc,
496 SourceRange Range,
497 VariadicCallType CallType) {
Jordan Rose66360e22012-10-02 01:49:54 +0000498 if (CurContext->isDependentContext())
499 return;
Daniel Dunbarde454282008-10-02 18:44:07 +0000500
Ted Kremenekc82faca2010-09-09 04:33:05 +0000501 // Printf and scanf checking.
Richard Smith831421f2012-06-25 20:30:08 +0000502 bool HandledFormatString = false;
Ted Kremenekc82faca2010-09-09 04:33:05 +0000503 for (specific_attr_iterator<FormatAttr>
Richard Smith831421f2012-06-25 20:30:08 +0000504 I = FDecl->specific_attr_begin<FormatAttr>(),
505 E = FDecl->specific_attr_end<FormatAttr>(); I != E ; ++I)
Jordan Roseddcfbc92012-07-19 18:10:23 +0000506 if (CheckFormatArguments(*I, Args, NumArgs, IsMemberFunction, CallType,
507 Loc, Range))
Richard Smith831421f2012-06-25 20:30:08 +0000508 HandledFormatString = true;
509
510 // Refuse POD arguments that weren't caught by the format string
511 // checks above.
512 if (!HandledFormatString && CallType != VariadicDoesNotApply)
513 for (unsigned ArgIdx = NumProtoArgs; ArgIdx < NumArgs; ++ArgIdx)
514 variadicArgumentPODCheck(Args[ArgIdx], CallType);
Mike Stump1eb44332009-09-09 15:08:12 +0000515
Ted Kremenekc82faca2010-09-09 04:33:05 +0000516 for (specific_attr_iterator<NonNullAttr>
Richard Smith831421f2012-06-25 20:30:08 +0000517 I = FDecl->specific_attr_begin<NonNullAttr>(),
518 E = FDecl->specific_attr_end<NonNullAttr>(); I != E; ++I)
519 CheckNonNullArguments(*I, Args, Loc);
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +0000520
521 // Type safety checking.
522 for (specific_attr_iterator<ArgumentWithTypeTagAttr>
523 i = FDecl->specific_attr_begin<ArgumentWithTypeTagAttr>(),
524 e = FDecl->specific_attr_end<ArgumentWithTypeTagAttr>(); i != e; ++i) {
525 CheckArgumentWithTypeTag(*i, Args);
526 }
Richard Smith831421f2012-06-25 20:30:08 +0000527}
528
529/// CheckConstructorCall - Check a constructor call for correctness and safety
530/// properties not enforced by the C type system.
531void Sema::CheckConstructorCall(FunctionDecl *FDecl, Expr **Args,
532 unsigned NumArgs,
533 const FunctionProtoType *Proto,
534 SourceLocation Loc) {
535 VariadicCallType CallType =
536 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
537 checkCall(FDecl, Args, NumArgs, Proto->getNumArgs(),
538 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
539}
540
541/// CheckFunctionCall - Check a direct function call for various correctness
542/// and safety properties not strictly enforced by the C type system.
543bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
544 const FunctionProtoType *Proto) {
545 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall);
546 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
547 TheCall->getCallee());
548 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
549 checkCall(FDecl, TheCall->getArgs(), TheCall->getNumArgs(), NumProtoArgs,
550 IsMemberFunction, TheCall->getRParenLoc(),
551 TheCall->getCallee()->getSourceRange(), CallType);
552
553 IdentifierInfo *FnInfo = FDecl->getIdentifier();
554 // None of the checks below are needed for functions that don't have
555 // simple names (e.g., C++ conversion functions).
556 if (!FnInfo)
557 return false;
Sebastian Redl0eb23302009-01-19 00:08:26 +0000558
Anna Zaks0a151a12012-01-17 00:37:07 +0000559 unsigned CMId = FDecl->getMemoryFunctionKind();
560 if (CMId == 0)
Anna Zaksd9b859a2012-01-13 21:52:01 +0000561 return false;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000562
Anna Zaksd9b859a2012-01-13 21:52:01 +0000563 // Handle memory setting and copying functions.
Anna Zaks0a151a12012-01-17 00:37:07 +0000564 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000565 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaksc36bedc2012-02-01 19:08:57 +0000566 else if (CMId == Builtin::BIstrncat)
567 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaksd9b859a2012-01-13 21:52:01 +0000568 else
Anna Zaks0a151a12012-01-17 00:37:07 +0000569 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth7ccc95b2011-04-27 07:05:31 +0000570
Anders Carlssond406bf02009-08-16 01:56:34 +0000571 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000572}
573
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000574bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
575 Expr **Args, unsigned NumArgs) {
Richard Smith831421f2012-06-25 20:30:08 +0000576 VariadicCallType CallType =
577 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000578
Richard Smith831421f2012-06-25 20:30:08 +0000579 checkCall(Method, Args, NumArgs, Method->param_size(),
580 /*IsMemberFunction=*/false,
581 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000582
583 return false;
584}
585
Richard Smith831421f2012-06-25 20:30:08 +0000586bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall,
587 const FunctionProtoType *Proto) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000588 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
589 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000590 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000591
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000592 QualType Ty = V->getType();
593 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000594 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000595
Richard Smith831421f2012-06-25 20:30:08 +0000596 VariadicCallType CallType =
597 Proto && Proto->isVariadic() ? VariadicBlock : VariadicDoesNotApply ;
598 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
Anders Carlssond406bf02009-08-16 01:56:34 +0000599
Richard Smith831421f2012-06-25 20:30:08 +0000600 checkCall(NDecl, TheCall->getArgs(), TheCall->getNumArgs(),
601 NumProtoArgs, /*IsMemberFunction=*/false,
602 TheCall->getRParenLoc(),
603 TheCall->getCallee()->getSourceRange(), CallType);
604
Anders Carlssond406bf02009-08-16 01:56:34 +0000605 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000606}
607
Richard Smithff34d402012-04-12 05:08:17 +0000608ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
609 AtomicExpr::AtomicOp Op) {
Eli Friedman276b0612011-10-11 02:20:01 +0000610 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
611 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedman276b0612011-10-11 02:20:01 +0000612
Richard Smithff34d402012-04-12 05:08:17 +0000613 // All these operations take one of the following forms:
614 enum {
615 // C __c11_atomic_init(A *, C)
616 Init,
617 // C __c11_atomic_load(A *, int)
618 Load,
619 // void __atomic_load(A *, CP, int)
620 Copy,
621 // C __c11_atomic_add(A *, M, int)
622 Arithmetic,
623 // C __atomic_exchange_n(A *, CP, int)
624 Xchg,
625 // void __atomic_exchange(A *, C *, CP, int)
626 GNUXchg,
627 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
628 C11CmpXchg,
629 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
630 GNUCmpXchg
631 } Form = Init;
632 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
633 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
634 // where:
635 // C is an appropriate type,
636 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
637 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
638 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
639 // the int parameters are for orderings.
Eli Friedman276b0612011-10-11 02:20:01 +0000640
Richard Smithff34d402012-04-12 05:08:17 +0000641 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
642 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
643 && "need to update code for modified C11 atomics");
644 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
645 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
646 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
647 Op == AtomicExpr::AO__atomic_store_n ||
648 Op == AtomicExpr::AO__atomic_exchange_n ||
649 Op == AtomicExpr::AO__atomic_compare_exchange_n;
650 bool IsAddSub = false;
651
652 switch (Op) {
653 case AtomicExpr::AO__c11_atomic_init:
654 Form = Init;
655 break;
656
657 case AtomicExpr::AO__c11_atomic_load:
658 case AtomicExpr::AO__atomic_load_n:
659 Form = Load;
660 break;
661
662 case AtomicExpr::AO__c11_atomic_store:
663 case AtomicExpr::AO__atomic_load:
664 case AtomicExpr::AO__atomic_store:
665 case AtomicExpr::AO__atomic_store_n:
666 Form = Copy;
667 break;
668
669 case AtomicExpr::AO__c11_atomic_fetch_add:
670 case AtomicExpr::AO__c11_atomic_fetch_sub:
671 case AtomicExpr::AO__atomic_fetch_add:
672 case AtomicExpr::AO__atomic_fetch_sub:
673 case AtomicExpr::AO__atomic_add_fetch:
674 case AtomicExpr::AO__atomic_sub_fetch:
675 IsAddSub = true;
676 // Fall through.
677 case AtomicExpr::AO__c11_atomic_fetch_and:
678 case AtomicExpr::AO__c11_atomic_fetch_or:
679 case AtomicExpr::AO__c11_atomic_fetch_xor:
680 case AtomicExpr::AO__atomic_fetch_and:
681 case AtomicExpr::AO__atomic_fetch_or:
682 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smith51b92402012-04-13 06:31:38 +0000683 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithff34d402012-04-12 05:08:17 +0000684 case AtomicExpr::AO__atomic_and_fetch:
685 case AtomicExpr::AO__atomic_or_fetch:
686 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smith51b92402012-04-13 06:31:38 +0000687 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithff34d402012-04-12 05:08:17 +0000688 Form = Arithmetic;
689 break;
690
691 case AtomicExpr::AO__c11_atomic_exchange:
692 case AtomicExpr::AO__atomic_exchange_n:
693 Form = Xchg;
694 break;
695
696 case AtomicExpr::AO__atomic_exchange:
697 Form = GNUXchg;
698 break;
699
700 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
701 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
702 Form = C11CmpXchg;
703 break;
704
705 case AtomicExpr::AO__atomic_compare_exchange:
706 case AtomicExpr::AO__atomic_compare_exchange_n:
707 Form = GNUCmpXchg;
708 break;
709 }
710
711 // Check we have the right number of arguments.
712 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedman276b0612011-10-11 02:20:01 +0000713 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithff34d402012-04-12 05:08:17 +0000714 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +0000715 << TheCall->getCallee()->getSourceRange();
716 return ExprError();
Richard Smithff34d402012-04-12 05:08:17 +0000717 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
718 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedman276b0612011-10-11 02:20:01 +0000719 diag::err_typecheck_call_too_many_args)
Richard Smithff34d402012-04-12 05:08:17 +0000720 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +0000721 << TheCall->getCallee()->getSourceRange();
722 return ExprError();
723 }
724
Richard Smithff34d402012-04-12 05:08:17 +0000725 // Inspect the first argument of the atomic operation.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000726 Expr *Ptr = TheCall->getArg(0);
Eli Friedman276b0612011-10-11 02:20:01 +0000727 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
728 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
729 if (!pointerType) {
Richard Smithff34d402012-04-12 05:08:17 +0000730 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedman276b0612011-10-11 02:20:01 +0000731 << Ptr->getType() << Ptr->getSourceRange();
732 return ExprError();
733 }
734
Richard Smithff34d402012-04-12 05:08:17 +0000735 // For a __c11 builtin, this should be a pointer to an _Atomic type.
736 QualType AtomTy = pointerType->getPointeeType(); // 'A'
737 QualType ValType = AtomTy; // 'C'
738 if (IsC11) {
739 if (!AtomTy->isAtomicType()) {
740 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
741 << Ptr->getType() << Ptr->getSourceRange();
742 return ExprError();
743 }
Richard Smithbc57b102012-09-15 06:09:58 +0000744 if (AtomTy.isConstQualified()) {
745 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
746 << Ptr->getType() << Ptr->getSourceRange();
747 return ExprError();
748 }
Richard Smithff34d402012-04-12 05:08:17 +0000749 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedman276b0612011-10-11 02:20:01 +0000750 }
Eli Friedman276b0612011-10-11 02:20:01 +0000751
Richard Smithff34d402012-04-12 05:08:17 +0000752 // For an arithmetic operation, the implied arithmetic must be well-formed.
753 if (Form == Arithmetic) {
754 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
755 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
756 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
757 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
758 return ExprError();
759 }
760 if (!IsAddSub && !ValType->isIntegerType()) {
761 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
762 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
763 return ExprError();
764 }
765 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
766 // For __atomic_*_n operations, the value type must be a scalar integral or
767 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedman276b0612011-10-11 02:20:01 +0000768 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithff34d402012-04-12 05:08:17 +0000769 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
770 return ExprError();
771 }
772
773 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context)) {
774 // For GNU atomics, require a trivially-copyable type. This is not part of
775 // the GNU atomics specification, but we enforce it for sanity.
776 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedman276b0612011-10-11 02:20:01 +0000777 << Ptr->getType() << Ptr->getSourceRange();
778 return ExprError();
779 }
780
Richard Smithff34d402012-04-12 05:08:17 +0000781 // FIXME: For any builtin other than a load, the ValType must not be
782 // const-qualified.
Eli Friedman276b0612011-10-11 02:20:01 +0000783
784 switch (ValType.getObjCLifetime()) {
785 case Qualifiers::OCL_None:
786 case Qualifiers::OCL_ExplicitNone:
787 // okay
788 break;
789
790 case Qualifiers::OCL_Weak:
791 case Qualifiers::OCL_Strong:
792 case Qualifiers::OCL_Autoreleasing:
Richard Smithff34d402012-04-12 05:08:17 +0000793 // FIXME: Can this happen? By this point, ValType should be known
794 // to be trivially copyable.
Eli Friedman276b0612011-10-11 02:20:01 +0000795 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
796 << ValType << Ptr->getSourceRange();
797 return ExprError();
798 }
799
800 QualType ResultType = ValType;
Richard Smithff34d402012-04-12 05:08:17 +0000801 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedman276b0612011-10-11 02:20:01 +0000802 ResultType = Context.VoidTy;
Richard Smithff34d402012-04-12 05:08:17 +0000803 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedman276b0612011-10-11 02:20:01 +0000804 ResultType = Context.BoolTy;
805
Richard Smithff34d402012-04-12 05:08:17 +0000806 // The type of a parameter passed 'by value'. In the GNU atomics, such
807 // arguments are actually passed as pointers.
808 QualType ByValType = ValType; // 'CP'
809 if (!IsC11 && !IsN)
810 ByValType = Ptr->getType();
811
Eli Friedman276b0612011-10-11 02:20:01 +0000812 // The first argument --- the pointer --- has a fixed type; we
813 // deduce the types of the rest of the arguments accordingly. Walk
814 // the remaining arguments, converting them to the deduced value type.
Richard Smithff34d402012-04-12 05:08:17 +0000815 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedman276b0612011-10-11 02:20:01 +0000816 QualType Ty;
Richard Smithff34d402012-04-12 05:08:17 +0000817 if (i < NumVals[Form] + 1) {
818 switch (i) {
819 case 1:
820 // The second argument is the non-atomic operand. For arithmetic, this
821 // is always passed by value, and for a compare_exchange it is always
822 // passed by address. For the rest, GNU uses by-address and C11 uses
823 // by-value.
824 assert(Form != Load);
825 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
826 Ty = ValType;
827 else if (Form == Copy || Form == Xchg)
828 Ty = ByValType;
829 else if (Form == Arithmetic)
830 Ty = Context.getPointerDiffType();
831 else
832 Ty = Context.getPointerType(ValType.getUnqualifiedType());
833 break;
834 case 2:
835 // The third argument to compare_exchange / GNU exchange is a
836 // (pointer to a) desired value.
837 Ty = ByValType;
838 break;
839 case 3:
840 // The fourth argument to GNU compare_exchange is a 'weak' flag.
841 Ty = Context.BoolTy;
842 break;
843 }
Eli Friedman276b0612011-10-11 02:20:01 +0000844 } else {
845 // The order(s) are always converted to int.
846 Ty = Context.IntTy;
847 }
Richard Smithff34d402012-04-12 05:08:17 +0000848
Eli Friedman276b0612011-10-11 02:20:01 +0000849 InitializedEntity Entity =
850 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithff34d402012-04-12 05:08:17 +0000851 ExprResult Arg = TheCall->getArg(i);
Eli Friedman276b0612011-10-11 02:20:01 +0000852 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
853 if (Arg.isInvalid())
854 return true;
855 TheCall->setArg(i, Arg.get());
856 }
857
Richard Smithff34d402012-04-12 05:08:17 +0000858 // Permute the arguments into a 'consistent' order.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000859 SmallVector<Expr*, 5> SubExprs;
860 SubExprs.push_back(Ptr);
Richard Smithff34d402012-04-12 05:08:17 +0000861 switch (Form) {
862 case Init:
863 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnall7a7ee302012-01-16 17:27:18 +0000864 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +0000865 break;
866 case Load:
867 SubExprs.push_back(TheCall->getArg(1)); // Order
868 break;
869 case Copy:
870 case Arithmetic:
871 case Xchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000872 SubExprs.push_back(TheCall->getArg(2)); // Order
873 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +0000874 break;
875 case GNUXchg:
876 // Note, AtomicExpr::getVal2() has a special case for this atomic.
877 SubExprs.push_back(TheCall->getArg(3)); // Order
878 SubExprs.push_back(TheCall->getArg(1)); // Val1
879 SubExprs.push_back(TheCall->getArg(2)); // Val2
880 break;
881 case C11CmpXchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000882 SubExprs.push_back(TheCall->getArg(3)); // Order
883 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000884 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall2ebb98a2012-03-29 17:58:59 +0000885 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithff34d402012-04-12 05:08:17 +0000886 break;
887 case GNUCmpXchg:
888 SubExprs.push_back(TheCall->getArg(4)); // Order
889 SubExprs.push_back(TheCall->getArg(1)); // Val1
890 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
891 SubExprs.push_back(TheCall->getArg(2)); // Val2
892 SubExprs.push_back(TheCall->getArg(3)); // Weak
893 break;
Eli Friedman276b0612011-10-11 02:20:01 +0000894 }
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000895
896 return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +0000897 SubExprs, ResultType, Op,
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000898 TheCall->getRParenLoc()));
Eli Friedman276b0612011-10-11 02:20:01 +0000899}
900
901
John McCall5f8d6042011-08-27 01:09:30 +0000902/// checkBuiltinArgument - Given a call to a builtin function, perform
903/// normal type-checking on the given argument, updating the call in
904/// place. This is useful when a builtin function requires custom
905/// type-checking for some of its arguments but not necessarily all of
906/// them.
907///
908/// Returns true on error.
909static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
910 FunctionDecl *Fn = E->getDirectCallee();
911 assert(Fn && "builtin call without direct callee!");
912
913 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
914 InitializedEntity Entity =
915 InitializedEntity::InitializeParameter(S.Context, Param);
916
917 ExprResult Arg = E->getArg(0);
918 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
919 if (Arg.isInvalid())
920 return true;
921
922 E->setArg(ArgIndex, Arg.take());
923 return false;
924}
925
Chris Lattner5caa3702009-05-08 06:58:22 +0000926/// SemaBuiltinAtomicOverloaded - We have a call to a function like
927/// __sync_fetch_and_add, which is an overloaded function based on the pointer
928/// type of its first argument. The main ActOnCallExpr routines have already
929/// promoted the types of arguments because all of these calls are prototyped as
930/// void(...).
931///
932/// This function goes through and does final semantic checking for these
933/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +0000934ExprResult
935Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000936 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +0000937 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
938 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
939
940 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +0000941 if (TheCall->getNumArgs() < 1) {
942 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
943 << 0 << 1 << TheCall->getNumArgs()
944 << TheCall->getCallee()->getSourceRange();
945 return ExprError();
946 }
Mike Stump1eb44332009-09-09 15:08:12 +0000947
Chris Lattner5caa3702009-05-08 06:58:22 +0000948 // Inspect the first argument of the atomic builtin. This should always be
949 // a pointer type, whose element is an integral scalar or pointer type.
950 // Because it is a pointer type, we don't have to worry about any implicit
951 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +0000952 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +0000953 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman8c382062012-01-23 02:35:22 +0000954 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
955 if (FirstArgResult.isInvalid())
956 return ExprError();
957 FirstArg = FirstArgResult.take();
958 TheCall->setArg(0, FirstArg);
959
John McCallf85e1932011-06-15 23:02:42 +0000960 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
961 if (!pointerType) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000962 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
963 << FirstArg->getType() << FirstArg->getSourceRange();
964 return ExprError();
965 }
Mike Stump1eb44332009-09-09 15:08:12 +0000966
John McCallf85e1932011-06-15 23:02:42 +0000967 QualType ValType = pointerType->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +0000968 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +0000969 !ValType->isBlockPointerType()) {
970 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
971 << FirstArg->getType() << FirstArg->getSourceRange();
972 return ExprError();
973 }
Chris Lattner5caa3702009-05-08 06:58:22 +0000974
John McCallf85e1932011-06-15 23:02:42 +0000975 switch (ValType.getObjCLifetime()) {
976 case Qualifiers::OCL_None:
977 case Qualifiers::OCL_ExplicitNone:
978 // okay
979 break;
980
981 case Qualifiers::OCL_Weak:
982 case Qualifiers::OCL_Strong:
983 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +0000984 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCallf85e1932011-06-15 23:02:42 +0000985 << ValType << FirstArg->getSourceRange();
986 return ExprError();
987 }
988
John McCallb45ae252011-10-05 07:41:44 +0000989 // Strip any qualifiers off ValType.
990 ValType = ValType.getUnqualifiedType();
991
Chandler Carruth8d13d222010-07-18 20:54:12 +0000992 // The majority of builtins return a value, but a few have special return
993 // types, so allow them to override appropriately below.
994 QualType ResultType = ValType;
995
Chris Lattner5caa3702009-05-08 06:58:22 +0000996 // We need to figure out which concrete builtin this maps onto. For example,
997 // __sync_fetch_and_add with a 2 byte object turns into
998 // __sync_fetch_and_add_2.
999#define BUILTIN_ROW(x) \
1000 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1001 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +00001002
Chris Lattner5caa3702009-05-08 06:58:22 +00001003 static const unsigned BuiltinIndices[][5] = {
1004 BUILTIN_ROW(__sync_fetch_and_add),
1005 BUILTIN_ROW(__sync_fetch_and_sub),
1006 BUILTIN_ROW(__sync_fetch_and_or),
1007 BUILTIN_ROW(__sync_fetch_and_and),
1008 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +00001009
Chris Lattner5caa3702009-05-08 06:58:22 +00001010 BUILTIN_ROW(__sync_add_and_fetch),
1011 BUILTIN_ROW(__sync_sub_and_fetch),
1012 BUILTIN_ROW(__sync_and_and_fetch),
1013 BUILTIN_ROW(__sync_or_and_fetch),
1014 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +00001015
Chris Lattner5caa3702009-05-08 06:58:22 +00001016 BUILTIN_ROW(__sync_val_compare_and_swap),
1017 BUILTIN_ROW(__sync_bool_compare_and_swap),
1018 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +00001019 BUILTIN_ROW(__sync_lock_release),
1020 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +00001021 };
Mike Stump1eb44332009-09-09 15:08:12 +00001022#undef BUILTIN_ROW
1023
Chris Lattner5caa3702009-05-08 06:58:22 +00001024 // Determine the index of the size.
1025 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +00001026 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +00001027 case 1: SizeIndex = 0; break;
1028 case 2: SizeIndex = 1; break;
1029 case 4: SizeIndex = 2; break;
1030 case 8: SizeIndex = 3; break;
1031 case 16: SizeIndex = 4; break;
1032 default:
Chandler Carruthd2014572010-07-09 18:59:35 +00001033 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1034 << FirstArg->getType() << FirstArg->getSourceRange();
1035 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +00001036 }
Mike Stump1eb44332009-09-09 15:08:12 +00001037
Chris Lattner5caa3702009-05-08 06:58:22 +00001038 // Each of these builtins has one pointer argument, followed by some number of
1039 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1040 // that we ignore. Find out which row of BuiltinIndices to read from as well
1041 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00001042 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +00001043 unsigned BuiltinIndex, NumFixed = 1;
1044 switch (BuiltinID) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001045 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregora9766412011-11-28 16:30:08 +00001046 case Builtin::BI__sync_fetch_and_add:
1047 case Builtin::BI__sync_fetch_and_add_1:
1048 case Builtin::BI__sync_fetch_and_add_2:
1049 case Builtin::BI__sync_fetch_and_add_4:
1050 case Builtin::BI__sync_fetch_and_add_8:
1051 case Builtin::BI__sync_fetch_and_add_16:
1052 BuiltinIndex = 0;
1053 break;
1054
1055 case Builtin::BI__sync_fetch_and_sub:
1056 case Builtin::BI__sync_fetch_and_sub_1:
1057 case Builtin::BI__sync_fetch_and_sub_2:
1058 case Builtin::BI__sync_fetch_and_sub_4:
1059 case Builtin::BI__sync_fetch_and_sub_8:
1060 case Builtin::BI__sync_fetch_and_sub_16:
1061 BuiltinIndex = 1;
1062 break;
1063
1064 case Builtin::BI__sync_fetch_and_or:
1065 case Builtin::BI__sync_fetch_and_or_1:
1066 case Builtin::BI__sync_fetch_and_or_2:
1067 case Builtin::BI__sync_fetch_and_or_4:
1068 case Builtin::BI__sync_fetch_and_or_8:
1069 case Builtin::BI__sync_fetch_and_or_16:
1070 BuiltinIndex = 2;
1071 break;
1072
1073 case Builtin::BI__sync_fetch_and_and:
1074 case Builtin::BI__sync_fetch_and_and_1:
1075 case Builtin::BI__sync_fetch_and_and_2:
1076 case Builtin::BI__sync_fetch_and_and_4:
1077 case Builtin::BI__sync_fetch_and_and_8:
1078 case Builtin::BI__sync_fetch_and_and_16:
1079 BuiltinIndex = 3;
1080 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001081
Douglas Gregora9766412011-11-28 16:30:08 +00001082 case Builtin::BI__sync_fetch_and_xor:
1083 case Builtin::BI__sync_fetch_and_xor_1:
1084 case Builtin::BI__sync_fetch_and_xor_2:
1085 case Builtin::BI__sync_fetch_and_xor_4:
1086 case Builtin::BI__sync_fetch_and_xor_8:
1087 case Builtin::BI__sync_fetch_and_xor_16:
1088 BuiltinIndex = 4;
1089 break;
1090
1091 case Builtin::BI__sync_add_and_fetch:
1092 case Builtin::BI__sync_add_and_fetch_1:
1093 case Builtin::BI__sync_add_and_fetch_2:
1094 case Builtin::BI__sync_add_and_fetch_4:
1095 case Builtin::BI__sync_add_and_fetch_8:
1096 case Builtin::BI__sync_add_and_fetch_16:
1097 BuiltinIndex = 5;
1098 break;
1099
1100 case Builtin::BI__sync_sub_and_fetch:
1101 case Builtin::BI__sync_sub_and_fetch_1:
1102 case Builtin::BI__sync_sub_and_fetch_2:
1103 case Builtin::BI__sync_sub_and_fetch_4:
1104 case Builtin::BI__sync_sub_and_fetch_8:
1105 case Builtin::BI__sync_sub_and_fetch_16:
1106 BuiltinIndex = 6;
1107 break;
1108
1109 case Builtin::BI__sync_and_and_fetch:
1110 case Builtin::BI__sync_and_and_fetch_1:
1111 case Builtin::BI__sync_and_and_fetch_2:
1112 case Builtin::BI__sync_and_and_fetch_4:
1113 case Builtin::BI__sync_and_and_fetch_8:
1114 case Builtin::BI__sync_and_and_fetch_16:
1115 BuiltinIndex = 7;
1116 break;
1117
1118 case Builtin::BI__sync_or_and_fetch:
1119 case Builtin::BI__sync_or_and_fetch_1:
1120 case Builtin::BI__sync_or_and_fetch_2:
1121 case Builtin::BI__sync_or_and_fetch_4:
1122 case Builtin::BI__sync_or_and_fetch_8:
1123 case Builtin::BI__sync_or_and_fetch_16:
1124 BuiltinIndex = 8;
1125 break;
1126
1127 case Builtin::BI__sync_xor_and_fetch:
1128 case Builtin::BI__sync_xor_and_fetch_1:
1129 case Builtin::BI__sync_xor_and_fetch_2:
1130 case Builtin::BI__sync_xor_and_fetch_4:
1131 case Builtin::BI__sync_xor_and_fetch_8:
1132 case Builtin::BI__sync_xor_and_fetch_16:
1133 BuiltinIndex = 9;
1134 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001135
Chris Lattner5caa3702009-05-08 06:58:22 +00001136 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001137 case Builtin::BI__sync_val_compare_and_swap_1:
1138 case Builtin::BI__sync_val_compare_and_swap_2:
1139 case Builtin::BI__sync_val_compare_and_swap_4:
1140 case Builtin::BI__sync_val_compare_and_swap_8:
1141 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001142 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +00001143 NumFixed = 2;
1144 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001145
Chris Lattner5caa3702009-05-08 06:58:22 +00001146 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001147 case Builtin::BI__sync_bool_compare_and_swap_1:
1148 case Builtin::BI__sync_bool_compare_and_swap_2:
1149 case Builtin::BI__sync_bool_compare_and_swap_4:
1150 case Builtin::BI__sync_bool_compare_and_swap_8:
1151 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001152 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +00001153 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001154 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001155 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001156
1157 case Builtin::BI__sync_lock_test_and_set:
1158 case Builtin::BI__sync_lock_test_and_set_1:
1159 case Builtin::BI__sync_lock_test_and_set_2:
1160 case Builtin::BI__sync_lock_test_and_set_4:
1161 case Builtin::BI__sync_lock_test_and_set_8:
1162 case Builtin::BI__sync_lock_test_and_set_16:
1163 BuiltinIndex = 12;
1164 break;
1165
Chris Lattner5caa3702009-05-08 06:58:22 +00001166 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +00001167 case Builtin::BI__sync_lock_release_1:
1168 case Builtin::BI__sync_lock_release_2:
1169 case Builtin::BI__sync_lock_release_4:
1170 case Builtin::BI__sync_lock_release_8:
1171 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001172 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +00001173 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001174 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001175 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001176
1177 case Builtin::BI__sync_swap:
1178 case Builtin::BI__sync_swap_1:
1179 case Builtin::BI__sync_swap_2:
1180 case Builtin::BI__sync_swap_4:
1181 case Builtin::BI__sync_swap_8:
1182 case Builtin::BI__sync_swap_16:
1183 BuiltinIndex = 14;
1184 break;
Chris Lattner5caa3702009-05-08 06:58:22 +00001185 }
Mike Stump1eb44332009-09-09 15:08:12 +00001186
Chris Lattner5caa3702009-05-08 06:58:22 +00001187 // Now that we know how many fixed arguments we expect, first check that we
1188 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +00001189 if (TheCall->getNumArgs() < 1+NumFixed) {
1190 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1191 << 0 << 1+NumFixed << TheCall->getNumArgs()
1192 << TheCall->getCallee()->getSourceRange();
1193 return ExprError();
1194 }
Mike Stump1eb44332009-09-09 15:08:12 +00001195
Chris Lattnere7ac0a92009-05-08 15:36:58 +00001196 // Get the decl for the concrete builtin from this, we can tell what the
1197 // concrete integer type we should convert to is.
1198 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1199 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara2ad11cd2012-09-22 09:05:22 +00001200 FunctionDecl *NewBuiltinDecl;
1201 if (NewBuiltinID == BuiltinID)
1202 NewBuiltinDecl = FDecl;
1203 else {
1204 // Perform builtin lookup to avoid redeclaring it.
1205 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1206 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1207 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1208 assert(Res.getFoundDecl());
1209 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
1210 if (NewBuiltinDecl == 0)
1211 return ExprError();
1212 }
Chandler Carruthd2014572010-07-09 18:59:35 +00001213
John McCallf871d0c2010-08-07 06:22:56 +00001214 // The first argument --- the pointer --- has a fixed type; we
1215 // deduce the types of the rest of the arguments accordingly. Walk
1216 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +00001217 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +00001218 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +00001219
Chris Lattner5caa3702009-05-08 06:58:22 +00001220 // GCC does an implicit conversion to the pointer or integer ValType. This
1221 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb45ae252011-10-05 07:41:44 +00001222 // Initialize the argument.
1223 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1224 ValType, /*consume*/ false);
1225 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley429bb272011-04-08 18:41:53 +00001226 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +00001227 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001228
Chris Lattner5caa3702009-05-08 06:58:22 +00001229 // Okay, we have something that *can* be converted to the right type. Check
1230 // to see if there is a potentially weird extension going on here. This can
1231 // happen when you do an atomic operation on something like an char* and
1232 // pass in 42. The 42 gets converted to char. This is even more strange
1233 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +00001234 // FIXME: Do this check.
John McCallb45ae252011-10-05 07:41:44 +00001235 TheCall->setArg(i+1, Arg.take());
Chris Lattner5caa3702009-05-08 06:58:22 +00001236 }
Mike Stump1eb44332009-09-09 15:08:12 +00001237
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001238 ASTContext& Context = this->getASTContext();
1239
1240 // Create a new DeclRefExpr to refer to the new decl.
1241 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1242 Context,
1243 DRE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001244 SourceLocation(),
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001245 NewBuiltinDecl,
John McCallf4b88a42012-03-10 09:33:50 +00001246 /*enclosing*/ false,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001247 DRE->getLocation(),
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001248 Context.BuiltinFnTy,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001249 DRE->getValueKind());
Mike Stump1eb44332009-09-09 15:08:12 +00001250
Chris Lattner5caa3702009-05-08 06:58:22 +00001251 // Set the callee in the CallExpr.
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001252 // FIXME: This loses syntactic information.
1253 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1254 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1255 CK_BuiltinFnToFnPtr);
John Wiegley429bb272011-04-08 18:41:53 +00001256 TheCall->setCallee(PromotedCall.take());
Mike Stump1eb44332009-09-09 15:08:12 +00001257
Chandler Carruthdb4325b2010-07-18 07:23:17 +00001258 // Change the result type of the call to match the original value type. This
1259 // is arbitrary, but the codegen for these builtins ins design to handle it
1260 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +00001261 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +00001262
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001263 return TheCallResult;
Chris Lattner5caa3702009-05-08 06:58:22 +00001264}
1265
Chris Lattner69039812009-02-18 06:01:06 +00001266/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +00001267/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +00001268/// Note: It might also make sense to do the UTF-16 conversion here (would
1269/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +00001270bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +00001271 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +00001272 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1273
Douglas Gregor5cee1192011-07-27 05:40:30 +00001274 if (!Literal || !Literal->isAscii()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001275 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1276 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001277 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +00001278 }
Mike Stump1eb44332009-09-09 15:08:12 +00001279
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001280 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001281 StringRef String = Literal->getString();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001282 unsigned NumBytes = String.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001283 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divacky31ba6132012-09-06 15:59:27 +00001284 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001285 UTF16 *ToPtr = &ToBuf[0];
1286
1287 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1288 &ToPtr, ToPtr + NumBytes,
1289 strictConversion);
1290 // Check for conversion failure.
1291 if (Result != conversionOK)
1292 Diag(Arg->getLocStart(),
1293 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1294 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001295 return false;
Chris Lattner59907c42007-08-10 20:18:51 +00001296}
1297
Chris Lattnerc27c6652007-12-20 00:05:45 +00001298/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1299/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +00001300bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1301 Expr *Fn = TheCall->getCallee();
1302 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +00001303 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001304 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001305 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1306 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +00001307 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001308 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +00001309 return true;
1310 }
Eli Friedman56f20ae2008-12-15 22:05:35 +00001311
1312 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +00001313 return Diag(TheCall->getLocEnd(),
1314 diag::err_typecheck_call_too_few_args_at_least)
1315 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +00001316 }
1317
John McCall5f8d6042011-08-27 01:09:30 +00001318 // Type-check the first argument normally.
1319 if (checkBuiltinArgument(*this, TheCall, 0))
1320 return true;
1321
Chris Lattnerc27c6652007-12-20 00:05:45 +00001322 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001323 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +00001324 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001325 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +00001326 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +00001327 else if (FunctionDecl *FD = getCurFunctionDecl())
1328 isVariadic = FD->isVariadic();
1329 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001330 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +00001331
Chris Lattnerc27c6652007-12-20 00:05:45 +00001332 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001333 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1334 return true;
1335 }
Mike Stump1eb44332009-09-09 15:08:12 +00001336
Chris Lattner30ce3442007-12-19 23:59:04 +00001337 // Verify that the second argument to the builtin is the last argument of the
1338 // current function or method.
1339 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +00001340 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001341
Anders Carlsson88cf2262008-02-11 04:20:54 +00001342 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1343 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001344 // FIXME: This isn't correct for methods (results in bogus warning).
1345 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +00001346 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001347 if (CurBlock)
1348 LastArg = *(CurBlock->TheDecl->param_end()-1);
1349 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +00001350 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001351 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001352 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001353 SecondArgIsLastNamedArgument = PV == LastArg;
1354 }
1355 }
Mike Stump1eb44332009-09-09 15:08:12 +00001356
Chris Lattner30ce3442007-12-19 23:59:04 +00001357 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001358 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +00001359 diag::warn_second_parameter_of_va_start_not_last_named_argument);
1360 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +00001361}
Chris Lattner30ce3442007-12-19 23:59:04 +00001362
Chris Lattner1b9a0792007-12-20 00:26:33 +00001363/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1364/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +00001365bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1366 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +00001367 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001368 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +00001369 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +00001370 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001371 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001372 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001373 << SourceRange(TheCall->getArg(2)->getLocStart(),
1374 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001375
John Wiegley429bb272011-04-08 18:41:53 +00001376 ExprResult OrigArg0 = TheCall->getArg(0);
1377 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +00001378
Chris Lattner1b9a0792007-12-20 00:26:33 +00001379 // Do standard promotions between the two arguments, returning their common
1380 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +00001381 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +00001382 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1383 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +00001384
1385 // Make sure any conversions are pushed back into the call; this is
1386 // type safe since unordered compare builtins are declared as "_Bool
1387 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +00001388 TheCall->setArg(0, OrigArg0.get());
1389 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001390
John Wiegley429bb272011-04-08 18:41:53 +00001391 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +00001392 return false;
1393
Chris Lattner1b9a0792007-12-20 00:26:33 +00001394 // If the common type isn't a real floating type, then the arguments were
1395 // invalid for this operation.
Eli Friedman860a3192012-06-16 02:19:17 +00001396 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +00001397 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001398 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +00001399 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1400 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001401
Chris Lattner1b9a0792007-12-20 00:26:33 +00001402 return false;
1403}
1404
Benjamin Kramere771a7a2010-02-15 22:42:31 +00001405/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1406/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001407/// to check everything. We expect the last argument to be a floating point
1408/// value.
1409bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1410 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +00001411 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001412 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001413 if (TheCall->getNumArgs() > NumArgs)
1414 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001415 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001416 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001417 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001418 (*(TheCall->arg_end()-1))->getLocEnd());
1419
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001420 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001421
Eli Friedman9ac6f622009-08-31 20:06:00 +00001422 if (OrigArg->isTypeDependent())
1423 return false;
1424
Chris Lattner81368fb2010-05-06 05:50:07 +00001425 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +00001426 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +00001427 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001428 diag::err_typecheck_call_invalid_unary_fp)
1429 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001430
Chris Lattner81368fb2010-05-06 05:50:07 +00001431 // If this is an implicit conversion from float -> double, remove it.
1432 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1433 Expr *CastArg = Cast->getSubExpr();
1434 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1435 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1436 "promotion from float to double is the only expected cast here");
1437 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +00001438 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner81368fb2010-05-06 05:50:07 +00001439 }
1440 }
1441
Eli Friedman9ac6f622009-08-31 20:06:00 +00001442 return false;
1443}
1444
Eli Friedmand38617c2008-05-14 19:38:39 +00001445/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1446// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +00001447ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001448 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001449 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +00001450 diag::err_typecheck_call_too_few_args_at_least)
Nate Begeman37b6a572010-06-08 00:16:34 +00001451 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherd77b9a22010-04-16 04:48:22 +00001452 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001453
Nate Begeman37b6a572010-06-08 00:16:34 +00001454 // Determine which of the following types of shufflevector we're checking:
1455 // 1) unary, vector mask: (lhs, mask)
1456 // 2) binary, vector mask: (lhs, rhs, mask)
1457 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1458 QualType resType = TheCall->getArg(0)->getType();
1459 unsigned numElements = 0;
1460
Douglas Gregorcde01732009-05-19 22:10:17 +00001461 if (!TheCall->getArg(0)->isTypeDependent() &&
1462 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001463 QualType LHSType = TheCall->getArg(0)->getType();
1464 QualType RHSType = TheCall->getArg(1)->getType();
1465
1466 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001467 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001468 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001469 TheCall->getArg(1)->getLocEnd());
1470 return ExprError();
1471 }
Nate Begeman37b6a572010-06-08 00:16:34 +00001472
1473 numElements = LHSType->getAs<VectorType>()->getNumElements();
1474 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +00001475
Nate Begeman37b6a572010-06-08 00:16:34 +00001476 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1477 // with mask. If so, verify that RHS is an integer vector type with the
1478 // same number of elts as lhs.
1479 if (TheCall->getNumArgs() == 2) {
Douglas Gregorf6094622010-07-23 15:58:24 +00001480 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +00001481 RHSType->getAs<VectorType>()->getNumElements() != numElements)
1482 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1483 << SourceRange(TheCall->getArg(1)->getLocStart(),
1484 TheCall->getArg(1)->getLocEnd());
1485 numResElements = numElements;
1486 }
1487 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001488 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001489 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001490 TheCall->getArg(1)->getLocEnd());
1491 return ExprError();
Nate Begeman37b6a572010-06-08 00:16:34 +00001492 } else if (numElements != numResElements) {
1493 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +00001494 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001495 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +00001496 }
Eli Friedmand38617c2008-05-14 19:38:39 +00001497 }
1498
1499 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001500 if (TheCall->getArg(i)->isTypeDependent() ||
1501 TheCall->getArg(i)->isValueDependent())
1502 continue;
1503
Nate Begeman37b6a572010-06-08 00:16:34 +00001504 llvm::APSInt Result(32);
1505 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1506 return ExprError(Diag(TheCall->getLocStart(),
1507 diag::err_shufflevector_nonconstant_argument)
1508 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001509
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001510 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001511 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001512 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001513 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001514 }
1515
Chris Lattner5f9e2722011-07-23 10:55:15 +00001516 SmallVector<Expr*, 32> exprs;
Eli Friedmand38617c2008-05-14 19:38:39 +00001517
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001518 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +00001519 exprs.push_back(TheCall->getArg(i));
1520 TheCall->setArg(i, 0);
1521 }
1522
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001523 return Owned(new (Context) ShuffleVectorExpr(Context, exprs, resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001524 TheCall->getCallee()->getLocStart(),
1525 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +00001526}
Chris Lattner30ce3442007-12-19 23:59:04 +00001527
Daniel Dunbar4493f792008-07-21 22:59:13 +00001528/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1529// This is declared to take (const void*, ...) and can take two
1530// optional constant int args.
1531bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001532 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001533
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001534 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +00001535 return Diag(TheCall->getLocEnd(),
1536 diag::err_typecheck_call_too_many_args_at_most)
1537 << 0 /*function call*/ << 3 << NumArgs
1538 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001539
1540 // Argument 0 is checked for us and the remaining arguments must be
1541 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001542 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +00001543 Expr *Arg = TheCall->getArg(i);
Douglas Gregor592a4232012-06-29 01:05:22 +00001544
1545 // We can't check the value of a dependent argument.
1546 if (Arg->isTypeDependent() || Arg->isValueDependent())
1547 continue;
1548
Eli Friedman9aef7262009-12-04 00:30:06 +00001549 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +00001550 if (SemaBuiltinConstantArg(TheCall, i, Result))
1551 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001552
Daniel Dunbar4493f792008-07-21 22:59:13 +00001553 // FIXME: gcc issues a warning and rewrites these to 0. These
1554 // seems especially odd for the third argument since the default
1555 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001556 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +00001557 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001558 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001559 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001560 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +00001561 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001562 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001563 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001564 }
1565 }
1566
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001567 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +00001568}
1569
Eric Christopher691ebc32010-04-17 02:26:23 +00001570/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1571/// TheCall is a constant expression.
1572bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1573 llvm::APSInt &Result) {
1574 Expr *Arg = TheCall->getArg(ArgNum);
1575 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1576 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1577
1578 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1579
1580 if (!Arg->isIntegerConstantExpr(Result, Context))
1581 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +00001582 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +00001583
Chris Lattner21fb98e2009-09-23 06:06:36 +00001584 return false;
1585}
1586
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001587/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1588/// int type). This simply type checks that type is one of the defined
1589/// constants (0-3).
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001590// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001591bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +00001592 llvm::APSInt Result;
Douglas Gregor592a4232012-06-29 01:05:22 +00001593
1594 // We can't check the value of a dependent argument.
1595 if (TheCall->getArg(1)->isTypeDependent() ||
1596 TheCall->getArg(1)->isValueDependent())
1597 return false;
1598
Eric Christopher691ebc32010-04-17 02:26:23 +00001599 // Check constant-ness first.
1600 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1601 return true;
1602
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001603 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001604 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001605 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1606 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001607 }
1608
1609 return false;
1610}
1611
Eli Friedman586d6a82009-05-03 06:04:26 +00001612/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +00001613/// This checks that val is a constant 1.
1614bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1615 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +00001616 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +00001617
Eric Christopher691ebc32010-04-17 02:26:23 +00001618 // TODO: This is less than ideal. Overload this to take a value.
1619 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1620 return true;
1621
1622 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +00001623 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1624 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1625
1626 return false;
1627}
1628
Richard Smith831421f2012-06-25 20:30:08 +00001629// Determine if an expression is a string literal or constant string.
1630// If this function returns false on the arguments to a function expecting a
1631// format string, we will usually need to emit a warning.
1632// True string literals are then checked by CheckFormatString.
1633Sema::StringLiteralCheckType
1634Sema::checkFormatStringExpr(const Expr *E, Expr **Args,
1635 unsigned NumArgs, bool HasVAListArg,
1636 unsigned format_idx, unsigned firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001637 FormatStringType Type, VariadicCallType CallType,
1638 bool inFunctionCall) {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001639 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +00001640 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith831421f2012-06-25 20:30:08 +00001641 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001642
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001643 E = E->IgnoreParenCasts();
Peter Collingbournef111d932011-04-15 00:35:48 +00001644
David Blaikiea73cdcb2012-02-10 21:07:25 +00001645 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
1646 // Technically -Wformat-nonliteral does not warn about this case.
1647 // The behavior of printf and friends in this case is implementation
1648 // dependent. Ideally if the format string cannot be null then
1649 // it should have a 'nonnull' attribute in the function prototype.
Richard Smith831421f2012-06-25 20:30:08 +00001650 return SLCT_CheckedLiteral;
David Blaikiea73cdcb2012-02-10 21:07:25 +00001651
Ted Kremenekd30ef872009-01-12 23:09:09 +00001652 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +00001653 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +00001654 case Stmt::ConditionalOperatorClass: {
Richard Smith831421f2012-06-25 20:30:08 +00001655 // The expression is a literal if both sub-expressions were, and it was
1656 // completely checked only if both sub-expressions were checked.
1657 const AbstractConditionalOperator *C =
1658 cast<AbstractConditionalOperator>(E);
1659 StringLiteralCheckType Left =
1660 checkFormatStringExpr(C->getTrueExpr(), Args, NumArgs,
1661 HasVAListArg, format_idx, firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001662 Type, CallType, inFunctionCall);
Richard Smith831421f2012-06-25 20:30:08 +00001663 if (Left == SLCT_NotALiteral)
1664 return SLCT_NotALiteral;
1665 StringLiteralCheckType Right =
1666 checkFormatStringExpr(C->getFalseExpr(), Args, NumArgs,
1667 HasVAListArg, format_idx, firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001668 Type, CallType, inFunctionCall);
Richard Smith831421f2012-06-25 20:30:08 +00001669 return Left < Right ? Left : Right;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001670 }
1671
1672 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001673 E = cast<ImplicitCastExpr>(E)->getSubExpr();
1674 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001675 }
1676
John McCall56ca35d2011-02-17 10:25:35 +00001677 case Stmt::OpaqueValueExprClass:
1678 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
1679 E = src;
1680 goto tryAgain;
1681 }
Richard Smith831421f2012-06-25 20:30:08 +00001682 return SLCT_NotALiteral;
John McCall56ca35d2011-02-17 10:25:35 +00001683
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001684 case Stmt::PredefinedExprClass:
1685 // While __func__, etc., are technically not string literals, they
1686 // cannot contain format specifiers and thus are not a security
1687 // liability.
Richard Smith831421f2012-06-25 20:30:08 +00001688 return SLCT_UncheckedLiteral;
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001689
Ted Kremenek082d9362009-03-20 21:35:28 +00001690 case Stmt::DeclRefExprClass: {
1691 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001692
Ted Kremenek082d9362009-03-20 21:35:28 +00001693 // As an exception, do not flag errors for variables binding to
1694 // const string literals.
1695 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1696 bool isConstant = false;
1697 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001698
Ted Kremenek082d9362009-03-20 21:35:28 +00001699 if (const ArrayType *AT = Context.getAsArrayType(T)) {
1700 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001701 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001702 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +00001703 PT->getPointeeType().isConstant(Context);
Jean-Daniel Dupase98e5b52012-01-25 10:35:33 +00001704 } else if (T->isObjCObjectPointerType()) {
1705 // In ObjC, there is usually no "const ObjectPointer" type,
1706 // so don't check if the pointee type is constant.
1707 isConstant = T.isConstant(Context);
Ted Kremenek082d9362009-03-20 21:35:28 +00001708 }
Mike Stump1eb44332009-09-09 15:08:12 +00001709
Ted Kremenek082d9362009-03-20 21:35:28 +00001710 if (isConstant) {
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00001711 if (const Expr *Init = VD->getAnyInitializer()) {
1712 // Look through initializers like const char c[] = { "foo" }
1713 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
1714 if (InitList->isStringLiteralInit())
1715 Init = InitList->getInit(0)->IgnoreParenImpCasts();
1716 }
Richard Smith831421f2012-06-25 20:30:08 +00001717 return checkFormatStringExpr(Init, Args, NumArgs,
1718 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001719 firstDataArg, Type, CallType,
Richard Smith831421f2012-06-25 20:30:08 +00001720 /*inFunctionCall*/false);
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00001721 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001722 }
Mike Stump1eb44332009-09-09 15:08:12 +00001723
Anders Carlssond966a552009-06-28 19:55:58 +00001724 // For vprintf* functions (i.e., HasVAListArg==true), we add a
1725 // special check to see if the format string is a function parameter
1726 // of the function calling the printf function. If the function
1727 // has an attribute indicating it is a printf-like function, then we
1728 // should suppress warnings concerning non-literals being used in a call
1729 // to a vprintf function. For example:
1730 //
1731 // void
1732 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1733 // va_list ap;
1734 // va_start(ap, fmt);
1735 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
1736 // ...
1737 //
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00001738 if (HasVAListArg) {
1739 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
1740 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
1741 int PVIndex = PV->getFunctionScopeIndex() + 1;
1742 for (specific_attr_iterator<FormatAttr>
1743 i = ND->specific_attr_begin<FormatAttr>(),
1744 e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) {
1745 FormatAttr *PVFormat = *i;
1746 // adjust for implicit parameter
1747 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1748 if (MD->isInstance())
1749 ++PVIndex;
1750 // We also check if the formats are compatible.
1751 // We can't pass a 'scanf' string to a 'printf' function.
1752 if (PVIndex == PVFormat->getFormatIdx() &&
1753 Type == GetFormatStringType(PVFormat))
Richard Smith831421f2012-06-25 20:30:08 +00001754 return SLCT_UncheckedLiteral;
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00001755 }
1756 }
1757 }
1758 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001759 }
Mike Stump1eb44332009-09-09 15:08:12 +00001760
Richard Smith831421f2012-06-25 20:30:08 +00001761 return SLCT_NotALiteral;
Ted Kremenek082d9362009-03-20 21:35:28 +00001762 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00001763
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001764 case Stmt::CallExprClass:
1765 case Stmt::CXXMemberCallExprClass: {
Anders Carlsson8f031b32009-06-27 04:05:33 +00001766 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001767 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
1768 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
1769 unsigned ArgIndex = FA->getFormatIdx();
1770 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1771 if (MD->isInstance())
1772 --ArgIndex;
1773 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001774
Richard Smith831421f2012-06-25 20:30:08 +00001775 return checkFormatStringExpr(Arg, Args, NumArgs,
1776 HasVAListArg, format_idx, firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001777 Type, CallType, inFunctionCall);
Jordan Rose50687312012-06-04 23:52:23 +00001778 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
1779 unsigned BuiltinID = FD->getBuiltinID();
1780 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
1781 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
1782 const Expr *Arg = CE->getArg(0);
Richard Smith831421f2012-06-25 20:30:08 +00001783 return checkFormatStringExpr(Arg, Args, NumArgs,
1784 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001785 firstDataArg, Type, CallType,
1786 inFunctionCall);
Jordan Rose50687312012-06-04 23:52:23 +00001787 }
Anders Carlsson8f031b32009-06-27 04:05:33 +00001788 }
1789 }
Mike Stump1eb44332009-09-09 15:08:12 +00001790
Richard Smith831421f2012-06-25 20:30:08 +00001791 return SLCT_NotALiteral;
Anders Carlsson8f031b32009-06-27 04:05:33 +00001792 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001793 case Stmt::ObjCStringLiteralClass:
1794 case Stmt::StringLiteralClass: {
1795 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001796
Ted Kremenek082d9362009-03-20 21:35:28 +00001797 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00001798 StrE = ObjCFExpr->getString();
1799 else
Ted Kremenek082d9362009-03-20 21:35:28 +00001800 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001801
Ted Kremenekd30ef872009-01-12 23:09:09 +00001802 if (StrE) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001803 CheckFormatString(StrE, E, Args, NumArgs, HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001804 firstDataArg, Type, inFunctionCall, CallType);
Richard Smith831421f2012-06-25 20:30:08 +00001805 return SLCT_CheckedLiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001806 }
Mike Stump1eb44332009-09-09 15:08:12 +00001807
Richard Smith831421f2012-06-25 20:30:08 +00001808 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001809 }
Mike Stump1eb44332009-09-09 15:08:12 +00001810
Ted Kremenek082d9362009-03-20 21:35:28 +00001811 default:
Richard Smith831421f2012-06-25 20:30:08 +00001812 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001813 }
1814}
1815
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001816void
Mike Stump1eb44332009-09-09 15:08:12 +00001817Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewycky909a70d2011-03-25 01:44:32 +00001818 const Expr * const *ExprArgs,
1819 SourceLocation CallSiteLoc) {
Sean Huntcf807c42010-08-18 23:23:40 +00001820 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1821 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001822 i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +00001823 const Expr *ArgExpr = ExprArgs[*i];
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001824 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00001825 Expr::NPC_ValueDependentIsNotNull))
Nick Lewycky909a70d2011-03-25 01:44:32 +00001826 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001827 }
1828}
Ted Kremenekd30ef872009-01-12 23:09:09 +00001829
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001830Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
1831 return llvm::StringSwitch<FormatStringType>(Format->getType())
1832 .Case("scanf", FST_Scanf)
1833 .Cases("printf", "printf0", FST_Printf)
1834 .Cases("NSString", "CFString", FST_NSString)
1835 .Case("strftime", FST_Strftime)
1836 .Case("strfmon", FST_Strfmon)
1837 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
1838 .Default(FST_Unknown);
1839}
1840
Jordan Roseddcfbc92012-07-19 18:10:23 +00001841/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek826a3452010-07-16 02:11:22 +00001842/// functions) for correct use of format strings.
Richard Smith831421f2012-06-25 20:30:08 +00001843/// Returns true if a format string has been fully checked.
Richard Smith831421f2012-06-25 20:30:08 +00001844bool Sema::CheckFormatArguments(const FormatAttr *Format, Expr **Args,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001845 unsigned NumArgs, bool IsCXXMember,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001846 VariadicCallType CallType,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001847 SourceLocation Loc, SourceRange Range) {
Richard Smith831421f2012-06-25 20:30:08 +00001848 FormatStringInfo FSI;
1849 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
1850 return CheckFormatArguments(Args, NumArgs, FSI.HasVAListArg, FSI.FormatIdx,
1851 FSI.FirstDataArg, GetFormatStringType(Format),
Jordan Roseddcfbc92012-07-19 18:10:23 +00001852 CallType, Loc, Range);
Richard Smith831421f2012-06-25 20:30:08 +00001853 return false;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001854}
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001855
Richard Smith831421f2012-06-25 20:30:08 +00001856bool Sema::CheckFormatArguments(Expr **Args, unsigned NumArgs,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001857 bool HasVAListArg, unsigned format_idx,
1858 unsigned firstDataArg, FormatStringType Type,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001859 VariadicCallType CallType,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001860 SourceLocation Loc, SourceRange Range) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001861 // CHECK: printf/scanf-like function is called with no format string.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001862 if (format_idx >= NumArgs) {
1863 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith831421f2012-06-25 20:30:08 +00001864 return false;
Ted Kremenek71895b92007-08-14 17:39:48 +00001865 }
Mike Stump1eb44332009-09-09 15:08:12 +00001866
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001867 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001868
Chris Lattner59907c42007-08-10 20:18:51 +00001869 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001870 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001871 // Dynamically generated format strings are difficult to
1872 // automatically vet at compile time. Requiring that format strings
1873 // are string literals: (1) permits the checking of format strings by
1874 // the compiler and thereby (2) can practically remove the source of
1875 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001876
Mike Stump1eb44332009-09-09 15:08:12 +00001877 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001878 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001879 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001880 // the same format string checking logic for both ObjC and C strings.
Richard Smith831421f2012-06-25 20:30:08 +00001881 StringLiteralCheckType CT =
1882 checkFormatStringExpr(OrigFormatExpr, Args, NumArgs, HasVAListArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001883 format_idx, firstDataArg, Type, CallType);
Richard Smith831421f2012-06-25 20:30:08 +00001884 if (CT != SLCT_NotALiteral)
1885 // Literal format string found, check done!
1886 return CT == SLCT_CheckedLiteral;
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001887
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00001888 // Strftime is particular as it always uses a single 'time' argument,
1889 // so it is safe to pass a non-literal string.
1890 if (Type == FST_Strftime)
Richard Smith831421f2012-06-25 20:30:08 +00001891 return false;
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00001892
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00001893 // Do not emit diag when the string param is a macro expansion and the
1894 // format is either NSString or CFString. This is a hack to prevent
1895 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
1896 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupasdc170202012-05-04 21:08:08 +00001897 if (Type == FST_NSString &&
1898 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith831421f2012-06-25 20:30:08 +00001899 return false;
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00001900
Chris Lattner655f1412009-04-29 04:59:47 +00001901 // If there are no arguments specified, warn with -Wformat-security, otherwise
1902 // warn only with -Wformat-nonliteral.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001903 if (NumArgs == format_idx+1)
1904 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001905 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00001906 << OrigFormatExpr->getSourceRange();
1907 else
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001908 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001909 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00001910 << OrigFormatExpr->getSourceRange();
Richard Smith831421f2012-06-25 20:30:08 +00001911 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001912}
Ted Kremenek71895b92007-08-14 17:39:48 +00001913
Ted Kremeneke0e53132010-01-28 23:39:18 +00001914namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00001915class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1916protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001917 Sema &S;
1918 const StringLiteral *FExpr;
1919 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001920 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001921 const unsigned NumDataArgs;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001922 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001923 const bool HasVAListArg;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001924 const Expr * const *Args;
1925 const unsigned NumArgs;
Ted Kremenek0d277352010-01-29 01:06:55 +00001926 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001927 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00001928 bool usesPositionalArgs;
1929 bool atFirstArg;
Richard Trieu55733de2011-10-28 00:41:25 +00001930 bool inFunctionCall;
Jordan Roseddcfbc92012-07-19 18:10:23 +00001931 Sema::VariadicCallType CallType;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001932public:
Ted Kremenek826a3452010-07-16 02:11:22 +00001933 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00001934 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00001935 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001936 Expr **args, unsigned numArgs,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001937 unsigned formatIdx, bool inFunctionCall,
1938 Sema::VariadicCallType callType)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001939 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose50687312012-06-04 23:52:23 +00001940 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
1941 Beg(beg), HasVAListArg(hasVAListArg),
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001942 Args(args), NumArgs(numArgs), FormatIdx(formatIdx),
Richard Trieu55733de2011-10-28 00:41:25 +00001943 usesPositionalArgs(false), atFirstArg(true),
Jordan Roseddcfbc92012-07-19 18:10:23 +00001944 inFunctionCall(inFunctionCall), CallType(callType) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001945 CoveredArgs.resize(numDataArgs);
1946 CoveredArgs.reset();
1947 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001948
Ted Kremenek07d161f2010-01-29 01:50:07 +00001949 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001950
Ted Kremenek826a3452010-07-16 02:11:22 +00001951 void HandleIncompleteSpecifier(const char *startSpecifier,
1952 unsigned specifierLen);
Hans Wennborg76517422012-02-22 10:17:01 +00001953
Jordan Rosebbb6bb42012-09-08 04:00:03 +00001954 void HandleInvalidLengthModifier(
1955 const analyze_format_string::FormatSpecifier &FS,
1956 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose8be066e2012-09-08 04:00:12 +00001957 const char *startSpecifier, unsigned specifierLen, unsigned DiagID);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00001958
Hans Wennborg76517422012-02-22 10:17:01 +00001959 void HandleNonStandardLengthModifier(
Jordan Rose8be066e2012-09-08 04:00:12 +00001960 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborg76517422012-02-22 10:17:01 +00001961 const char *startSpecifier, unsigned specifierLen);
1962
1963 void HandleNonStandardConversionSpecifier(
1964 const analyze_format_string::ConversionSpecifier &CS,
1965 const char *startSpecifier, unsigned specifierLen);
1966
Hans Wennborgf8562642012-03-09 10:10:54 +00001967 virtual void HandlePosition(const char *startPos, unsigned posLen);
1968
Ted Kremenekefaff192010-02-27 01:41:03 +00001969 virtual void HandleInvalidPosition(const char *startSpecifier,
1970 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00001971 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00001972
1973 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1974
Ted Kremeneke0e53132010-01-28 23:39:18 +00001975 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001976
Richard Trieu55733de2011-10-28 00:41:25 +00001977 template <typename Range>
1978 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
1979 const Expr *ArgumentExpr,
1980 PartialDiagnostic PDiag,
1981 SourceLocation StringLoc,
1982 bool IsStringLocation, Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00001983 ArrayRef<FixItHint> Fixit = ArrayRef<FixItHint>());
Richard Trieu55733de2011-10-28 00:41:25 +00001984
Ted Kremenek826a3452010-07-16 02:11:22 +00001985protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001986 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1987 const char *startSpec,
1988 unsigned specifierLen,
1989 const char *csStart, unsigned csLen);
Richard Trieu55733de2011-10-28 00:41:25 +00001990
1991 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
1992 const char *startSpec,
1993 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001994
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001995 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00001996 CharSourceRange getSpecifierRange(const char *startSpecifier,
1997 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001998 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001999
Ted Kremenek0d277352010-01-29 01:06:55 +00002000 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00002001
2002 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2003 const analyze_format_string::ConversionSpecifier &CS,
2004 const char *startSpecifier, unsigned specifierLen,
2005 unsigned argIndex);
Richard Trieu55733de2011-10-28 00:41:25 +00002006
2007 template <typename Range>
2008 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2009 bool IsStringLocation, Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002010 ArrayRef<FixItHint> Fixit = ArrayRef<FixItHint>());
Richard Trieu55733de2011-10-28 00:41:25 +00002011
2012 void CheckPositionalAndNonpositionalArgs(
2013 const analyze_format_string::FormatSpecifier *FS);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002014};
2015}
2016
Ted Kremenek826a3452010-07-16 02:11:22 +00002017SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00002018 return OrigFormatExpr->getSourceRange();
2019}
2020
Ted Kremenek826a3452010-07-16 02:11:22 +00002021CharSourceRange CheckFormatHandler::
2022getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002023 SourceLocation Start = getLocationOfByte(startSpecifier);
2024 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2025
2026 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002027 End = End.getLocWithOffset(1);
Tom Care45f9b7e2010-06-21 21:21:01 +00002028
2029 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002030}
2031
Ted Kremenek826a3452010-07-16 02:11:22 +00002032SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002033 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002034}
2035
Ted Kremenek826a3452010-07-16 02:11:22 +00002036void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2037 unsigned specifierLen){
Richard Trieu55733de2011-10-28 00:41:25 +00002038 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2039 getLocationOfByte(startSpecifier),
2040 /*IsStringLocation*/true,
2041 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek808015a2010-01-29 03:16:21 +00002042}
2043
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002044void CheckFormatHandler::HandleInvalidLengthModifier(
2045 const analyze_format_string::FormatSpecifier &FS,
2046 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose8be066e2012-09-08 04:00:12 +00002047 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002048 using namespace analyze_format_string;
2049
2050 const LengthModifier &LM = FS.getLengthModifier();
2051 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2052
2053 // See if we know how to fix this length modifier.
2054 llvm::Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
2055 if (FixedLM) {
Jordan Rose8be066e2012-09-08 04:00:12 +00002056 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002057 getLocationOfByte(LM.getStart()),
2058 /*IsStringLocation*/true,
2059 getSpecifierRange(startSpecifier, specifierLen));
2060
2061 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2062 << FixedLM->toString()
2063 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2064
2065 } else {
Jordan Rose8be066e2012-09-08 04:00:12 +00002066 FixItHint Hint;
2067 if (DiagID == diag::warn_format_nonsensical_length)
2068 Hint = FixItHint::CreateRemoval(LMRange);
2069
2070 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002071 getLocationOfByte(LM.getStart()),
2072 /*IsStringLocation*/true,
2073 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose8be066e2012-09-08 04:00:12 +00002074 Hint);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002075 }
2076}
2077
Hans Wennborg76517422012-02-22 10:17:01 +00002078void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose8be066e2012-09-08 04:00:12 +00002079 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborg76517422012-02-22 10:17:01 +00002080 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose8be066e2012-09-08 04:00:12 +00002081 using namespace analyze_format_string;
2082
2083 const LengthModifier &LM = FS.getLengthModifier();
2084 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2085
2086 // See if we know how to fix this length modifier.
2087 llvm::Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
2088 if (FixedLM) {
2089 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2090 << LM.toString() << 0,
2091 getLocationOfByte(LM.getStart()),
2092 /*IsStringLocation*/true,
2093 getSpecifierRange(startSpecifier, specifierLen));
2094
2095 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2096 << FixedLM->toString()
2097 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2098
2099 } else {
2100 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2101 << LM.toString() << 0,
2102 getLocationOfByte(LM.getStart()),
2103 /*IsStringLocation*/true,
2104 getSpecifierRange(startSpecifier, specifierLen));
2105 }
Hans Wennborg76517422012-02-22 10:17:01 +00002106}
2107
2108void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2109 const analyze_format_string::ConversionSpecifier &CS,
2110 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose670941c2012-09-13 02:11:15 +00002111 using namespace analyze_format_string;
2112
2113 // See if we know how to fix this conversion specifier.
2114 llvm::Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
2115 if (FixedCS) {
2116 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2117 << CS.toString() << /*conversion specifier*/1,
2118 getLocationOfByte(CS.getStart()),
2119 /*IsStringLocation*/true,
2120 getSpecifierRange(startSpecifier, specifierLen));
2121
2122 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2123 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2124 << FixedCS->toString()
2125 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2126 } else {
2127 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2128 << CS.toString() << /*conversion specifier*/1,
2129 getLocationOfByte(CS.getStart()),
2130 /*IsStringLocation*/true,
2131 getSpecifierRange(startSpecifier, specifierLen));
2132 }
Hans Wennborg76517422012-02-22 10:17:01 +00002133}
2134
Hans Wennborgf8562642012-03-09 10:10:54 +00002135void CheckFormatHandler::HandlePosition(const char *startPos,
2136 unsigned posLen) {
2137 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2138 getLocationOfByte(startPos),
2139 /*IsStringLocation*/true,
2140 getSpecifierRange(startPos, posLen));
2141}
2142
Ted Kremenekefaff192010-02-27 01:41:03 +00002143void
Ted Kremenek826a3452010-07-16 02:11:22 +00002144CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2145 analyze_format_string::PositionContext p) {
Richard Trieu55733de2011-10-28 00:41:25 +00002146 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2147 << (unsigned) p,
2148 getLocationOfByte(startPos), /*IsStringLocation*/true,
2149 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002150}
2151
Ted Kremenek826a3452010-07-16 02:11:22 +00002152void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00002153 unsigned posLen) {
Richard Trieu55733de2011-10-28 00:41:25 +00002154 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2155 getLocationOfByte(startPos),
2156 /*IsStringLocation*/true,
2157 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002158}
2159
Ted Kremenek826a3452010-07-16 02:11:22 +00002160void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose50687312012-06-04 23:52:23 +00002161 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0c069442011-03-15 21:18:48 +00002162 // The presence of a null character is likely an error.
Richard Trieu55733de2011-10-28 00:41:25 +00002163 EmitFormatDiagnostic(
2164 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2165 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2166 getFormatStringRange());
Ted Kremenek0c069442011-03-15 21:18:48 +00002167 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002168}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002169
Jordan Rose48716662012-07-19 18:10:08 +00002170// Note that this may return NULL if there was an error parsing or building
2171// one of the argument expressions.
Ted Kremenek826a3452010-07-16 02:11:22 +00002172const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002173 return Args[FirstDataArg + i];
Ted Kremenek826a3452010-07-16 02:11:22 +00002174}
2175
2176void CheckFormatHandler::DoneProcessing() {
2177 // Does the number of data arguments exceed the number of
2178 // format conversions in the format string?
2179 if (!HasVAListArg) {
2180 // Find any arguments that weren't covered.
2181 CoveredArgs.flip();
2182 signed notCoveredArg = CoveredArgs.find_first();
2183 if (notCoveredArg >= 0) {
2184 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose48716662012-07-19 18:10:08 +00002185 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2186 SourceLocation Loc = E->getLocStart();
2187 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2188 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2189 Loc, /*IsStringLocation*/false,
2190 getFormatStringRange());
2191 }
Bob Wilsonc03f2df2012-05-03 19:47:19 +00002192 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002193 }
2194 }
2195}
2196
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002197bool
2198CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2199 SourceLocation Loc,
2200 const char *startSpec,
2201 unsigned specifierLen,
2202 const char *csStart,
2203 unsigned csLen) {
2204
2205 bool keepGoing = true;
2206 if (argIndex < NumDataArgs) {
2207 // Consider the argument coverered, even though the specifier doesn't
2208 // make sense.
2209 CoveredArgs.set(argIndex);
2210 }
2211 else {
2212 // If argIndex exceeds the number of data arguments we
2213 // don't issue a warning because that is just a cascade of warnings (and
2214 // they may have intended '%%' anyway). We don't want to continue processing
2215 // the format string after this point, however, as we will like just get
2216 // gibberish when trying to match arguments.
2217 keepGoing = false;
2218 }
2219
Richard Trieu55733de2011-10-28 00:41:25 +00002220 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2221 << StringRef(csStart, csLen),
2222 Loc, /*IsStringLocation*/true,
2223 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002224
2225 return keepGoing;
2226}
2227
Richard Trieu55733de2011-10-28 00:41:25 +00002228void
2229CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2230 const char *startSpec,
2231 unsigned specifierLen) {
2232 EmitFormatDiagnostic(
2233 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2234 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2235}
2236
Ted Kremenek666a1972010-07-26 19:45:42 +00002237bool
2238CheckFormatHandler::CheckNumArgs(
2239 const analyze_format_string::FormatSpecifier &FS,
2240 const analyze_format_string::ConversionSpecifier &CS,
2241 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2242
2243 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002244 PartialDiagnostic PDiag = FS.usesPositionalArg()
2245 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2246 << (argIndex+1) << NumDataArgs)
2247 : S.PDiag(diag::warn_printf_insufficient_data_args);
2248 EmitFormatDiagnostic(
2249 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2250 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek666a1972010-07-26 19:45:42 +00002251 return false;
2252 }
2253 return true;
2254}
2255
Richard Trieu55733de2011-10-28 00:41:25 +00002256template<typename Range>
2257void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2258 SourceLocation Loc,
2259 bool IsStringLocation,
2260 Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002261 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002262 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu55733de2011-10-28 00:41:25 +00002263 Loc, IsStringLocation, StringRange, FixIt);
2264}
2265
2266/// \brief If the format string is not within the funcion call, emit a note
2267/// so that the function call and string are in diagnostic messages.
2268///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00002269/// \param InFunctionCall if true, the format string is within the function
Richard Trieu55733de2011-10-28 00:41:25 +00002270/// call and only one diagnostic message will be produced. Otherwise, an
2271/// extra note will be emitted pointing to location of the format string.
2272///
2273/// \param ArgumentExpr the expression that is passed as the format string
2274/// argument in the function call. Used for getting locations when two
2275/// diagnostics are emitted.
2276///
2277/// \param PDiag the callee should already have provided any strings for the
2278/// diagnostic message. This function only adds locations and fixits
2279/// to diagnostics.
2280///
2281/// \param Loc primary location for diagnostic. If two diagnostics are
2282/// required, one will be at Loc and a new SourceLocation will be created for
2283/// the other one.
2284///
2285/// \param IsStringLocation if true, Loc points to the format string should be
2286/// used for the note. Otherwise, Loc points to the argument list and will
2287/// be used with PDiag.
2288///
2289/// \param StringRange some or all of the string to highlight. This is
2290/// templated so it can accept either a CharSourceRange or a SourceRange.
2291///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00002292/// \param FixIt optional fix it hint for the format string.
Richard Trieu55733de2011-10-28 00:41:25 +00002293template<typename Range>
2294void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2295 const Expr *ArgumentExpr,
2296 PartialDiagnostic PDiag,
2297 SourceLocation Loc,
2298 bool IsStringLocation,
2299 Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002300 ArrayRef<FixItHint> FixIt) {
2301 if (InFunctionCall) {
2302 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2303 D << StringRange;
2304 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2305 I != E; ++I) {
2306 D << *I;
2307 }
2308 } else {
Richard Trieu55733de2011-10-28 00:41:25 +00002309 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2310 << ArgumentExpr->getSourceRange();
Jordan Roseec087352012-09-05 22:56:26 +00002311
2312 const Sema::SemaDiagnosticBuilder &Note =
2313 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2314 diag::note_format_string_defined);
2315
2316 Note << StringRange;
2317 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2318 I != E; ++I) {
2319 Note << *I;
2320 }
Richard Trieu55733de2011-10-28 00:41:25 +00002321 }
2322}
2323
Ted Kremenek826a3452010-07-16 02:11:22 +00002324//===--- CHECK: Printf format string checking ------------------------------===//
2325
2326namespace {
2327class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose50687312012-06-04 23:52:23 +00002328 bool ObjCContext;
Ted Kremenek826a3452010-07-16 02:11:22 +00002329public:
2330 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2331 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002332 unsigned numDataArgs, bool isObjC,
Ted Kremenek826a3452010-07-16 02:11:22 +00002333 const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002334 Expr **Args, unsigned NumArgs,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002335 unsigned formatIdx, bool inFunctionCall,
2336 Sema::VariadicCallType CallType)
Ted Kremenek826a3452010-07-16 02:11:22 +00002337 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002338 numDataArgs, beg, hasVAListArg, Args, NumArgs,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002339 formatIdx, inFunctionCall, CallType), ObjCContext(isObjC)
2340 {}
2341
Ted Kremenek826a3452010-07-16 02:11:22 +00002342
2343 bool HandleInvalidPrintfConversionSpecifier(
2344 const analyze_printf::PrintfSpecifier &FS,
2345 const char *startSpecifier,
2346 unsigned specifierLen);
2347
2348 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2349 const char *startSpecifier,
2350 unsigned specifierLen);
Richard Smith831421f2012-06-25 20:30:08 +00002351 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2352 const char *StartSpecifier,
2353 unsigned SpecifierLen,
2354 const Expr *E);
2355
Ted Kremenek826a3452010-07-16 02:11:22 +00002356 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2357 const char *startSpecifier, unsigned specifierLen);
2358 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2359 const analyze_printf::OptionalAmount &Amt,
2360 unsigned type,
2361 const char *startSpecifier, unsigned specifierLen);
2362 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2363 const analyze_printf::OptionalFlag &flag,
2364 const char *startSpecifier, unsigned specifierLen);
2365 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2366 const analyze_printf::OptionalFlag &ignoredFlag,
2367 const analyze_printf::OptionalFlag &flag,
2368 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgf3749f42012-08-07 08:11:26 +00002369 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith831421f2012-06-25 20:30:08 +00002370 const Expr *E, const CharSourceRange &CSR);
2371
Ted Kremenek826a3452010-07-16 02:11:22 +00002372};
2373}
2374
2375bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2376 const analyze_printf::PrintfSpecifier &FS,
2377 const char *startSpecifier,
2378 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002379 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002380 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002381
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002382 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2383 getLocationOfByte(CS.getStart()),
2384 startSpecifier, specifierLen,
2385 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00002386}
2387
Ted Kremenek826a3452010-07-16 02:11:22 +00002388bool CheckPrintfHandler::HandleAmount(
2389 const analyze_format_string::OptionalAmount &Amt,
2390 unsigned k, const char *startSpecifier,
2391 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002392
2393 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002394 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002395 unsigned argIndex = Amt.getArgIndex();
2396 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002397 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2398 << k,
2399 getLocationOfByte(Amt.getStart()),
2400 /*IsStringLocation*/true,
2401 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002402 // Don't do any more checking. We will just emit
2403 // spurious errors.
2404 return false;
2405 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002406
Ted Kremenek0d277352010-01-29 01:06:55 +00002407 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00002408 // Although not in conformance with C99, we also allow the argument to be
2409 // an 'unsigned int' as that is a reasonably safe case. GCC also
2410 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002411 CoveredArgs.set(argIndex);
2412 const Expr *Arg = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00002413 if (!Arg)
2414 return false;
2415
Ted Kremenek0d277352010-01-29 01:06:55 +00002416 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002417
Hans Wennborgf3749f42012-08-07 08:11:26 +00002418 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
2419 assert(AT.isValid());
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002420
Hans Wennborgf3749f42012-08-07 08:11:26 +00002421 if (!AT.matchesType(S.Context, T)) {
Richard Trieu55733de2011-10-28 00:41:25 +00002422 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgf3749f42012-08-07 08:11:26 +00002423 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu55733de2011-10-28 00:41:25 +00002424 << T << Arg->getSourceRange(),
2425 getLocationOfByte(Amt.getStart()),
2426 /*IsStringLocation*/true,
2427 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002428 // Don't do any more checking. We will just emit
2429 // spurious errors.
2430 return false;
2431 }
2432 }
2433 }
2434 return true;
2435}
Ted Kremenek0d277352010-01-29 01:06:55 +00002436
Tom Caree4ee9662010-06-17 19:00:27 +00002437void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00002438 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002439 const analyze_printf::OptionalAmount &Amt,
2440 unsigned type,
2441 const char *startSpecifier,
2442 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002443 const analyze_printf::PrintfConversionSpecifier &CS =
2444 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00002445
Richard Trieu55733de2011-10-28 00:41:25 +00002446 FixItHint fixit =
2447 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2448 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2449 Amt.getConstantLength()))
2450 : FixItHint();
2451
2452 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2453 << type << CS.toString(),
2454 getLocationOfByte(Amt.getStart()),
2455 /*IsStringLocation*/true,
2456 getSpecifierRange(startSpecifier, specifierLen),
2457 fixit);
Tom Caree4ee9662010-06-17 19:00:27 +00002458}
2459
Ted Kremenek826a3452010-07-16 02:11:22 +00002460void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002461 const analyze_printf::OptionalFlag &flag,
2462 const char *startSpecifier,
2463 unsigned specifierLen) {
2464 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002465 const analyze_printf::PrintfConversionSpecifier &CS =
2466 FS.getConversionSpecifier();
Richard Trieu55733de2011-10-28 00:41:25 +00002467 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2468 << flag.toString() << CS.toString(),
2469 getLocationOfByte(flag.getPosition()),
2470 /*IsStringLocation*/true,
2471 getSpecifierRange(startSpecifier, specifierLen),
2472 FixItHint::CreateRemoval(
2473 getSpecifierRange(flag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002474}
2475
2476void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00002477 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002478 const analyze_printf::OptionalFlag &ignoredFlag,
2479 const analyze_printf::OptionalFlag &flag,
2480 const char *startSpecifier,
2481 unsigned specifierLen) {
2482 // Warn about ignored flag with a fixit removal.
Richard Trieu55733de2011-10-28 00:41:25 +00002483 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2484 << ignoredFlag.toString() << flag.toString(),
2485 getLocationOfByte(ignoredFlag.getPosition()),
2486 /*IsStringLocation*/true,
2487 getSpecifierRange(startSpecifier, specifierLen),
2488 FixItHint::CreateRemoval(
2489 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002490}
2491
Richard Smith831421f2012-06-25 20:30:08 +00002492// Determines if the specified is a C++ class or struct containing
2493// a member with the specified name and kind (e.g. a CXXMethodDecl named
2494// "c_str()").
2495template<typename MemberKind>
2496static llvm::SmallPtrSet<MemberKind*, 1>
2497CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2498 const RecordType *RT = Ty->getAs<RecordType>();
2499 llvm::SmallPtrSet<MemberKind*, 1> Results;
2500
2501 if (!RT)
2502 return Results;
2503 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
2504 if (!RD)
2505 return Results;
2506
2507 LookupResult R(S, &S.PP.getIdentifierTable().get(Name), SourceLocation(),
2508 Sema::LookupMemberName);
2509
2510 // We just need to include all members of the right kind turned up by the
2511 // filter, at this point.
2512 if (S.LookupQualifiedName(R, RT->getDecl()))
2513 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2514 NamedDecl *decl = (*I)->getUnderlyingDecl();
2515 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
2516 Results.insert(FK);
2517 }
2518 return Results;
2519}
2520
2521// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgf3749f42012-08-07 08:11:26 +00002522// better diagnostic if so. AT is assumed to be valid.
Richard Smith831421f2012-06-25 20:30:08 +00002523// Returns true when a c_str() conversion method is found.
2524bool CheckPrintfHandler::checkForCStrMembers(
Hans Wennborgf3749f42012-08-07 08:11:26 +00002525 const analyze_printf::ArgType &AT, const Expr *E,
Richard Smith831421f2012-06-25 20:30:08 +00002526 const CharSourceRange &CSR) {
2527 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2528
2529 MethodSet Results =
2530 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
2531
2532 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2533 MI != ME; ++MI) {
2534 const CXXMethodDecl *Method = *MI;
2535 if (Method->getNumParams() == 0 &&
Hans Wennborgf3749f42012-08-07 08:11:26 +00002536 AT.matchesType(S.Context, Method->getResultType())) {
Richard Smith831421f2012-06-25 20:30:08 +00002537 // FIXME: Suggest parens if the expression needs them.
2538 SourceLocation EndLoc =
2539 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd());
2540 S.Diag(E->getLocStart(), diag::note_printf_c_str)
2541 << "c_str()"
2542 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
2543 return true;
2544 }
2545 }
2546
2547 return false;
2548}
2549
Ted Kremeneke0e53132010-01-28 23:39:18 +00002550bool
Ted Kremenek826a3452010-07-16 02:11:22 +00002551CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002552 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00002553 const char *startSpecifier,
2554 unsigned specifierLen) {
2555
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002556 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00002557 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002558 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00002559
Ted Kremenekbaa40062010-07-19 22:01:06 +00002560 if (FS.consumesDataArgument()) {
2561 if (atFirstArg) {
2562 atFirstArg = false;
2563 usesPositionalArgs = FS.usesPositionalArg();
2564 }
2565 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002566 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2567 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002568 return false;
2569 }
Ted Kremenek0d277352010-01-29 01:06:55 +00002570 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002571
Ted Kremenekefaff192010-02-27 01:41:03 +00002572 // First check if the field width, precision, and conversion specifier
2573 // have matching data arguments.
2574 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2575 startSpecifier, specifierLen)) {
2576 return false;
2577 }
2578
2579 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2580 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002581 return false;
2582 }
2583
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002584 if (!CS.consumesDataArgument()) {
2585 // FIXME: Technically specifying a precision or field width here
2586 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002587 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002588 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002589
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002590 // Consume the argument.
2591 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00002592 if (argIndex < NumDataArgs) {
2593 // The check to see if the argIndex is valid will come later.
2594 // We set the bit here because we may exit early from this
2595 // function if we encounter some other error.
2596 CoveredArgs.set(argIndex);
2597 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002598
2599 // Check for using an Objective-C specific conversion specifier
2600 // in a non-ObjC literal.
Jordan Rose50687312012-06-04 23:52:23 +00002601 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002602 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2603 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002604 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002605
Tom Caree4ee9662010-06-17 19:00:27 +00002606 // Check for invalid use of field width
2607 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002608 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00002609 startSpecifier, specifierLen);
2610 }
2611
2612 // Check for invalid use of precision
2613 if (!FS.hasValidPrecision()) {
2614 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
2615 startSpecifier, specifierLen);
2616 }
2617
2618 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00002619 if (!FS.hasValidThousandsGroupingPrefix())
2620 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002621 if (!FS.hasValidLeadingZeros())
2622 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
2623 if (!FS.hasValidPlusPrefix())
2624 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00002625 if (!FS.hasValidSpacePrefix())
2626 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002627 if (!FS.hasValidAlternativeForm())
2628 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
2629 if (!FS.hasValidLeftJustified())
2630 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
2631
2632 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00002633 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
2634 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
2635 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002636 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
2637 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
2638 startSpecifier, specifierLen);
2639
2640 // Check the length modifier is valid with the given conversion specifier.
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002641 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose8be066e2012-09-08 04:00:12 +00002642 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
2643 diag::warn_format_nonsensical_length);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002644 else if (!FS.hasStandardLengthModifier())
Jordan Rose8be066e2012-09-08 04:00:12 +00002645 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002646 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose8be066e2012-09-08 04:00:12 +00002647 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
2648 diag::warn_format_non_standard_conversion_spec);
Tom Caree4ee9662010-06-17 19:00:27 +00002649
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002650 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
2651 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
2652
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002653 // The remaining checks depend on the data arguments.
2654 if (HasVAListArg)
2655 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002656
Ted Kremenek666a1972010-07-26 19:45:42 +00002657 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002658 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002659
Jordan Rose48716662012-07-19 18:10:08 +00002660 const Expr *Arg = getDataArg(argIndex);
2661 if (!Arg)
2662 return true;
2663
2664 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith831421f2012-06-25 20:30:08 +00002665}
2666
Jordan Roseec087352012-09-05 22:56:26 +00002667static bool requiresParensToAddCast(const Expr *E) {
2668 // FIXME: We should have a general way to reason about operator
2669 // precedence and whether parens are actually needed here.
2670 // Take care of a few common cases where they aren't.
2671 const Expr *Inside = E->IgnoreImpCasts();
2672 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
2673 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
2674
2675 switch (Inside->getStmtClass()) {
2676 case Stmt::ArraySubscriptExprClass:
2677 case Stmt::CallExprClass:
2678 case Stmt::DeclRefExprClass:
2679 case Stmt::MemberExprClass:
2680 case Stmt::ObjCIvarRefExprClass:
2681 case Stmt::ObjCMessageExprClass:
2682 case Stmt::ObjCPropertyRefExprClass:
2683 case Stmt::ParenExprClass:
2684 case Stmt::UnaryOperatorClass:
2685 return false;
2686 default:
2687 return true;
2688 }
2689}
2690
Richard Smith831421f2012-06-25 20:30:08 +00002691bool
2692CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2693 const char *StartSpecifier,
2694 unsigned SpecifierLen,
2695 const Expr *E) {
2696 using namespace analyze_format_string;
2697 using namespace analyze_printf;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002698 // Now type check the data expression that matches the
2699 // format specifier.
Hans Wennborgf3749f42012-08-07 08:11:26 +00002700 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
2701 ObjCContext);
Jordan Rose614a8652012-09-05 22:56:19 +00002702 if (!AT.isValid())
2703 return true;
Jordan Roseec087352012-09-05 22:56:26 +00002704
2705 QualType IntendedTy = E->getType();
2706 if (AT.matchesType(S.Context, IntendedTy))
Jordan Rose614a8652012-09-05 22:56:19 +00002707 return true;
Jordan Roseee0259d2012-06-04 22:48:57 +00002708
Jordan Rose614a8652012-09-05 22:56:19 +00002709 // Look through argument promotions for our error message's reported type.
2710 // This includes the integral and floating promotions, but excludes array
2711 // and function pointer decay; seeing that an argument intended to be a
2712 // string has type 'char [6]' is probably more confusing than 'char *'.
2713 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2714 if (ICE->getCastKind() == CK_IntegralCast ||
2715 ICE->getCastKind() == CK_FloatingCast) {
2716 E = ICE->getSubExpr();
Jordan Roseec087352012-09-05 22:56:26 +00002717 IntendedTy = E->getType();
Jordan Rose614a8652012-09-05 22:56:19 +00002718
2719 // Check if we didn't match because of an implicit cast from a 'char'
2720 // or 'short' to an 'int'. This is done because printf is a varargs
2721 // function.
2722 if (ICE->getType() == S.Context.IntTy ||
2723 ICE->getType() == S.Context.UnsignedIntTy) {
2724 // All further checking is done on the subexpression.
Jordan Roseec087352012-09-05 22:56:26 +00002725 if (AT.matchesType(S.Context, IntendedTy))
Jordan Rose614a8652012-09-05 22:56:19 +00002726 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00002727 }
Jordan Roseee0259d2012-06-04 22:48:57 +00002728 }
Jordan Rose614a8652012-09-05 22:56:19 +00002729 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002730
Jordan Roseec087352012-09-05 22:56:26 +00002731 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
2732 // Special-case some of Darwin's platform-independence types.
2733 if (const TypedefType *UserTy = IntendedTy->getAs<TypedefType>()) {
2734 StringRef Name = UserTy->getDecl()->getName();
2735 IntendedTy = llvm::StringSwitch<QualType>(Name)
2736 .Case("NSInteger", S.Context.LongTy)
2737 .Case("NSUInteger", S.Context.UnsignedLongTy)
2738 .Case("SInt32", S.Context.IntTy)
2739 .Case("UInt32", S.Context.UnsignedIntTy)
2740 .Default(IntendedTy);
2741 }
2742 }
2743
Jordan Rose614a8652012-09-05 22:56:19 +00002744 // We may be able to offer a FixItHint if it is a supported type.
2745 PrintfSpecifier fixedFS = FS;
Jordan Roseec087352012-09-05 22:56:26 +00002746 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose614a8652012-09-05 22:56:19 +00002747 S.Context, ObjCContext);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002748
Jordan Rose614a8652012-09-05 22:56:19 +00002749 if (success) {
2750 // Get the fix string from the fixed format specifier
2751 SmallString<16> buf;
2752 llvm::raw_svector_ostream os(buf);
2753 fixedFS.toString(os);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002754
Jordan Roseec087352012-09-05 22:56:26 +00002755 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
2756
2757 if (IntendedTy != E->getType()) {
2758 // The canonical type for formatting this value is different from the
2759 // actual type of the expression. (This occurs, for example, with Darwin's
2760 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
2761 // should be printed as 'long' for 64-bit compatibility.)
2762 // Rather than emitting a normal format/argument mismatch, we want to
2763 // add a cast to the recommended type (and correct the format string
2764 // if necessary).
2765 SmallString<16> CastBuf;
2766 llvm::raw_svector_ostream CastFix(CastBuf);
2767 CastFix << "(";
2768 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
2769 CastFix << ")";
2770
2771 SmallVector<FixItHint,4> Hints;
2772 if (!AT.matchesType(S.Context, IntendedTy))
2773 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
2774
2775 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
2776 // If there's already a cast present, just replace it.
2777 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
2778 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
2779
2780 } else if (!requiresParensToAddCast(E)) {
2781 // If the expression has high enough precedence,
2782 // just write the C-style cast.
2783 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
2784 CastFix.str()));
2785 } else {
2786 // Otherwise, add parens around the expression as well as the cast.
2787 CastFix << "(";
2788 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
2789 CastFix.str()));
2790
2791 SourceLocation After = S.PP.getLocForEndOfToken(E->getLocEnd());
2792 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
2793 }
2794
2795 // We extract the name from the typedef because we don't want to show
2796 // the underlying type in the diagnostic.
2797 const TypedefType *UserTy = cast<TypedefType>(E->getType());
2798 StringRef Name = UserTy->getDecl()->getName();
2799
2800 // Finally, emit the diagnostic.
2801 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
2802 << Name << IntendedTy
2803 << E->getSourceRange(),
2804 E->getLocStart(), /*IsStringLocation=*/false,
2805 SpecRange, Hints);
2806 } else {
2807 EmitFormatDiagnostic(
2808 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2809 << AT.getRepresentativeTypeName(S.Context) << IntendedTy
2810 << E->getSourceRange(),
2811 E->getLocStart(),
2812 /*IsStringLocation*/false,
2813 SpecRange,
2814 FixItHint::CreateReplacement(SpecRange, os.str()));
2815 }
Jordan Rose614a8652012-09-05 22:56:19 +00002816 } else {
2817 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
2818 SpecifierLen);
2819 // Since the warning for passing non-POD types to variadic functions
2820 // was deferred until now, we emit a warning for non-POD
2821 // arguments here.
2822 if (S.isValidVarArgType(E->getType()) == Sema::VAK_Invalid) {
2823 unsigned DiagKind;
2824 if (E->getType()->isObjCObjectType())
2825 DiagKind = diag::err_cannot_pass_objc_interface_to_vararg_format;
2826 else
2827 DiagKind = diag::warn_non_pod_vararg_with_format_string;
2828
2829 EmitFormatDiagnostic(
2830 S.PDiag(DiagKind)
2831 << S.getLangOpts().CPlusPlus0x
2832 << E->getType()
2833 << CallType
2834 << AT.getRepresentativeTypeName(S.Context)
2835 << CSR
2836 << E->getSourceRange(),
2837 E->getLocStart(), /*IsStringLocation*/false, CSR);
2838
2839 checkForCStrMembers(AT, E, CSR);
2840 } else
Richard Trieu55733de2011-10-28 00:41:25 +00002841 EmitFormatDiagnostic(
2842 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborgf3749f42012-08-07 08:11:26 +00002843 << AT.getRepresentativeTypeName(S.Context) << E->getType()
Jordan Rose614a8652012-09-05 22:56:19 +00002844 << CSR
Richard Smith831421f2012-06-25 20:30:08 +00002845 << E->getSourceRange(),
Jordan Rose614a8652012-09-05 22:56:19 +00002846 E->getLocStart(), /*IsStringLocation*/false, CSR);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002847 }
2848
Ted Kremeneke0e53132010-01-28 23:39:18 +00002849 return true;
2850}
2851
Ted Kremenek826a3452010-07-16 02:11:22 +00002852//===--- CHECK: Scanf format string checking ------------------------------===//
2853
2854namespace {
2855class CheckScanfHandler : public CheckFormatHandler {
2856public:
2857 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
2858 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002859 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002860 Expr **Args, unsigned NumArgs,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002861 unsigned formatIdx, bool inFunctionCall,
2862 Sema::VariadicCallType CallType)
Ted Kremenek826a3452010-07-16 02:11:22 +00002863 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002864 numDataArgs, beg, hasVAListArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002865 Args, NumArgs, formatIdx, inFunctionCall, CallType)
2866 {}
Ted Kremenek826a3452010-07-16 02:11:22 +00002867
2868 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
2869 const char *startSpecifier,
2870 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002871
2872 bool HandleInvalidScanfConversionSpecifier(
2873 const analyze_scanf::ScanfSpecifier &FS,
2874 const char *startSpecifier,
2875 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00002876
2877 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00002878};
Ted Kremenek07d161f2010-01-29 01:50:07 +00002879}
Ted Kremeneke0e53132010-01-28 23:39:18 +00002880
Ted Kremenekb7c21012010-07-16 18:28:03 +00002881void CheckScanfHandler::HandleIncompleteScanList(const char *start,
2882 const char *end) {
Richard Trieu55733de2011-10-28 00:41:25 +00002883 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
2884 getLocationOfByte(end), /*IsStringLocation*/true,
2885 getSpecifierRange(start, end - start));
Ted Kremenekb7c21012010-07-16 18:28:03 +00002886}
2887
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002888bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
2889 const analyze_scanf::ScanfSpecifier &FS,
2890 const char *startSpecifier,
2891 unsigned specifierLen) {
2892
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002893 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002894 FS.getConversionSpecifier();
2895
2896 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2897 getLocationOfByte(CS.getStart()),
2898 startSpecifier, specifierLen,
2899 CS.getStart(), CS.getLength());
2900}
2901
Ted Kremenek826a3452010-07-16 02:11:22 +00002902bool CheckScanfHandler::HandleScanfSpecifier(
2903 const analyze_scanf::ScanfSpecifier &FS,
2904 const char *startSpecifier,
2905 unsigned specifierLen) {
2906
2907 using namespace analyze_scanf;
2908 using namespace analyze_format_string;
2909
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002910 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002911
Ted Kremenekbaa40062010-07-19 22:01:06 +00002912 // Handle case where '%' and '*' don't consume an argument. These shouldn't
2913 // be used to decide if we are using positional arguments consistently.
2914 if (FS.consumesDataArgument()) {
2915 if (atFirstArg) {
2916 atFirstArg = false;
2917 usesPositionalArgs = FS.usesPositionalArg();
2918 }
2919 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002920 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2921 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002922 return false;
2923 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002924 }
2925
2926 // Check if the field with is non-zero.
2927 const OptionalAmount &Amt = FS.getFieldWidth();
2928 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
2929 if (Amt.getConstantAmount() == 0) {
2930 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
2931 Amt.getConstantLength());
Richard Trieu55733de2011-10-28 00:41:25 +00002932 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
2933 getLocationOfByte(Amt.getStart()),
2934 /*IsStringLocation*/true, R,
2935 FixItHint::CreateRemoval(R));
Ted Kremenek826a3452010-07-16 02:11:22 +00002936 }
2937 }
2938
2939 if (!FS.consumesDataArgument()) {
2940 // FIXME: Technically specifying a precision or field width here
2941 // makes no sense. Worth issuing a warning at some point.
2942 return true;
2943 }
2944
2945 // Consume the argument.
2946 unsigned argIndex = FS.getArgIndex();
2947 if (argIndex < NumDataArgs) {
2948 // The check to see if the argIndex is valid will come later.
2949 // We set the bit here because we may exit early from this
2950 // function if we encounter some other error.
2951 CoveredArgs.set(argIndex);
2952 }
2953
Ted Kremenek1e51c202010-07-20 20:04:47 +00002954 // Check the length modifier is valid with the given conversion specifier.
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002955 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose8be066e2012-09-08 04:00:12 +00002956 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
2957 diag::warn_format_nonsensical_length);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002958 else if (!FS.hasStandardLengthModifier())
Jordan Rose8be066e2012-09-08 04:00:12 +00002959 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002960 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose8be066e2012-09-08 04:00:12 +00002961 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
2962 diag::warn_format_non_standard_conversion_spec);
Hans Wennborg76517422012-02-22 10:17:01 +00002963
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002964 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
2965 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
2966
Ted Kremenek826a3452010-07-16 02:11:22 +00002967 // The remaining checks depend on the data arguments.
2968 if (HasVAListArg)
2969 return true;
2970
Ted Kremenek666a1972010-07-26 19:45:42 +00002971 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00002972 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00002973
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002974 // Check that the argument type matches the format specifier.
2975 const Expr *Ex = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00002976 if (!Ex)
2977 return true;
2978
Hans Wennborg58e1e542012-08-07 08:59:46 +00002979 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
2980 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002981 ScanfSpecifier fixedFS = FS;
David Blaikie4e4d0842012-03-11 07:00:24 +00002982 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
Hans Wennborgbe6126a2012-02-15 09:59:46 +00002983 S.Context);
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002984
2985 if (success) {
2986 // Get the fix string from the fixed format specifier.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002987 SmallString<128> buf;
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002988 llvm::raw_svector_ostream os(buf);
2989 fixedFS.toString(os);
2990
2991 EmitFormatDiagnostic(
2992 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg58e1e542012-08-07 08:59:46 +00002993 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002994 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00002995 Ex->getLocStart(),
2996 /*IsStringLocation*/false,
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002997 getSpecifierRange(startSpecifier, specifierLen),
2998 FixItHint::CreateReplacement(
2999 getSpecifierRange(startSpecifier, specifierLen),
3000 os.str()));
3001 } else {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003002 EmitFormatDiagnostic(
3003 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg58e1e542012-08-07 08:59:46 +00003004 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003005 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00003006 Ex->getLocStart(),
3007 /*IsStringLocation*/false,
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003008 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003009 }
3010 }
3011
Ted Kremenek826a3452010-07-16 02:11:22 +00003012 return true;
3013}
3014
3015void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00003016 const Expr *OrigFormatExpr,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003017 Expr **Args, unsigned NumArgs,
3018 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003019 unsigned firstDataArg, FormatStringType Type,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003020 bool inFunctionCall, VariadicCallType CallType) {
Ted Kremenek826a3452010-07-16 02:11:22 +00003021
Ted Kremeneke0e53132010-01-28 23:39:18 +00003022 // CHECK: is the format string a wide literal?
Richard Smithdf9ef1b2012-06-13 05:37:23 +00003023 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu55733de2011-10-28 00:41:25 +00003024 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003025 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00003026 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3027 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00003028 return;
3029 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003030
Ted Kremeneke0e53132010-01-28 23:39:18 +00003031 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner5f9e2722011-07-23 10:55:15 +00003032 StringRef StrRef = FExpr->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00003033 const char *Str = StrRef.data();
3034 unsigned StrLen = StrRef.size();
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003035 const unsigned numDataArgs = NumArgs - firstDataArg;
Ted Kremenek826a3452010-07-16 02:11:22 +00003036
Ted Kremeneke0e53132010-01-28 23:39:18 +00003037 // CHECK: empty format string?
Ted Kremenek4cd57912011-09-29 05:52:16 +00003038 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu55733de2011-10-28 00:41:25 +00003039 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003040 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00003041 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3042 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00003043 return;
3044 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003045
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003046 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek826a3452010-07-16 02:11:22 +00003047 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00003048 numDataArgs, (Type == FST_NSString),
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003049 Str, HasVAListArg, Args, NumArgs, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003050 inFunctionCall, CallType);
Ted Kremenek826a3452010-07-16 02:11:22 +00003051
Hans Wennborgd02deeb2011-12-15 10:25:47 +00003052 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose275b6f52012-09-13 02:11:03 +00003053 getLangOpts(),
3054 Context.getTargetInfo()))
Ted Kremenek826a3452010-07-16 02:11:22 +00003055 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003056 } else if (Type == FST_Scanf) {
Jordan Rose50687312012-06-04 23:52:23 +00003057 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003058 Str, HasVAListArg, Args, NumArgs, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003059 inFunctionCall, CallType);
Ted Kremenek826a3452010-07-16 02:11:22 +00003060
Hans Wennborgd02deeb2011-12-15 10:25:47 +00003061 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose275b6f52012-09-13 02:11:03 +00003062 getLangOpts(),
3063 Context.getTargetInfo()))
Ted Kremenek826a3452010-07-16 02:11:22 +00003064 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003065 } // TODO: handle other formats
Ted Kremenekce7024e2010-01-28 01:18:22 +00003066}
3067
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003068//===--- CHECK: Standard memory functions ---------------------------------===//
3069
Douglas Gregor2a053a32011-05-03 20:05:22 +00003070/// \brief Determine whether the given type is a dynamic class type (e.g.,
3071/// whether it has a vtable).
3072static bool isDynamicClassType(QualType T) {
3073 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3074 if (CXXRecordDecl *Definition = Record->getDefinition())
3075 if (Definition->isDynamicClass())
3076 return true;
3077
3078 return false;
3079}
3080
Chandler Carrutha72a12f2011-06-21 23:04:20 +00003081/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth000d4282011-06-16 09:09:40 +00003082/// otherwise returns NULL.
3083static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Webere4a1c642011-06-14 16:14:58 +00003084 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth000d4282011-06-16 09:09:40 +00003085 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3086 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
3087 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00003088
Chandler Carruth000d4282011-06-16 09:09:40 +00003089 return 0;
3090}
3091
Chandler Carrutha72a12f2011-06-21 23:04:20 +00003092/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth000d4282011-06-16 09:09:40 +00003093static QualType getSizeOfArgType(const Expr* E) {
3094 if (const UnaryExprOrTypeTraitExpr *SizeOf =
3095 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3096 if (SizeOf->getKind() == clang::UETT_SizeOf)
3097 return SizeOf->getTypeOfArgument();
3098
3099 return QualType();
Nico Webere4a1c642011-06-14 16:14:58 +00003100}
3101
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003102/// \brief Check for dangerous or invalid arguments to memset().
3103///
Chandler Carruth929f0132011-06-03 06:23:57 +00003104/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003105/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
3106/// function calls.
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003107///
3108/// \param Call The call expression to diagnose.
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003109void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks0a151a12012-01-17 00:37:07 +00003110 unsigned BId,
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003111 IdentifierInfo *FnName) {
Anna Zaks0a151a12012-01-17 00:37:07 +00003112 assert(BId != 0);
3113
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00003114 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor707a23e2011-06-16 17:56:04 +00003115 // we have enough arguments, and if not, abort further checking.
Anna Zaks0a151a12012-01-17 00:37:07 +00003116 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Webercda57822011-10-13 22:30:23 +00003117 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00003118 return;
3119
Anna Zaks0a151a12012-01-17 00:37:07 +00003120 unsigned LastArg = (BId == Builtin::BImemset ||
3121 BId == Builtin::BIstrndup ? 1 : 2);
3122 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Webercda57822011-10-13 22:30:23 +00003123 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth000d4282011-06-16 09:09:40 +00003124
3125 // We have special checking when the length is a sizeof expression.
3126 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
3127 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
3128 llvm::FoldingSetNodeID SizeOfArgID;
3129
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003130 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
3131 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00003132 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003133
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003134 QualType DestTy = Dest->getType();
3135 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
3136 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00003137
Chandler Carruth000d4282011-06-16 09:09:40 +00003138 // Never warn about void type pointers. This can be used to suppress
3139 // false positives.
3140 if (PointeeTy->isVoidType())
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003141 continue;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003142
Chandler Carruth000d4282011-06-16 09:09:40 +00003143 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
3144 // actually comparing the expressions for equality. Because computing the
3145 // expression IDs can be expensive, we only do this if the diagnostic is
3146 // enabled.
3147 if (SizeOfArg &&
3148 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
3149 SizeOfArg->getExprLoc())) {
3150 // We only compute IDs for expressions if the warning is enabled, and
3151 // cache the sizeof arg's ID.
3152 if (SizeOfArgID == llvm::FoldingSetNodeID())
3153 SizeOfArg->Profile(SizeOfArgID, Context, true);
3154 llvm::FoldingSetNodeID DestID;
3155 Dest->Profile(DestID, Context, true);
3156 if (DestID == SizeOfArgID) {
Nico Webercda57822011-10-13 22:30:23 +00003157 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
3158 // over sizeof(src) as well.
Chandler Carruth000d4282011-06-16 09:09:40 +00003159 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks6fcb3722012-05-30 00:34:21 +00003160 StringRef ReadableName = FnName->getName();
3161
Chandler Carruth000d4282011-06-16 09:09:40 +00003162 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaks90c78322012-05-30 23:14:52 +00003163 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth000d4282011-06-16 09:09:40 +00003164 ActionIdx = 1; // If its an address-of operator, just remove it.
3165 if (Context.getTypeSize(PointeeTy) == Context.getCharWidth())
3166 ActionIdx = 2; // If the pointee's size is sizeof(char),
3167 // suggest an explicit length.
Anna Zaks6fcb3722012-05-30 00:34:21 +00003168
3169 // If the function is defined as a builtin macro, do not show macro
3170 // expansion.
3171 SourceLocation SL = SizeOfArg->getExprLoc();
3172 SourceRange DSR = Dest->getSourceRange();
3173 SourceRange SSR = SizeOfArg->getSourceRange();
3174 SourceManager &SM = PP.getSourceManager();
3175
3176 if (SM.isMacroArgExpansion(SL)) {
3177 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
3178 SL = SM.getSpellingLoc(SL);
3179 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
3180 SM.getSpellingLoc(DSR.getEnd()));
3181 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
3182 SM.getSpellingLoc(SSR.getEnd()));
3183 }
3184
Anna Zaks90c78322012-05-30 23:14:52 +00003185 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth000d4282011-06-16 09:09:40 +00003186 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks6fcb3722012-05-30 00:34:21 +00003187 << ReadableName
Anna Zaks90c78322012-05-30 23:14:52 +00003188 << PointeeTy
3189 << DestTy
Anna Zaks6fcb3722012-05-30 00:34:21 +00003190 << DSR
Anna Zaks90c78322012-05-30 23:14:52 +00003191 << SSR);
3192 DiagRuntimeBehavior(SL, SizeOfArg,
3193 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
3194 << ActionIdx
3195 << SSR);
3196
Chandler Carruth000d4282011-06-16 09:09:40 +00003197 break;
3198 }
3199 }
3200
3201 // Also check for cases where the sizeof argument is the exact same
3202 // type as the memory argument, and where it points to a user-defined
3203 // record type.
3204 if (SizeOfArgTy != QualType()) {
3205 if (PointeeTy->isRecordType() &&
3206 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
3207 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
3208 PDiag(diag::warn_sizeof_pointer_type_memaccess)
3209 << FnName << SizeOfArgTy << ArgIdx
3210 << PointeeTy << Dest->getSourceRange()
3211 << LenExpr->getSourceRange());
3212 break;
3213 }
Nico Webere4a1c642011-06-14 16:14:58 +00003214 }
3215
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003216 // Always complain about dynamic classes.
Anna Zaks0a151a12012-01-17 00:37:07 +00003217 if (isDynamicClassType(PointeeTy)) {
3218
3219 unsigned OperationType = 0;
3220 // "overwritten" if we're warning about the destination for any call
3221 // but memcmp; otherwise a verb appropriate to the call.
3222 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
3223 if (BId == Builtin::BImemcpy)
3224 OperationType = 1;
3225 else if(BId == Builtin::BImemmove)
3226 OperationType = 2;
3227 else if (BId == Builtin::BImemcmp)
3228 OperationType = 3;
3229 }
3230
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003231 DiagRuntimeBehavior(
3232 Dest->getExprLoc(), Dest,
3233 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks0a151a12012-01-17 00:37:07 +00003234 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Anna Zaksd9b859a2012-01-13 21:52:01 +00003235 << FnName << PointeeTy
Anna Zaks0a151a12012-01-17 00:37:07 +00003236 << OperationType
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003237 << Call->getCallee()->getSourceRange());
Anna Zaks0a151a12012-01-17 00:37:07 +00003238 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
3239 BId != Builtin::BImemset)
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003240 DiagRuntimeBehavior(
3241 Dest->getExprLoc(), Dest,
3242 PDiag(diag::warn_arc_object_memaccess)
3243 << ArgIdx << FnName << PointeeTy
3244 << Call->getCallee()->getSourceRange());
John McCallf85e1932011-06-15 23:02:42 +00003245 else
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003246 continue;
John McCallf85e1932011-06-15 23:02:42 +00003247
3248 DiagRuntimeBehavior(
3249 Dest->getExprLoc(), Dest,
Chandler Carruth929f0132011-06-03 06:23:57 +00003250 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003251 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
3252 break;
3253 }
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003254 }
3255}
3256
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003257// A little helper routine: ignore addition and subtraction of integer literals.
3258// This intentionally does not ignore all integer constant expressions because
3259// we don't want to remove sizeof().
3260static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
3261 Ex = Ex->IgnoreParenCasts();
3262
3263 for (;;) {
3264 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
3265 if (!BO || !BO->isAdditiveOp())
3266 break;
3267
3268 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
3269 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
3270
3271 if (isa<IntegerLiteral>(RHS))
3272 Ex = LHS;
3273 else if (isa<IntegerLiteral>(LHS))
3274 Ex = RHS;
3275 else
3276 break;
3277 }
3278
3279 return Ex;
3280}
3281
Anna Zaks0f38ace2012-08-08 21:42:23 +00003282static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
3283 ASTContext &Context) {
3284 // Only handle constant-sized or VLAs, but not flexible members.
3285 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
3286 // Only issue the FIXIT for arrays of size > 1.
3287 if (CAT->getSize().getSExtValue() <= 1)
3288 return false;
3289 } else if (!Ty->isVariableArrayType()) {
3290 return false;
3291 }
3292 return true;
3293}
3294
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003295// Warn if the user has made the 'size' argument to strlcpy or strlcat
3296// be the size of the source, instead of the destination.
3297void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
3298 IdentifierInfo *FnName) {
3299
3300 // Don't crash if the user has the wrong number of arguments
3301 if (Call->getNumArgs() != 3)
3302 return;
3303
3304 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
3305 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
3306 const Expr *CompareWithSrc = NULL;
3307
3308 // Look for 'strlcpy(dst, x, sizeof(x))'
3309 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
3310 CompareWithSrc = Ex;
3311 else {
3312 // Look for 'strlcpy(dst, x, strlen(x))'
3313 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Richard Smith180f4792011-11-10 06:34:14 +00003314 if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003315 && SizeCall->getNumArgs() == 1)
3316 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
3317 }
3318 }
3319
3320 if (!CompareWithSrc)
3321 return;
3322
3323 // Determine if the argument to sizeof/strlen is equal to the source
3324 // argument. In principle there's all kinds of things you could do
3325 // here, for instance creating an == expression and evaluating it with
3326 // EvaluateAsBooleanCondition, but this uses a more direct technique:
3327 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
3328 if (!SrcArgDRE)
3329 return;
3330
3331 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
3332 if (!CompareWithSrcDRE ||
3333 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
3334 return;
3335
3336 const Expr *OriginalSizeArg = Call->getArg(2);
3337 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
3338 << OriginalSizeArg->getSourceRange() << FnName;
3339
3340 // Output a FIXIT hint if the destination is an array (rather than a
3341 // pointer to an array). This could be enhanced to handle some
3342 // pointers if we know the actual size, like if DstArg is 'array+2'
3343 // we could say 'sizeof(array)-2'.
3344 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks0f38ace2012-08-08 21:42:23 +00003345 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek8f746222011-08-18 22:48:41 +00003346 return;
Ted Kremenek8f746222011-08-18 22:48:41 +00003347
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003348 SmallString<128> sizeString;
Ted Kremenek8f746222011-08-18 22:48:41 +00003349 llvm::raw_svector_ostream OS(sizeString);
3350 OS << "sizeof(";
Richard Smithd1420c62012-08-16 03:56:14 +00003351 DstArg->printPretty(OS, 0, getPrintingPolicy());
Ted Kremenek8f746222011-08-18 22:48:41 +00003352 OS << ")";
3353
3354 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
3355 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
3356 OS.str());
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003357}
3358
Anna Zaksc36bedc2012-02-01 19:08:57 +00003359/// Check if two expressions refer to the same declaration.
3360static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
3361 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
3362 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
3363 return D1->getDecl() == D2->getDecl();
3364 return false;
3365}
3366
3367static const Expr *getStrlenExprArg(const Expr *E) {
3368 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
3369 const FunctionDecl *FD = CE->getDirectCallee();
3370 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
3371 return 0;
3372 return CE->getArg(0)->IgnoreParenCasts();
3373 }
3374 return 0;
3375}
3376
3377// Warn on anti-patterns as the 'size' argument to strncat.
3378// The correct size argument should look like following:
3379// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
3380void Sema::CheckStrncatArguments(const CallExpr *CE,
3381 IdentifierInfo *FnName) {
3382 // Don't crash if the user has the wrong number of arguments.
3383 if (CE->getNumArgs() < 3)
3384 return;
3385 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
3386 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
3387 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
3388
3389 // Identify common expressions, which are wrongly used as the size argument
3390 // to strncat and may lead to buffer overflows.
3391 unsigned PatternType = 0;
3392 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
3393 // - sizeof(dst)
3394 if (referToTheSameDecl(SizeOfArg, DstArg))
3395 PatternType = 1;
3396 // - sizeof(src)
3397 else if (referToTheSameDecl(SizeOfArg, SrcArg))
3398 PatternType = 2;
3399 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
3400 if (BE->getOpcode() == BO_Sub) {
3401 const Expr *L = BE->getLHS()->IgnoreParenCasts();
3402 const Expr *R = BE->getRHS()->IgnoreParenCasts();
3403 // - sizeof(dst) - strlen(dst)
3404 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
3405 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
3406 PatternType = 1;
3407 // - sizeof(src) - (anything)
3408 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
3409 PatternType = 2;
3410 }
3411 }
3412
3413 if (PatternType == 0)
3414 return;
3415
Anna Zaksafdb0412012-02-03 01:27:37 +00003416 // Generate the diagnostic.
3417 SourceLocation SL = LenArg->getLocStart();
3418 SourceRange SR = LenArg->getSourceRange();
3419 SourceManager &SM = PP.getSourceManager();
3420
3421 // If the function is defined as a builtin macro, do not show macro expansion.
3422 if (SM.isMacroArgExpansion(SL)) {
3423 SL = SM.getSpellingLoc(SL);
3424 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
3425 SM.getSpellingLoc(SR.getEnd()));
3426 }
3427
Anna Zaks0f38ace2012-08-08 21:42:23 +00003428 // Check if the destination is an array (rather than a pointer to an array).
3429 QualType DstTy = DstArg->getType();
3430 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
3431 Context);
3432 if (!isKnownSizeArray) {
3433 if (PatternType == 1)
3434 Diag(SL, diag::warn_strncat_wrong_size) << SR;
3435 else
3436 Diag(SL, diag::warn_strncat_src_size) << SR;
3437 return;
3438 }
3439
Anna Zaksc36bedc2012-02-01 19:08:57 +00003440 if (PatternType == 1)
Anna Zaksafdb0412012-02-03 01:27:37 +00003441 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003442 else
Anna Zaksafdb0412012-02-03 01:27:37 +00003443 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003444
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003445 SmallString<128> sizeString;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003446 llvm::raw_svector_ostream OS(sizeString);
3447 OS << "sizeof(";
Richard Smithd1420c62012-08-16 03:56:14 +00003448 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003449 OS << ") - ";
3450 OS << "strlen(";
Richard Smithd1420c62012-08-16 03:56:14 +00003451 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003452 OS << ") - 1";
3453
Anna Zaksafdb0412012-02-03 01:27:37 +00003454 Diag(SL, diag::note_strncat_wrong_size)
3455 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003456}
3457
Ted Kremenek06de2762007-08-17 16:46:58 +00003458//===--- CHECK: Return Address of Stack Variable --------------------------===//
3459
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003460static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3461 Decl *ParentDecl);
3462static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
3463 Decl *ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003464
3465/// CheckReturnStackAddr - Check if a return statement returns the address
3466/// of a stack variable.
3467void
3468Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
3469 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00003470
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003471 Expr *stackE = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003472 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003473
3474 // Perform checking for returned stack addresses, local blocks,
3475 // label addresses or references to temporaries.
John McCallf85e1932011-06-15 23:02:42 +00003476 if (lhsType->isPointerType() ||
David Blaikie4e4d0842012-03-11 07:00:24 +00003477 (!getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003478 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003479 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003480 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003481 }
3482
3483 if (stackE == 0)
3484 return; // Nothing suspicious was found.
3485
3486 SourceLocation diagLoc;
3487 SourceRange diagRange;
3488 if (refVars.empty()) {
3489 diagLoc = stackE->getLocStart();
3490 diagRange = stackE->getSourceRange();
3491 } else {
3492 // We followed through a reference variable. 'stackE' contains the
3493 // problematic expression but we will warn at the return statement pointing
3494 // at the reference variable. We will later display the "trail" of
3495 // reference variables using notes.
3496 diagLoc = refVars[0]->getLocStart();
3497 diagRange = refVars[0]->getSourceRange();
3498 }
3499
3500 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
3501 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
3502 : diag::warn_ret_stack_addr)
3503 << DR->getDecl()->getDeclName() << diagRange;
3504 } else if (isa<BlockExpr>(stackE)) { // local block.
3505 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
3506 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
3507 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
3508 } else { // local temporary.
3509 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
3510 : diag::warn_ret_local_temp_addr)
3511 << diagRange;
3512 }
3513
3514 // Display the "trail" of reference variables that we followed until we
3515 // found the problematic expression using notes.
3516 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
3517 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
3518 // If this var binds to another reference var, show the range of the next
3519 // var, otherwise the var binds to the problematic expression, in which case
3520 // show the range of the expression.
3521 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
3522 : stackE->getSourceRange();
3523 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
3524 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00003525 }
3526}
3527
3528/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
3529/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003530/// to a location on the stack, a local block, an address of a label, or a
3531/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00003532/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003533/// encounter a subexpression that (1) clearly does not lead to one of the
3534/// above problematic expressions (2) is something we cannot determine leads to
3535/// a problematic expression based on such local checking.
3536///
3537/// Both EvalAddr and EvalVal follow through reference variables to evaluate
3538/// the expression that they point to. Such variables are added to the
3539/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00003540///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00003541/// EvalAddr processes expressions that are pointers that are used as
3542/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003543/// At the base case of the recursion is a check for the above problematic
3544/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00003545///
3546/// This implementation handles:
3547///
3548/// * pointer-to-pointer casts
3549/// * implicit conversions from array references to pointers
3550/// * taking the address of fields
3551/// * arbitrary interplay between "&" and "*" operators
3552/// * pointer arithmetic from an address of a stack variable
3553/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003554static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3555 Decl *ParentDecl) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003556 if (E->isTypeDependent())
3557 return NULL;
3558
Ted Kremenek06de2762007-08-17 16:46:58 +00003559 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00003560 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00003561 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003562 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003563 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00003564
Peter Collingbournef111d932011-04-15 00:35:48 +00003565 E = E->IgnoreParens();
3566
Ted Kremenek06de2762007-08-17 16:46:58 +00003567 // Our "symbolic interpreter" is just a dispatch off the currently
3568 // viewed AST node. We then recursively traverse the AST by calling
3569 // EvalAddr and EvalVal appropriately.
3570 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003571 case Stmt::DeclRefExprClass: {
3572 DeclRefExpr *DR = cast<DeclRefExpr>(E);
3573
3574 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
3575 // If this is a reference variable, follow through to the expression that
3576 // it points to.
3577 if (V->hasLocalStorage() &&
3578 V->getType()->isReferenceType() && V->hasInit()) {
3579 // Add the reference variable to the "trail".
3580 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003581 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003582 }
3583
3584 return NULL;
3585 }
Ted Kremenek06de2762007-08-17 16:46:58 +00003586
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003587 case Stmt::UnaryOperatorClass: {
3588 // The only unary operator that make sense to handle here
3589 // is AddrOf. All others don't make sense as pointers.
3590 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003591
John McCall2de56d12010-08-25 11:45:40 +00003592 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003593 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003594 else
Ted Kremenek06de2762007-08-17 16:46:58 +00003595 return NULL;
3596 }
Mike Stump1eb44332009-09-09 15:08:12 +00003597
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003598 case Stmt::BinaryOperatorClass: {
3599 // Handle pointer arithmetic. All other binary operators are not valid
3600 // in this context.
3601 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00003602 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00003603
John McCall2de56d12010-08-25 11:45:40 +00003604 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003605 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00003606
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003607 Expr *Base = B->getLHS();
3608
3609 // Determine which argument is the real pointer base. It could be
3610 // the RHS argument instead of the LHS.
3611 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00003612
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003613 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003614 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003615 }
Steve Naroff61f40a22008-09-10 19:17:48 +00003616
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003617 // For conditional operators we need to see if either the LHS or RHS are
3618 // valid DeclRefExpr*s. If one of them is valid, we return it.
3619 case Stmt::ConditionalOperatorClass: {
3620 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003621
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003622 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003623 if (Expr *lhsExpr = C->getLHS()) {
3624 // In C++, we can have a throw-expression, which has 'void' type.
3625 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003626 if (Expr* LHS = EvalAddr(lhsExpr, refVars, ParentDecl))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003627 return LHS;
3628 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003629
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003630 // In C++, we can have a throw-expression, which has 'void' type.
3631 if (C->getRHS()->getType()->isVoidType())
3632 return NULL;
3633
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003634 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003635 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003636
3637 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00003638 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003639 return E; // local block.
3640 return NULL;
3641
3642 case Stmt::AddrLabelExprClass:
3643 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00003644
John McCall80ee6e82011-11-10 05:35:25 +00003645 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003646 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
3647 ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00003648
Ted Kremenek54b52742008-08-07 00:49:01 +00003649 // For casts, we need to handle conversions from arrays to
3650 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00003651 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00003652 case Stmt::CStyleCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00003653 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8b9414e2012-02-23 23:04:32 +00003654 case Stmt::ObjCBridgedCastExprClass:
Mike Stump1eb44332009-09-09 15:08:12 +00003655 case Stmt::CXXStaticCastExprClass:
3656 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00003657 case Stmt::CXXConstCastExprClass:
3658 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8b9414e2012-02-23 23:04:32 +00003659 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
3660 switch (cast<CastExpr>(E)->getCastKind()) {
3661 case CK_BitCast:
3662 case CK_LValueToRValue:
3663 case CK_NoOp:
3664 case CK_BaseToDerived:
3665 case CK_DerivedToBase:
3666 case CK_UncheckedDerivedToBase:
3667 case CK_Dynamic:
3668 case CK_CPointerToObjCPointerCast:
3669 case CK_BlockPointerToObjCPointerCast:
3670 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003671 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00003672
3673 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003674 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00003675
3676 default:
3677 return 0;
3678 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003679 }
Mike Stump1eb44332009-09-09 15:08:12 +00003680
Douglas Gregor03e80032011-06-21 17:03:29 +00003681 case Stmt::MaterializeTemporaryExprClass:
3682 if (Expr *Result = EvalAddr(
3683 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003684 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00003685 return Result;
3686
3687 return E;
3688
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003689 // Everything else: we simply don't reason about them.
3690 default:
3691 return NULL;
3692 }
Ted Kremenek06de2762007-08-17 16:46:58 +00003693}
Mike Stump1eb44332009-09-09 15:08:12 +00003694
Ted Kremenek06de2762007-08-17 16:46:58 +00003695
3696/// EvalVal - This function is complements EvalAddr in the mutual recursion.
3697/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003698static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3699 Decl *ParentDecl) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003700do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00003701 // We should only be called for evaluating non-pointer expressions, or
3702 // expressions with a pointer type that are not used as references but instead
3703 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00003704
Ted Kremenek06de2762007-08-17 16:46:58 +00003705 // Our "symbolic interpreter" is just a dispatch off the currently
3706 // viewed AST node. We then recursively traverse the AST by calling
3707 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00003708
3709 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00003710 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003711 case Stmt::ImplicitCastExprClass: {
3712 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00003713 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003714 E = IE->getSubExpr();
3715 continue;
3716 }
3717 return NULL;
3718 }
3719
John McCall80ee6e82011-11-10 05:35:25 +00003720 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003721 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00003722
Douglas Gregora2813ce2009-10-23 18:54:35 +00003723 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003724 // When we hit a DeclRefExpr we are looking at code that refers to a
3725 // variable's name. If it's not a reference variable we check if it has
3726 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00003727 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003728
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003729 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
3730 // Check if it refers to itself, e.g. "int& i = i;".
3731 if (V == ParentDecl)
3732 return DR;
3733
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003734 if (V->hasLocalStorage()) {
3735 if (!V->getType()->isReferenceType())
3736 return DR;
3737
3738 // Reference variable, follow through to the expression that
3739 // it points to.
3740 if (V->hasInit()) {
3741 // Add the reference variable to the "trail".
3742 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003743 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003744 }
3745 }
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003746 }
Mike Stump1eb44332009-09-09 15:08:12 +00003747
Ted Kremenek06de2762007-08-17 16:46:58 +00003748 return NULL;
3749 }
Mike Stump1eb44332009-09-09 15:08:12 +00003750
Ted Kremenek06de2762007-08-17 16:46:58 +00003751 case Stmt::UnaryOperatorClass: {
3752 // The only unary operator that make sense to handle here
3753 // is Deref. All others don't resolve to a "name." This includes
3754 // handling all sorts of rvalues passed to a unary operator.
3755 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003756
John McCall2de56d12010-08-25 11:45:40 +00003757 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003758 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003759
3760 return NULL;
3761 }
Mike Stump1eb44332009-09-09 15:08:12 +00003762
Ted Kremenek06de2762007-08-17 16:46:58 +00003763 case Stmt::ArraySubscriptExprClass: {
3764 // Array subscripts are potential references to data on the stack. We
3765 // retrieve the DeclRefExpr* for the array variable if it indeed
3766 // has local storage.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003767 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003768 }
Mike Stump1eb44332009-09-09 15:08:12 +00003769
Ted Kremenek06de2762007-08-17 16:46:58 +00003770 case Stmt::ConditionalOperatorClass: {
3771 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003772 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00003773 ConditionalOperator *C = cast<ConditionalOperator>(E);
3774
Anders Carlsson39073232007-11-30 19:04:31 +00003775 // Handle the GNU extension for missing LHS.
3776 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003777 if (Expr *LHS = EvalVal(lhsExpr, refVars, ParentDecl))
Anders Carlsson39073232007-11-30 19:04:31 +00003778 return LHS;
3779
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003780 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003781 }
Mike Stump1eb44332009-09-09 15:08:12 +00003782
Ted Kremenek06de2762007-08-17 16:46:58 +00003783 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00003784 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00003785 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003786
Ted Kremenek06de2762007-08-17 16:46:58 +00003787 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00003788 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00003789 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00003790
3791 // Check whether the member type is itself a reference, in which case
3792 // we're not going to refer to the member, but to what the member refers to.
3793 if (M->getMemberDecl()->getType()->isReferenceType())
3794 return NULL;
3795
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003796 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003797 }
Mike Stump1eb44332009-09-09 15:08:12 +00003798
Douglas Gregor03e80032011-06-21 17:03:29 +00003799 case Stmt::MaterializeTemporaryExprClass:
3800 if (Expr *Result = EvalVal(
3801 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003802 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00003803 return Result;
3804
3805 return E;
3806
Ted Kremenek06de2762007-08-17 16:46:58 +00003807 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003808 // Check that we don't return or take the address of a reference to a
3809 // temporary. This is only useful in C++.
3810 if (!E->isTypeDependent() && E->isRValue())
3811 return E;
3812
3813 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00003814 return NULL;
3815 }
Ted Kremenek68957a92010-08-04 20:01:07 +00003816} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00003817}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003818
3819//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
3820
3821/// Check for comparisons of floating point operands using != and ==.
3822/// Issue a warning if these are no self-comparisons, as they are not likely
3823/// to do what the programmer intended.
Richard Trieudd225092011-09-15 21:56:47 +00003824void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieudd225092011-09-15 21:56:47 +00003825 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
3826 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003827
3828 // Special case: check for x == x (which is OK).
3829 // Do not emit warnings for such cases.
3830 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
3831 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
3832 if (DRL->getDecl() == DRR->getDecl())
David Blaikie980343b2012-07-16 20:47:22 +00003833 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003834
3835
Ted Kremenek1b500bb2007-11-29 00:59:04 +00003836 // Special case: check for comparisons against literals that can be exactly
3837 // represented by APFloat. In such cases, do not emit a warning. This
3838 // is a heuristic: often comparison against such literals are used to
3839 // detect if a value in a variable has not changed. This clearly can
3840 // lead to false negatives.
David Blaikie980343b2012-07-16 20:47:22 +00003841 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
3842 if (FLL->isExact())
3843 return;
3844 } else
3845 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
3846 if (FLR->isExact())
3847 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003848
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003849 // Check for comparisons with builtin types.
David Blaikie980343b2012-07-16 20:47:22 +00003850 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
3851 if (CL->isBuiltinCall())
3852 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003853
David Blaikie980343b2012-07-16 20:47:22 +00003854 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
3855 if (CR->isBuiltinCall())
3856 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003857
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003858 // Emit the diagnostic.
David Blaikie980343b2012-07-16 20:47:22 +00003859 Diag(Loc, diag::warn_floatingpoint_eq)
3860 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003861}
John McCallba26e582010-01-04 23:21:16 +00003862
John McCallf2370c92010-01-06 05:24:50 +00003863//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
3864//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00003865
John McCallf2370c92010-01-06 05:24:50 +00003866namespace {
John McCallba26e582010-01-04 23:21:16 +00003867
John McCallf2370c92010-01-06 05:24:50 +00003868/// Structure recording the 'active' range of an integer-valued
3869/// expression.
3870struct IntRange {
3871 /// The number of bits active in the int.
3872 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00003873
John McCallf2370c92010-01-06 05:24:50 +00003874 /// True if the int is known not to have negative values.
3875 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00003876
John McCallf2370c92010-01-06 05:24:50 +00003877 IntRange(unsigned Width, bool NonNegative)
3878 : Width(Width), NonNegative(NonNegative)
3879 {}
John McCallba26e582010-01-04 23:21:16 +00003880
John McCall1844a6e2010-11-10 23:38:19 +00003881 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00003882 static IntRange forBoolType() {
3883 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00003884 }
3885
John McCall1844a6e2010-11-10 23:38:19 +00003886 /// Returns the range of an opaque value of the given integral type.
3887 static IntRange forValueOfType(ASTContext &C, QualType T) {
3888 return forValueOfCanonicalType(C,
3889 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00003890 }
3891
John McCall1844a6e2010-11-10 23:38:19 +00003892 /// Returns the range of an opaque value of a canonical integral type.
3893 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00003894 assert(T->isCanonicalUnqualified());
3895
3896 if (const VectorType *VT = dyn_cast<VectorType>(T))
3897 T = VT->getElementType().getTypePtr();
3898 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
3899 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00003900
John McCall091f23f2010-11-09 22:22:12 +00003901 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00003902 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
3903 EnumDecl *Enum = ET->getDecl();
John McCall5e1cdac2011-10-07 06:10:15 +00003904 if (!Enum->isCompleteDefinition())
John McCall091f23f2010-11-09 22:22:12 +00003905 return IntRange(C.getIntWidth(QualType(T, 0)), false);
3906
John McCall323ed742010-05-06 08:58:33 +00003907 unsigned NumPositive = Enum->getNumPositiveBits();
3908 unsigned NumNegative = Enum->getNumNegativeBits();
3909
3910 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
3911 }
John McCallf2370c92010-01-06 05:24:50 +00003912
3913 const BuiltinType *BT = cast<BuiltinType>(T);
3914 assert(BT->isInteger());
3915
3916 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
3917 }
3918
John McCall1844a6e2010-11-10 23:38:19 +00003919 /// Returns the "target" range of a canonical integral type, i.e.
3920 /// the range of values expressible in the type.
3921 ///
3922 /// This matches forValueOfCanonicalType except that enums have the
3923 /// full range of their type, not the range of their enumerators.
3924 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
3925 assert(T->isCanonicalUnqualified());
3926
3927 if (const VectorType *VT = dyn_cast<VectorType>(T))
3928 T = VT->getElementType().getTypePtr();
3929 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
3930 T = CT->getElementType().getTypePtr();
3931 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor69ff26b2011-09-08 23:29:05 +00003932 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall1844a6e2010-11-10 23:38:19 +00003933
3934 const BuiltinType *BT = cast<BuiltinType>(T);
3935 assert(BT->isInteger());
3936
3937 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
3938 }
3939
3940 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00003941 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00003942 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00003943 L.NonNegative && R.NonNegative);
3944 }
3945
John McCall1844a6e2010-11-10 23:38:19 +00003946 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00003947 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00003948 return IntRange(std::min(L.Width, R.Width),
3949 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00003950 }
3951};
3952
Ted Kremenek0692a192012-01-31 05:37:37 +00003953static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
3954 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00003955 if (value.isSigned() && value.isNegative())
3956 return IntRange(value.getMinSignedBits(), false);
3957
3958 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00003959 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00003960
3961 // isNonNegative() just checks the sign bit without considering
3962 // signedness.
3963 return IntRange(value.getActiveBits(), true);
3964}
3965
Ted Kremenek0692a192012-01-31 05:37:37 +00003966static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
3967 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00003968 if (result.isInt())
3969 return GetValueRange(C, result.getInt(), MaxWidth);
3970
3971 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00003972 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
3973 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
3974 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
3975 R = IntRange::join(R, El);
3976 }
John McCallf2370c92010-01-06 05:24:50 +00003977 return R;
3978 }
3979
3980 if (result.isComplexInt()) {
3981 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
3982 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
3983 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00003984 }
3985
3986 // This can happen with lossless casts to intptr_t of "based" lvalues.
3987 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00003988 // FIXME: The only reason we need to pass the type in here is to get
3989 // the sign right on this one case. It would be nice if APValue
3990 // preserved this.
Eli Friedman65639282012-01-04 23:13:47 +00003991 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00003992 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall51313c32010-01-04 23:31:57 +00003993}
John McCallf2370c92010-01-06 05:24:50 +00003994
3995/// Pseudo-evaluate the given integer expression, estimating the
3996/// range of values it might take.
3997///
3998/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek0692a192012-01-31 05:37:37 +00003999static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004000 E = E->IgnoreParens();
4001
4002 // Try a full evaluation first.
4003 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00004004 if (E->EvaluateAsRValue(result, C))
John McCall0acc3112010-01-06 22:57:21 +00004005 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00004006
4007 // I think we only want to look through implicit casts here; if the
4008 // user has an explicit widening cast, we should treat the value as
4009 // being of the new, wider type.
4010 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedmanb17ee5b2011-12-15 02:41:52 +00004011 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCallf2370c92010-01-06 05:24:50 +00004012 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
4013
John McCall1844a6e2010-11-10 23:38:19 +00004014 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCallf2370c92010-01-06 05:24:50 +00004015
John McCall2de56d12010-08-25 11:45:40 +00004016 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00004017
John McCallf2370c92010-01-06 05:24:50 +00004018 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00004019 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00004020 return OutputTypeRange;
4021
4022 IntRange SubRange
4023 = GetExprRange(C, CE->getSubExpr(),
4024 std::min(MaxWidth, OutputTypeRange.Width));
4025
4026 // Bail out if the subexpr's range is as wide as the cast type.
4027 if (SubRange.Width >= OutputTypeRange.Width)
4028 return OutputTypeRange;
4029
4030 // Otherwise, we take the smaller width, and we're non-negative if
4031 // either the output type or the subexpr is.
4032 return IntRange(SubRange.Width,
4033 SubRange.NonNegative || OutputTypeRange.NonNegative);
4034 }
4035
4036 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4037 // If we can fold the condition, just take that operand.
4038 bool CondResult;
4039 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
4040 return GetExprRange(C, CondResult ? CO->getTrueExpr()
4041 : CO->getFalseExpr(),
4042 MaxWidth);
4043
4044 // Otherwise, conservatively merge.
4045 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
4046 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
4047 return IntRange::join(L, R);
4048 }
4049
4050 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4051 switch (BO->getOpcode()) {
4052
4053 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00004054 case BO_LAnd:
4055 case BO_LOr:
4056 case BO_LT:
4057 case BO_GT:
4058 case BO_LE:
4059 case BO_GE:
4060 case BO_EQ:
4061 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00004062 return IntRange::forBoolType();
4063
John McCall862ff872011-07-13 06:35:24 +00004064 // The type of the assignments is the type of the LHS, so the RHS
4065 // is not necessarily the same type.
John McCall2de56d12010-08-25 11:45:40 +00004066 case BO_MulAssign:
4067 case BO_DivAssign:
4068 case BO_RemAssign:
4069 case BO_AddAssign:
4070 case BO_SubAssign:
John McCall862ff872011-07-13 06:35:24 +00004071 case BO_XorAssign:
4072 case BO_OrAssign:
4073 // TODO: bitfields?
John McCall1844a6e2010-11-10 23:38:19 +00004074 return IntRange::forValueOfType(C, E->getType());
John McCallc0cd21d2010-02-23 19:22:29 +00004075
John McCall862ff872011-07-13 06:35:24 +00004076 // Simple assignments just pass through the RHS, which will have
4077 // been coerced to the LHS type.
4078 case BO_Assign:
4079 // TODO: bitfields?
4080 return GetExprRange(C, BO->getRHS(), MaxWidth);
4081
John McCallf2370c92010-01-06 05:24:50 +00004082 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00004083 case BO_PtrMemD:
4084 case BO_PtrMemI:
John McCall1844a6e2010-11-10 23:38:19 +00004085 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00004086
John McCall60fad452010-01-06 22:07:33 +00004087 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00004088 case BO_And:
4089 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00004090 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
4091 GetExprRange(C, BO->getRHS(), MaxWidth));
4092
John McCallf2370c92010-01-06 05:24:50 +00004093 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00004094 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00004095 // ...except that we want to treat '1 << (blah)' as logically
4096 // positive. It's an important idiom.
4097 if (IntegerLiteral *I
4098 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
4099 if (I->getValue() == 1) {
John McCall1844a6e2010-11-10 23:38:19 +00004100 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall3aae6092010-04-07 01:14:35 +00004101 return IntRange(R.Width, /*NonNegative*/ true);
4102 }
4103 }
4104 // fallthrough
4105
John McCall2de56d12010-08-25 11:45:40 +00004106 case BO_ShlAssign:
John McCall1844a6e2010-11-10 23:38:19 +00004107 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00004108
John McCall60fad452010-01-06 22:07:33 +00004109 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00004110 case BO_Shr:
4111 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00004112 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4113
4114 // If the shift amount is a positive constant, drop the width by
4115 // that much.
4116 llvm::APSInt shift;
4117 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
4118 shift.isNonNegative()) {
4119 unsigned zext = shift.getZExtValue();
4120 if (zext >= L.Width)
4121 L.Width = (L.NonNegative ? 0 : 1);
4122 else
4123 L.Width -= zext;
4124 }
4125
4126 return L;
4127 }
4128
4129 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00004130 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00004131 return GetExprRange(C, BO->getRHS(), MaxWidth);
4132
John McCall60fad452010-01-06 22:07:33 +00004133 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00004134 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00004135 if (BO->getLHS()->getType()->isPointerType())
John McCall1844a6e2010-11-10 23:38:19 +00004136 return IntRange::forValueOfType(C, E->getType());
John McCall00fe7612011-07-14 22:39:48 +00004137 break;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00004138
John McCall00fe7612011-07-14 22:39:48 +00004139 // The width of a division result is mostly determined by the size
4140 // of the LHS.
4141 case BO_Div: {
4142 // Don't 'pre-truncate' the operands.
4143 unsigned opWidth = C.getIntWidth(E->getType());
4144 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4145
4146 // If the divisor is constant, use that.
4147 llvm::APSInt divisor;
4148 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
4149 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
4150 if (log2 >= L.Width)
4151 L.Width = (L.NonNegative ? 0 : 1);
4152 else
4153 L.Width = std::min(L.Width - log2, MaxWidth);
4154 return L;
4155 }
4156
4157 // Otherwise, just use the LHS's width.
4158 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4159 return IntRange(L.Width, L.NonNegative && R.NonNegative);
4160 }
4161
4162 // The result of a remainder can't be larger than the result of
4163 // either side.
4164 case BO_Rem: {
4165 // Don't 'pre-truncate' the operands.
4166 unsigned opWidth = C.getIntWidth(E->getType());
4167 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4168 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4169
4170 IntRange meet = IntRange::meet(L, R);
4171 meet.Width = std::min(meet.Width, MaxWidth);
4172 return meet;
4173 }
4174
4175 // The default behavior is okay for these.
4176 case BO_Mul:
4177 case BO_Add:
4178 case BO_Xor:
4179 case BO_Or:
John McCallf2370c92010-01-06 05:24:50 +00004180 break;
4181 }
4182
John McCall00fe7612011-07-14 22:39:48 +00004183 // The default case is to treat the operation as if it were closed
4184 // on the narrowest type that encompasses both operands.
John McCallf2370c92010-01-06 05:24:50 +00004185 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4186 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
4187 return IntRange::join(L, R);
4188 }
4189
4190 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
4191 switch (UO->getOpcode()) {
4192 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00004193 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00004194 return IntRange::forBoolType();
4195
4196 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00004197 case UO_Deref:
4198 case UO_AddrOf: // should be impossible
John McCall1844a6e2010-11-10 23:38:19 +00004199 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00004200
4201 default:
4202 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
4203 }
4204 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004205
4206 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall1844a6e2010-11-10 23:38:19 +00004207 IntRange::forValueOfType(C, E->getType());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004208 }
John McCallf2370c92010-01-06 05:24:50 +00004209
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004210 if (FieldDecl *BitField = E->getBitField())
4211 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00004212 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00004213
John McCall1844a6e2010-11-10 23:38:19 +00004214 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00004215}
John McCall51313c32010-01-04 23:31:57 +00004216
Ted Kremenek0692a192012-01-31 05:37:37 +00004217static IntRange GetExprRange(ASTContext &C, Expr *E) {
John McCall323ed742010-05-06 08:58:33 +00004218 return GetExprRange(C, E, C.getIntWidth(E->getType()));
4219}
4220
John McCall51313c32010-01-04 23:31:57 +00004221/// Checks whether the given value, which currently has the given
4222/// source semantics, has the same value when coerced through the
4223/// target semantics.
Ted Kremenek0692a192012-01-31 05:37:37 +00004224static bool IsSameFloatAfterCast(const llvm::APFloat &value,
4225 const llvm::fltSemantics &Src,
4226 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00004227 llvm::APFloat truncated = value;
4228
4229 bool ignored;
4230 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
4231 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
4232
4233 return truncated.bitwiseIsEqual(value);
4234}
4235
4236/// Checks whether the given value, which currently has the given
4237/// source semantics, has the same value when coerced through the
4238/// target semantics.
4239///
4240/// The value might be a vector of floats (or a complex number).
Ted Kremenek0692a192012-01-31 05:37:37 +00004241static bool IsSameFloatAfterCast(const APValue &value,
4242 const llvm::fltSemantics &Src,
4243 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00004244 if (value.isFloat())
4245 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
4246
4247 if (value.isVector()) {
4248 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
4249 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
4250 return false;
4251 return true;
4252 }
4253
4254 assert(value.isComplexFloat());
4255 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
4256 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
4257}
4258
Ted Kremenek0692a192012-01-31 05:37:37 +00004259static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00004260
Ted Kremeneke3b159c2010-09-23 21:43:44 +00004261static bool IsZero(Sema &S, Expr *E) {
4262 // Suppress cases where we are comparing against an enum constant.
4263 if (const DeclRefExpr *DR =
4264 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
4265 if (isa<EnumConstantDecl>(DR->getDecl()))
4266 return false;
4267
4268 // Suppress cases where the '0' value is expanded from a macro.
4269 if (E->getLocStart().isMacroID())
4270 return false;
4271
John McCall323ed742010-05-06 08:58:33 +00004272 llvm::APSInt Value;
4273 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
4274}
4275
John McCall372e1032010-10-06 00:25:24 +00004276static bool HasEnumType(Expr *E) {
4277 // Strip off implicit integral promotions.
4278 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00004279 if (ICE->getCastKind() != CK_IntegralCast &&
4280 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00004281 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00004282 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00004283 }
4284
4285 return E->getType()->isEnumeralType();
4286}
4287
Ted Kremenek0692a192012-01-31 05:37:37 +00004288static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00004289 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00004290 if (E->isValueDependent())
4291 return;
4292
John McCall2de56d12010-08-25 11:45:40 +00004293 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00004294 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004295 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00004296 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004297 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00004298 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004299 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00004300 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004301 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00004302 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004303 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00004304 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004305 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00004306 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004307 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00004308 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4309 }
4310}
4311
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004312static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004313 Expr *Constant, Expr *Other,
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004314 llvm::APSInt Value,
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004315 bool RhsConstant) {
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004316 BinaryOperatorKind op = E->getOpcode();
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004317 QualType OtherT = Other->getType();
4318 QualType ConstantT = Constant->getType();
4319 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004320 return;
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004321 assert((OtherT->isIntegerType() && ConstantT->isIntegerType())
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004322 && "comparison with non-integer type");
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004323 // FIXME. handle cases for signedness to catch (signed char)N == 200
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004324 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004325 IntRange LitRange = GetValueRange(S.Context, Value, Value.getBitWidth());
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004326 if (OtherRange.Width >= LitRange.Width)
4327 return;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004328 bool IsTrue = true;
4329 if (op == BO_EQ)
4330 IsTrue = false;
4331 else if (op == BO_NE)
4332 IsTrue = true;
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004333 else if (RhsConstant) {
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004334 if (op == BO_GT || op == BO_GE)
4335 IsTrue = !LitRange.NonNegative;
4336 else // op == BO_LT || op == BO_LE
4337 IsTrue = LitRange.NonNegative;
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004338 } else {
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004339 if (op == BO_LT || op == BO_LE)
4340 IsTrue = !LitRange.NonNegative;
4341 else // op == BO_GT || op == BO_GE
4342 IsTrue = LitRange.NonNegative;
4343 }
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004344 SmallString<16> PrettySourceValue(Value.toString(10));
4345 S.Diag(E->getOperatorLoc(), diag::warn_out_of_range_compare)
4346 << PrettySourceValue << OtherT << IsTrue
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004347 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4348}
4349
John McCall323ed742010-05-06 08:58:33 +00004350/// Analyze the operands of the given comparison. Implements the
4351/// fallback case from AnalyzeComparison.
Ted Kremenek0692a192012-01-31 05:37:37 +00004352static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00004353 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4354 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00004355}
John McCall51313c32010-01-04 23:31:57 +00004356
John McCallba26e582010-01-04 23:21:16 +00004357/// \brief Implements -Wsign-compare.
4358///
Richard Trieudd225092011-09-15 21:56:47 +00004359/// \param E the binary operator to check for warnings
Ted Kremenek0692a192012-01-31 05:37:37 +00004360static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCall323ed742010-05-06 08:58:33 +00004361 // The type the comparison is being performed in.
4362 QualType T = E->getLHS()->getType();
4363 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
4364 && "comparison with mismatched types");
Fariborz Jahanianab4702f2012-09-18 17:46:26 +00004365 if (E->isValueDependent())
4366 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004367
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004368 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
4369 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004370
4371 bool IsComparisonConstant = false;
4372
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004373 // Check whether an integer constant comparison results in a value
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004374 // of 'true' or 'false'.
4375 if (T->isIntegralType(S.Context)) {
4376 llvm::APSInt RHSValue;
4377 bool IsRHSIntegralLiteral =
4378 RHS->isIntegerConstantExpr(RHSValue, S.Context);
4379 llvm::APSInt LHSValue;
4380 bool IsLHSIntegralLiteral =
4381 LHS->isIntegerConstantExpr(LHSValue, S.Context);
4382 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
4383 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
4384 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
4385 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
4386 else
4387 IsComparisonConstant =
4388 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004389 } else if (!T->hasUnsignedIntegerRepresentation())
4390 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004391
John McCall323ed742010-05-06 08:58:33 +00004392 // We don't do anything special if this isn't an unsigned integral
4393 // comparison: we're only interested in integral comparisons, and
4394 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00004395 //
4396 // We also don't care about value-dependent expressions or expressions
4397 // whose result is a constant.
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004398 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCall323ed742010-05-06 08:58:33 +00004399 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004400
John McCall323ed742010-05-06 08:58:33 +00004401 // Check to see if one of the (unmodified) operands is of different
4402 // signedness.
4403 Expr *signedOperand, *unsignedOperand;
Richard Trieudd225092011-09-15 21:56:47 +00004404 if (LHS->getType()->hasSignedIntegerRepresentation()) {
4405 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00004406 "unsigned comparison between two signed integer expressions?");
Richard Trieudd225092011-09-15 21:56:47 +00004407 signedOperand = LHS;
4408 unsignedOperand = RHS;
4409 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
4410 signedOperand = RHS;
4411 unsignedOperand = LHS;
John McCallba26e582010-01-04 23:21:16 +00004412 } else {
John McCall323ed742010-05-06 08:58:33 +00004413 CheckTrivialUnsignedComparison(S, E);
4414 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004415 }
4416
John McCall323ed742010-05-06 08:58:33 +00004417 // Otherwise, calculate the effective range of the signed operand.
4418 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00004419
John McCall323ed742010-05-06 08:58:33 +00004420 // Go ahead and analyze implicit conversions in the operands. Note
4421 // that we skip the implicit conversions on both sides.
Richard Trieudd225092011-09-15 21:56:47 +00004422 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
4423 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00004424
John McCall323ed742010-05-06 08:58:33 +00004425 // If the signed range is non-negative, -Wsign-compare won't fire,
4426 // but we should still check for comparisons which are always true
4427 // or false.
4428 if (signedRange.NonNegative)
4429 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004430
4431 // For (in)equality comparisons, if the unsigned operand is a
4432 // constant which cannot collide with a overflowed signed operand,
4433 // then reinterpreting the signed operand as unsigned will not
4434 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00004435 if (E->isEqualityOp()) {
4436 unsigned comparisonWidth = S.Context.getIntWidth(T);
4437 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00004438
John McCall323ed742010-05-06 08:58:33 +00004439 // We should never be unable to prove that the unsigned operand is
4440 // non-negative.
4441 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
4442
4443 if (unsignedRange.Width < comparisonWidth)
4444 return;
4445 }
4446
Douglas Gregor6d3b93d2012-05-01 01:53:49 +00004447 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
4448 S.PDiag(diag::warn_mixed_sign_comparison)
4449 << LHS->getType() << RHS->getType()
4450 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallba26e582010-01-04 23:21:16 +00004451}
4452
John McCall15d7d122010-11-11 03:21:53 +00004453/// Analyzes an attempt to assign the given value to a bitfield.
4454///
4455/// Returns true if there was something fishy about the attempt.
Ted Kremenek0692a192012-01-31 05:37:37 +00004456static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
4457 SourceLocation InitLoc) {
John McCall15d7d122010-11-11 03:21:53 +00004458 assert(Bitfield->isBitField());
4459 if (Bitfield->isInvalidDecl())
4460 return false;
4461
John McCall91b60142010-11-11 05:33:51 +00004462 // White-list bool bitfields.
4463 if (Bitfield->getType()->isBooleanType())
4464 return false;
4465
Douglas Gregor46ff3032011-02-04 13:09:01 +00004466 // Ignore value- or type-dependent expressions.
4467 if (Bitfield->getBitWidth()->isValueDependent() ||
4468 Bitfield->getBitWidth()->isTypeDependent() ||
4469 Init->isValueDependent() ||
4470 Init->isTypeDependent())
4471 return false;
4472
John McCall15d7d122010-11-11 03:21:53 +00004473 Expr *OriginalInit = Init->IgnoreParenImpCasts();
4474
Richard Smith80d4b552011-12-28 19:48:30 +00004475 llvm::APSInt Value;
4476 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall15d7d122010-11-11 03:21:53 +00004477 return false;
4478
John McCall15d7d122010-11-11 03:21:53 +00004479 unsigned OriginalWidth = Value.getBitWidth();
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004480 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall15d7d122010-11-11 03:21:53 +00004481
4482 if (OriginalWidth <= FieldWidth)
4483 return false;
4484
Eli Friedman3a643af2012-01-26 23:11:39 +00004485 // Compute the value which the bitfield will contain.
Jay Foad9f71a8f2010-12-07 08:25:34 +00004486 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedman3a643af2012-01-26 23:11:39 +00004487 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall15d7d122010-11-11 03:21:53 +00004488
Eli Friedman3a643af2012-01-26 23:11:39 +00004489 // Check whether the stored value is equal to the original value.
4490 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieue1ecdc12012-07-23 20:21:35 +00004491 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall15d7d122010-11-11 03:21:53 +00004492 return false;
4493
Eli Friedman3a643af2012-01-26 23:11:39 +00004494 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedman34ff0622012-02-02 00:40:20 +00004495 // therefore don't strictly fit into a signed bitfield of width 1.
4496 if (FieldWidth == 1 && Value == 1)
Eli Friedman3a643af2012-01-26 23:11:39 +00004497 return false;
4498
John McCall15d7d122010-11-11 03:21:53 +00004499 std::string PrettyValue = Value.toString(10);
4500 std::string PrettyTrunc = TruncatedValue.toString(10);
4501
4502 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
4503 << PrettyValue << PrettyTrunc << OriginalInit->getType()
4504 << Init->getSourceRange();
4505
4506 return true;
4507}
4508
John McCallbeb22aa2010-11-09 23:24:47 +00004509/// Analyze the given simple or compound assignment for warning-worthy
4510/// operations.
Ted Kremenek0692a192012-01-31 05:37:37 +00004511static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCallbeb22aa2010-11-09 23:24:47 +00004512 // Just recurse on the LHS.
4513 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4514
4515 // We want to recurse on the RHS as normal unless we're assigning to
4516 // a bitfield.
4517 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
John McCall15d7d122010-11-11 03:21:53 +00004518 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
4519 E->getOperatorLoc())) {
4520 // Recurse, ignoring any implicit conversions on the RHS.
4521 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
4522 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00004523 }
4524 }
4525
4526 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
4527}
4528
John McCall51313c32010-01-04 23:31:57 +00004529/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00004530static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00004531 SourceLocation CContext, unsigned diag,
4532 bool pruneControlFlow = false) {
4533 if (pruneControlFlow) {
4534 S.DiagRuntimeBehavior(E->getExprLoc(), E,
4535 S.PDiag(diag)
4536 << SourceType << T << E->getSourceRange()
4537 << SourceRange(CContext));
4538 return;
4539 }
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004540 S.Diag(E->getExprLoc(), diag)
4541 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
4542}
4543
Chandler Carruthe1b02e02011-04-05 06:47:57 +00004544/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00004545static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00004546 SourceLocation CContext, unsigned diag,
4547 bool pruneControlFlow = false) {
4548 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruthe1b02e02011-04-05 06:47:57 +00004549}
4550
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004551/// Diagnose an implicit cast from a literal expression. Does not warn when the
4552/// cast wouldn't lose information.
Chandler Carruthf65076e2011-04-10 08:36:24 +00004553void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
4554 SourceLocation CContext) {
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004555 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruthf65076e2011-04-10 08:36:24 +00004556 bool isExact = false;
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004557 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00004558 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
4559 T->hasUnsignedIntegerRepresentation());
4560 if (Value.convertToInteger(IntegerValue,
Chandler Carruthf65076e2011-04-10 08:36:24 +00004561 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004562 == llvm::APFloat::opOK && isExact)
Chandler Carruthf65076e2011-04-10 08:36:24 +00004563 return;
4564
David Blaikiebe0ee872012-05-15 16:56:36 +00004565 SmallString<16> PrettySourceValue;
4566 Value.toString(PrettySourceValue);
David Blaikiede7e7b82012-05-15 17:18:27 +00004567 SmallString<16> PrettyTargetValue;
David Blaikiebe0ee872012-05-15 16:56:36 +00004568 if (T->isSpecificBuiltinType(BuiltinType::Bool))
4569 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
4570 else
David Blaikiede7e7b82012-05-15 17:18:27 +00004571 IntegerValue.toString(PrettyTargetValue);
David Blaikiebe0ee872012-05-15 16:56:36 +00004572
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004573 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikiebe0ee872012-05-15 16:56:36 +00004574 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
4575 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruthf65076e2011-04-10 08:36:24 +00004576}
4577
John McCall091f23f2010-11-09 22:22:12 +00004578std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
4579 if (!Range.Width) return "0";
4580
4581 llvm::APSInt ValueInRange = Value;
4582 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00004583 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00004584 return ValueInRange.toString(10);
4585}
4586
Hans Wennborg88617a22012-08-28 15:44:30 +00004587static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
4588 if (!isa<ImplicitCastExpr>(Ex))
4589 return false;
4590
4591 Expr *InnerE = Ex->IgnoreParenImpCasts();
4592 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
4593 const Type *Source =
4594 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
4595 if (Target->isDependentType())
4596 return false;
4597
4598 const BuiltinType *FloatCandidateBT =
4599 dyn_cast<BuiltinType>(ToBool ? Source : Target);
4600 const Type *BoolCandidateType = ToBool ? Target : Source;
4601
4602 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
4603 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
4604}
4605
4606void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
4607 SourceLocation CC) {
4608 unsigned NumArgs = TheCall->getNumArgs();
4609 for (unsigned i = 0; i < NumArgs; ++i) {
4610 Expr *CurrA = TheCall->getArg(i);
4611 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
4612 continue;
4613
4614 bool IsSwapped = ((i > 0) &&
4615 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
4616 IsSwapped |= ((i < (NumArgs - 1)) &&
4617 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
4618 if (IsSwapped) {
4619 // Warn on this floating-point to bool conversion.
4620 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
4621 CurrA->getType(), CC,
4622 diag::warn_impcast_floating_point_to_bool);
4623 }
4624 }
4625}
4626
John McCall323ed742010-05-06 08:58:33 +00004627void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00004628 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00004629 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00004630
John McCall323ed742010-05-06 08:58:33 +00004631 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
4632 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
4633 if (Source == Target) return;
4634 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00004635
Chandler Carruth108f7562011-07-26 05:40:03 +00004636 // If the conversion context location is invalid don't complain. We also
4637 // don't want to emit a warning if the issue occurs from the expansion of
4638 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
4639 // delay this check as long as possible. Once we detect we are in that
4640 // scenario, we just return.
Ted Kremenekef9ff882011-03-10 20:03:42 +00004641 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00004642 return;
4643
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004644 // Diagnose implicit casts to bool.
4645 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
4646 if (isa<StringLiteral>(E))
4647 // Warn on string literal to bool. Checks for string literals in logical
4648 // expressions, for instances, assert(0 && "error here"), is prevented
4649 // by a check in AnalyzeImplicitConversions().
4650 return DiagnoseImpCast(S, E, T, CC,
4651 diag::warn_impcast_string_literal_to_bool);
Lang Hamese14ca9f2011-12-05 20:49:50 +00004652 if (Source->isFunctionType()) {
4653 // Warn on function to bool. Checks free functions and static member
4654 // functions. Weakly imported functions are excluded from the check,
4655 // since it's common to test their value to check whether the linker
4656 // found a definition for them.
4657 ValueDecl *D = 0;
4658 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
4659 D = R->getDecl();
4660 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
4661 D = M->getMemberDecl();
4662 }
4663
4664 if (D && !D->isWeak()) {
Richard Trieu26b45d82011-12-06 04:48:01 +00004665 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
4666 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
4667 << F << E->getSourceRange() << SourceRange(CC);
David Blaikie2def7732011-12-09 21:42:37 +00004668 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
4669 << FixItHint::CreateInsertion(E->getExprLoc(), "&");
4670 QualType ReturnType;
4671 UnresolvedSet<4> NonTemplateOverloads;
4672 S.isExprCallable(*E, ReturnType, NonTemplateOverloads);
4673 if (!ReturnType.isNull()
4674 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
4675 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
4676 << FixItHint::CreateInsertion(
4677 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu26b45d82011-12-06 04:48:01 +00004678 return;
4679 }
Lang Hamese14ca9f2011-12-05 20:49:50 +00004680 }
4681 }
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004682 }
John McCall51313c32010-01-04 23:31:57 +00004683
4684 // Strip vector types.
4685 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004686 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004687 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004688 return;
John McCallb4eb64d2010-10-08 02:01:28 +00004689 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004690 }
Chris Lattnerb792b302011-06-14 04:51:15 +00004691
4692 // If the vector cast is cast between two vectors of the same size, it is
4693 // a bitcast, not a conversion.
4694 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
4695 return;
John McCall51313c32010-01-04 23:31:57 +00004696
4697 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
4698 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
4699 }
4700
4701 // Strip complex types.
4702 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004703 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004704 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004705 return;
4706
John McCallb4eb64d2010-10-08 02:01:28 +00004707 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004708 }
John McCall51313c32010-01-04 23:31:57 +00004709
4710 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
4711 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
4712 }
4713
4714 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
4715 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
4716
4717 // If the source is floating point...
4718 if (SourceBT && SourceBT->isFloatingPoint()) {
4719 // ...and the target is floating point...
4720 if (TargetBT && TargetBT->isFloatingPoint()) {
4721 // ...then warn if we're dropping FP rank.
4722
4723 // Builtin FP kinds are ordered by increasing FP rank.
4724 if (SourceBT->getKind() > TargetBT->getKind()) {
4725 // Don't warn about float constants that are precisely
4726 // representable in the target type.
4727 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00004728 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00004729 // Value might be a float, a float vector, or a float complex.
4730 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00004731 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
4732 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00004733 return;
4734 }
4735
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004736 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004737 return;
4738
John McCallb4eb64d2010-10-08 02:01:28 +00004739 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00004740 }
4741 return;
4742 }
4743
Ted Kremenekef9ff882011-03-10 20:03:42 +00004744 // If the target is integral, always warn.
David Blaikiebe0ee872012-05-15 16:56:36 +00004745 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004746 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004747 return;
4748
Chandler Carrutha5b93322011-02-17 11:05:49 +00004749 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay634c8af2011-09-08 22:30:47 +00004750 // We also want to warn on, e.g., "int i = -1.234"
4751 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
4752 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
4753 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
4754
Chandler Carruthf65076e2011-04-10 08:36:24 +00004755 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
4756 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00004757 } else {
4758 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
4759 }
4760 }
John McCall51313c32010-01-04 23:31:57 +00004761
Hans Wennborg88617a22012-08-28 15:44:30 +00004762 // If the target is bool, warn if expr is a function or method call.
4763 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
4764 isa<CallExpr>(E)) {
4765 // Check last argument of function call to see if it is an
4766 // implicit cast from a type matching the type the result
4767 // is being cast to.
4768 CallExpr *CEx = cast<CallExpr>(E);
4769 unsigned NumArgs = CEx->getNumArgs();
4770 if (NumArgs > 0) {
4771 Expr *LastA = CEx->getArg(NumArgs - 1);
4772 Expr *InnerE = LastA->IgnoreParenImpCasts();
4773 const Type *InnerType =
4774 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
4775 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
4776 // Warn on this floating-point to bool conversion
4777 DiagnoseImpCast(S, E, T, CC,
4778 diag::warn_impcast_floating_point_to_bool);
4779 }
4780 }
4781 }
John McCall51313c32010-01-04 23:31:57 +00004782 return;
4783 }
4784
Richard Trieu1838ca52011-05-29 19:59:02 +00004785 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
David Blaikieb26331b2012-06-19 21:19:06 +00004786 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
David Blaikie28a5f0c2012-06-21 18:51:10 +00004787 && !Target->isBlockPointerType() && !Target->isMemberPointerType()) {
David Blaikieb1360492012-03-16 20:30:12 +00004788 SourceLocation Loc = E->getSourceRange().getBegin();
4789 if (Loc.isMacroID())
4790 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
David Blaikie9fb1ac52012-05-15 21:57:38 +00004791 if (!Loc.isMacroID() || CC.isMacroID())
4792 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
4793 << T << clang::SourceRange(CC)
4794 << FixItHint::CreateReplacement(Loc, S.getFixItZeroLiteralForType(T));
Richard Trieu1838ca52011-05-29 19:59:02 +00004795 }
4796
David Blaikieb26331b2012-06-19 21:19:06 +00004797 if (!Source->isIntegerType() || !Target->isIntegerType())
4798 return;
4799
David Blaikiebe0ee872012-05-15 16:56:36 +00004800 // TODO: remove this early return once the false positives for constant->bool
4801 // in templates, macros, etc, are reduced or removed.
4802 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
4803 return;
4804
John McCall323ed742010-05-06 08:58:33 +00004805 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00004806 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00004807
4808 if (SourceRange.Width > TargetRange.Width) {
John McCall091f23f2010-11-09 22:22:12 +00004809 // If the source is a constant, use a default-on diagnostic.
4810 // TODO: this should happen for bitfield stores, too.
4811 llvm::APSInt Value(32);
4812 if (E->isIntegerConstantExpr(Value, S.Context)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004813 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004814 return;
4815
John McCall091f23f2010-11-09 22:22:12 +00004816 std::string PrettySourceValue = Value.toString(10);
4817 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
4818
Ted Kremenek5e745da2011-10-22 02:37:33 +00004819 S.DiagRuntimeBehavior(E->getExprLoc(), E,
4820 S.PDiag(diag::warn_impcast_integer_precision_constant)
4821 << PrettySourceValue << PrettyTargetValue
4822 << E->getType() << T << E->getSourceRange()
4823 << clang::SourceRange(CC));
John McCall091f23f2010-11-09 22:22:12 +00004824 return;
4825 }
4826
Chris Lattnerb792b302011-06-14 04:51:15 +00004827 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004828 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004829 return;
4830
David Blaikie37050842012-04-12 22:40:54 +00004831 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaksc36bedc2012-02-01 19:08:57 +00004832 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
4833 /* pruneControlFlow */ true);
John McCallb4eb64d2010-10-08 02:01:28 +00004834 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00004835 }
4836
4837 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
4838 (!TargetRange.NonNegative && SourceRange.NonNegative &&
4839 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004840
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004841 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004842 return;
4843
John McCall323ed742010-05-06 08:58:33 +00004844 unsigned DiagID = diag::warn_impcast_integer_sign;
4845
4846 // Traditionally, gcc has warned about this under -Wsign-compare.
4847 // We also want to warn about it in -Wconversion.
4848 // So if -Wconversion is off, use a completely identical diagnostic
4849 // in the sign-compare group.
4850 // The conditional-checking code will
4851 if (ICContext) {
4852 DiagID = diag::warn_impcast_integer_sign_conditional;
4853 *ICContext = true;
4854 }
4855
John McCallb4eb64d2010-10-08 02:01:28 +00004856 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00004857 }
4858
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004859 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004860 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
4861 // type, to give us better diagnostics.
4862 QualType SourceType = E->getType();
David Blaikie4e4d0842012-03-11 07:00:24 +00004863 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004864 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
4865 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
4866 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
4867 SourceType = S.Context.getTypeDeclType(Enum);
4868 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
4869 }
4870 }
4871
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004872 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
4873 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
4874 if ((SourceEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00004875 SourceEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004876 (TargetEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00004877 TargetEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00004878 SourceEnum != TargetEnum) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004879 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004880 return;
4881
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004882 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004883 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004884 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004885
John McCall51313c32010-01-04 23:31:57 +00004886 return;
4887}
4888
David Blaikie9fb1ac52012-05-15 21:57:38 +00004889void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
4890 SourceLocation CC, QualType T);
John McCall323ed742010-05-06 08:58:33 +00004891
4892void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00004893 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00004894 E = E->IgnoreParenImpCasts();
4895
4896 if (isa<ConditionalOperator>(E))
David Blaikie9fb1ac52012-05-15 21:57:38 +00004897 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCall323ed742010-05-06 08:58:33 +00004898
John McCallb4eb64d2010-10-08 02:01:28 +00004899 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00004900 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00004901 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00004902 return;
4903}
4904
David Blaikie9fb1ac52012-05-15 21:57:38 +00004905void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
4906 SourceLocation CC, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00004907 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00004908
4909 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00004910 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
4911 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00004912
4913 // If -Wconversion would have warned about either of the candidates
4914 // for a signedness conversion to the context type...
4915 if (!Suspicious) return;
4916
4917 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00004918 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
4919 CC))
John McCall323ed742010-05-06 08:58:33 +00004920 return;
4921
John McCall323ed742010-05-06 08:58:33 +00004922 // ...then check whether it would have warned about either of the
4923 // candidates for a signedness conversion to the condition type.
Richard Trieu52541612011-07-21 02:46:28 +00004924 if (E->getType() == T) return;
4925
4926 Suspicious = false;
4927 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
4928 E->getType(), CC, &Suspicious);
4929 if (!Suspicious)
4930 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00004931 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00004932}
4933
4934/// AnalyzeImplicitConversions - Find and report any interesting
4935/// implicit conversions in the given expression. There are a couple
4936/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00004937void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00004938 QualType T = OrigE->getType();
4939 Expr *E = OrigE->IgnoreParenImpCasts();
4940
Douglas Gregorf8b6e152011-10-10 17:38:18 +00004941 if (E->isTypeDependent() || E->isValueDependent())
4942 return;
4943
John McCall323ed742010-05-06 08:58:33 +00004944 // For conditional operators, we analyze the arguments as if they
4945 // were being fed directly into the output.
4946 if (isa<ConditionalOperator>(E)) {
4947 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie9fb1ac52012-05-15 21:57:38 +00004948 CheckConditionalOperator(S, CO, CC, T);
John McCall323ed742010-05-06 08:58:33 +00004949 return;
4950 }
4951
Hans Wennborg88617a22012-08-28 15:44:30 +00004952 // Check implicit argument conversions for function calls.
4953 if (CallExpr *Call = dyn_cast<CallExpr>(E))
4954 CheckImplicitArgumentConversions(S, Call, CC);
4955
John McCall323ed742010-05-06 08:58:33 +00004956 // Go ahead and check any implicit conversions we might have skipped.
4957 // The non-canonical typecheck is just an optimization;
4958 // CheckImplicitConversion will filter out dead implicit conversions.
4959 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00004960 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00004961
4962 // Now continue drilling into this expression.
4963
4964 // Skip past explicit casts.
4965 if (isa<ExplicitCastExpr>(E)) {
4966 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00004967 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00004968 }
4969
John McCallbeb22aa2010-11-09 23:24:47 +00004970 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4971 // Do a somewhat different check with comparison operators.
4972 if (BO->isComparisonOp())
4973 return AnalyzeComparison(S, BO);
4974
Eli Friedman0fa06382012-01-26 23:34:06 +00004975 // And with simple assignments.
4976 if (BO->getOpcode() == BO_Assign)
John McCallbeb22aa2010-11-09 23:24:47 +00004977 return AnalyzeAssignment(S, BO);
4978 }
John McCall323ed742010-05-06 08:58:33 +00004979
4980 // These break the otherwise-useful invariant below. Fortunately,
4981 // we don't really need to recurse into them, because any internal
4982 // expressions should have been analyzed already when they were
4983 // built into statements.
4984 if (isa<StmtExpr>(E)) return;
4985
4986 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004987 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00004988
4989 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00004990 CC = E->getExprLoc();
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004991 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
4992 bool IsLogicalOperator = BO && BO->isLogicalOp();
4993 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor54042f12012-02-09 10:18:50 +00004994 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor503384f2012-02-09 00:47:04 +00004995 if (!ChildExpr)
4996 continue;
4997
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004998 if (IsLogicalOperator &&
4999 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
5000 // Ignore checking string literals that are in logical operators.
5001 continue;
5002 AnalyzeImplicitConversions(S, ChildExpr, CC);
5003 }
John McCall323ed742010-05-06 08:58:33 +00005004}
5005
5006} // end anonymous namespace
5007
5008/// Diagnoses "dangerous" implicit conversions within the given
5009/// expression (which is a full expression). Implements -Wconversion
5010/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00005011///
5012/// \param CC the "context" location of the implicit conversion, i.e.
5013/// the most location of the syntactic entity requiring the implicit
5014/// conversion
5015void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00005016 // Don't diagnose in unevaluated contexts.
David Blaikie71f55f72012-08-06 22:47:24 +00005017 if (isUnevaluatedContext())
John McCall323ed742010-05-06 08:58:33 +00005018 return;
5019
5020 // Don't diagnose for value- or type-dependent expressions.
5021 if (E->isTypeDependent() || E->isValueDependent())
5022 return;
5023
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005024 // Check for array bounds violations in cases where the check isn't triggered
5025 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
5026 // ArraySubscriptExpr is on the RHS of a variable initialization.
5027 CheckArrayAccess(E);
5028
John McCallb4eb64d2010-10-08 02:01:28 +00005029 // This is not the right CC for (e.g.) a variable initialization.
5030 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005031}
5032
John McCall15d7d122010-11-11 03:21:53 +00005033void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
5034 FieldDecl *BitField,
5035 Expr *Init) {
5036 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
5037}
5038
Mike Stumpf8c49212010-01-21 03:59:47 +00005039/// CheckParmsForFunctionDef - Check that the parameters of the given
5040/// function are appropriate for the definition of a function. This
5041/// takes care of any checks that cannot be performed on the
5042/// declaration itself, e.g., that the types of each of the function
5043/// parameters are complete.
Douglas Gregor82aa7132010-11-01 18:37:59 +00005044bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
5045 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00005046 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00005047 for (; P != PEnd; ++P) {
5048 ParmVarDecl *Param = *P;
5049
Mike Stumpf8c49212010-01-21 03:59:47 +00005050 // C99 6.7.5.3p4: the parameters in a parameter type list in a
5051 // function declarator that is part of a function definition of
5052 // that function shall not have incomplete type.
5053 //
5054 // This is also C++ [dcl.fct]p6.
5055 if (!Param->isInvalidDecl() &&
5056 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00005057 diag::err_typecheck_decl_incomplete_type)) {
Mike Stumpf8c49212010-01-21 03:59:47 +00005058 Param->setInvalidDecl();
5059 HasInvalidParm = true;
5060 }
5061
5062 // C99 6.9.1p5: If the declarator includes a parameter type list, the
5063 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00005064 if (CheckParameterNames &&
5065 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00005066 !Param->isImplicit() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00005067 !getLangOpts().CPlusPlus)
Mike Stumpf8c49212010-01-21 03:59:47 +00005068 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00005069
5070 // C99 6.7.5.3p12:
5071 // If the function declarator is not part of a definition of that
5072 // function, parameters may have incomplete type and may use the [*]
5073 // notation in their sequences of declarator specifiers to specify
5074 // variable length array types.
5075 QualType PType = Param->getOriginalType();
5076 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
5077 if (AT->getSizeModifier() == ArrayType::Star) {
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00005078 // FIXME: This diagnosic should point the '[*]' if source-location
Sam Weinigd17e3402010-02-01 05:02:49 +00005079 // information is added for it.
5080 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
5081 }
5082 }
Mike Stumpf8c49212010-01-21 03:59:47 +00005083 }
5084
5085 return HasInvalidParm;
5086}
John McCallb7f4ffe2010-08-12 21:44:57 +00005087
5088/// CheckCastAlign - Implements -Wcast-align, which warns when a
5089/// pointer cast increases the alignment requirements.
5090void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
5091 // This is actually a lot of work to potentially be doing on every
5092 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00005093 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
5094 TRange.getBegin())
David Blaikied6471f72011-09-25 23:23:43 +00005095 == DiagnosticsEngine::Ignored)
John McCallb7f4ffe2010-08-12 21:44:57 +00005096 return;
5097
5098 // Ignore dependent types.
5099 if (T->isDependentType() || Op->getType()->isDependentType())
5100 return;
5101
5102 // Require that the destination be a pointer type.
5103 const PointerType *DestPtr = T->getAs<PointerType>();
5104 if (!DestPtr) return;
5105
5106 // If the destination has alignment 1, we're done.
5107 QualType DestPointee = DestPtr->getPointeeType();
5108 if (DestPointee->isIncompleteType()) return;
5109 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
5110 if (DestAlign.isOne()) return;
5111
5112 // Require that the source be a pointer type.
5113 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
5114 if (!SrcPtr) return;
5115 QualType SrcPointee = SrcPtr->getPointeeType();
5116
5117 // Whitelist casts from cv void*. We already implicitly
5118 // whitelisted casts to cv void*, since they have alignment 1.
5119 // Also whitelist casts involving incomplete types, which implicitly
5120 // includes 'void'.
5121 if (SrcPointee->isIncompleteType()) return;
5122
5123 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
5124 if (SrcAlign >= DestAlign) return;
5125
5126 Diag(TRange.getBegin(), diag::warn_cast_align)
5127 << Op->getType() << T
5128 << static_cast<unsigned>(SrcAlign.getQuantity())
5129 << static_cast<unsigned>(DestAlign.getQuantity())
5130 << TRange << Op->getSourceRange();
5131}
5132
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005133static const Type* getElementType(const Expr *BaseExpr) {
5134 const Type* EltType = BaseExpr->getType().getTypePtr();
5135 if (EltType->isAnyPointerType())
5136 return EltType->getPointeeType().getTypePtr();
5137 else if (EltType->isArrayType())
5138 return EltType->getBaseElementTypeUnsafe();
5139 return EltType;
5140}
5141
Chandler Carruthc2684342011-08-05 09:10:50 +00005142/// \brief Check whether this array fits the idiom of a size-one tail padded
5143/// array member of a struct.
5144///
5145/// We avoid emitting out-of-bounds access warnings for such arrays as they are
5146/// commonly used to emulate flexible arrays in C89 code.
5147static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
5148 const NamedDecl *ND) {
5149 if (Size != 1 || !ND) return false;
5150
5151 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
5152 if (!FD) return false;
5153
5154 // Don't consider sizes resulting from macro expansions or template argument
5155 // substitution to form C89 tail-padded arrays.
Sean Callanand2cf3482012-05-04 18:22:53 +00005156
5157 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00005158 while (TInfo) {
5159 TypeLoc TL = TInfo->getTypeLoc();
5160 // Look through typedefs.
5161 const TypedefTypeLoc *TTL = dyn_cast<TypedefTypeLoc>(&TL);
5162 if (TTL) {
5163 const TypedefNameDecl *TDL = TTL->getTypedefNameDecl();
5164 TInfo = TDL->getTypeSourceInfo();
5165 continue;
5166 }
5167 ConstantArrayTypeLoc CTL = cast<ConstantArrayTypeLoc>(TL);
5168 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Sean Callanand2cf3482012-05-04 18:22:53 +00005169 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
5170 return false;
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00005171 break;
Sean Callanand2cf3482012-05-04 18:22:53 +00005172 }
Chandler Carruthc2684342011-08-05 09:10:50 +00005173
5174 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gay381711c2011-11-29 22:43:53 +00005175 if (!RD) return false;
5176 if (RD->isUnion()) return false;
5177 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
5178 if (!CRD->isStandardLayout()) return false;
5179 }
Chandler Carruthc2684342011-08-05 09:10:50 +00005180
Benjamin Kramer22d4fed2011-08-06 03:04:42 +00005181 // See if this is the last field decl in the record.
5182 const Decl *D = FD;
5183 while ((D = D->getNextDeclInContext()))
5184 if (isa<FieldDecl>(D))
5185 return false;
5186 return true;
Chandler Carruthc2684342011-08-05 09:10:50 +00005187}
5188
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005189void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005190 const ArraySubscriptExpr *ASE,
Richard Smith25b009a2011-12-16 19:31:14 +00005191 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman92b670e2012-02-27 21:21:40 +00005192 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005193 if (IndexExpr->isValueDependent())
5194 return;
5195
Matt Beaumont-Gay8ef8f432011-12-12 22:35:02 +00005196 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005197 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00005198 const ConstantArrayType *ArrayTy =
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005199 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00005200 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00005201 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00005202
Chandler Carruth34064582011-02-17 20:55:08 +00005203 llvm::APSInt index;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005204 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00005205 return;
Richard Smith25b009a2011-12-16 19:31:14 +00005206 if (IndexNegated)
5207 index = -index;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00005208
Chandler Carruthba447122011-08-05 08:07:29 +00005209 const NamedDecl *ND = NULL;
Chandler Carruthba447122011-08-05 08:07:29 +00005210 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
5211 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruthc2684342011-08-05 09:10:50 +00005212 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruthba447122011-08-05 08:07:29 +00005213 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruthba447122011-08-05 08:07:29 +00005214
Ted Kremenek9e060ca2011-02-23 23:06:04 +00005215 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00005216 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00005217 if (!size.isStrictlyPositive())
5218 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005219
5220 const Type* BaseType = getElementType(BaseExpr);
Nico Weberde5998f2011-09-17 22:59:41 +00005221 if (BaseType != EffectiveType) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005222 // Make sure we're comparing apples to apples when comparing index to size
5223 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
5224 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhraind10f4bc2011-08-10 19:47:25 +00005225 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhrain18f16972011-08-10 18:49:28 +00005226 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005227 if (ptrarith_typesize != array_typesize) {
5228 // There's a cast to a different size type involved
5229 uint64_t ratio = array_typesize / ptrarith_typesize;
5230 // TODO: Be smarter about handling cases where array_typesize is not a
5231 // multiple of ptrarith_typesize
5232 if (ptrarith_typesize * ratio == array_typesize)
5233 size *= llvm::APInt(size.getBitWidth(), ratio);
5234 }
5235 }
5236
Chandler Carruth34064582011-02-17 20:55:08 +00005237 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00005238 index = index.zext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00005239 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00005240 size = size.zext(index.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00005241
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005242 // For array subscripting the index must be less than size, but for pointer
5243 // arithmetic also allow the index (offset) to be equal to size since
5244 // computing the next address after the end of the array is legal and
5245 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman92b670e2012-02-27 21:21:40 +00005246 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruthba447122011-08-05 08:07:29 +00005247 return;
5248
5249 // Also don't warn for arrays of size 1 which are members of some
5250 // structure. These are often used to approximate flexible arrays in C89
5251 // code.
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005252 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00005253 return;
Chandler Carruth34064582011-02-17 20:55:08 +00005254
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005255 // Suppress the warning if the subscript expression (as identified by the
5256 // ']' location) and the index expression are both from macro expansions
5257 // within a system header.
5258 if (ASE) {
5259 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
5260 ASE->getRBracketLoc());
5261 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
5262 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
5263 IndexExpr->getLocStart());
5264 if (SourceMgr.isFromSameFile(RBracketLoc, IndexLoc))
5265 return;
5266 }
5267 }
5268
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005269 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005270 if (ASE)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005271 DiagID = diag::warn_array_index_exceeds_bounds;
5272
5273 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
5274 PDiag(DiagID) << index.toString(10, true)
5275 << size.toString(10, true)
5276 << (unsigned)size.getLimitedValue(~0U)
5277 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00005278 } else {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005279 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005280 if (!ASE) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005281 DiagID = diag::warn_ptr_arith_precedes_bounds;
5282 if (index.isNegative()) index = -index;
5283 }
5284
5285 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
5286 PDiag(DiagID) << index.toString(10, true)
5287 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00005288 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00005289
Matt Beaumont-Gaycfbc5b52011-11-29 19:27:11 +00005290 if (!ND) {
5291 // Try harder to find a NamedDecl to point at in the note.
5292 while (const ArraySubscriptExpr *ASE =
5293 dyn_cast<ArraySubscriptExpr>(BaseExpr))
5294 BaseExpr = ASE->getBase()->IgnoreParenCasts();
5295 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
5296 ND = dyn_cast<NamedDecl>(DRE->getDecl());
5297 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
5298 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
5299 }
5300
Chandler Carruth35001ca2011-02-17 21:10:52 +00005301 if (ND)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005302 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
5303 PDiag(diag::note_array_index_out_of_bounds)
5304 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00005305}
5306
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005307void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005308 int AllowOnePastEnd = 0;
5309 while (expr) {
5310 expr = expr->IgnoreParenImpCasts();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005311 switch (expr->getStmtClass()) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005312 case Stmt::ArraySubscriptExprClass: {
5313 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005314 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005315 AllowOnePastEnd > 0);
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005316 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005317 }
5318 case Stmt::UnaryOperatorClass: {
5319 // Only unwrap the * and & unary operators
5320 const UnaryOperator *UO = cast<UnaryOperator>(expr);
5321 expr = UO->getSubExpr();
5322 switch (UO->getOpcode()) {
5323 case UO_AddrOf:
5324 AllowOnePastEnd++;
5325 break;
5326 case UO_Deref:
5327 AllowOnePastEnd--;
5328 break;
5329 default:
5330 return;
5331 }
5332 break;
5333 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005334 case Stmt::ConditionalOperatorClass: {
5335 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
5336 if (const Expr *lhs = cond->getLHS())
5337 CheckArrayAccess(lhs);
5338 if (const Expr *rhs = cond->getRHS())
5339 CheckArrayAccess(rhs);
5340 return;
5341 }
5342 default:
5343 return;
5344 }
Peter Collingbournef111d932011-04-15 00:35:48 +00005345 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00005346}
John McCallf85e1932011-06-15 23:02:42 +00005347
5348//===--- CHECK: Objective-C retain cycles ----------------------------------//
5349
5350namespace {
5351 struct RetainCycleOwner {
5352 RetainCycleOwner() : Variable(0), Indirect(false) {}
5353 VarDecl *Variable;
5354 SourceRange Range;
5355 SourceLocation Loc;
5356 bool Indirect;
5357
5358 void setLocsFrom(Expr *e) {
5359 Loc = e->getExprLoc();
5360 Range = e->getSourceRange();
5361 }
5362 };
5363}
5364
5365/// Consider whether capturing the given variable can possibly lead to
5366/// a retain cycle.
5367static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledruf3477c12012-09-27 10:16:10 +00005368 // In ARC, it's captured strongly iff the variable has __strong
John McCallf85e1932011-06-15 23:02:42 +00005369 // lifetime. In MRR, it's captured strongly if the variable is
5370 // __block and has an appropriate type.
5371 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
5372 return false;
5373
5374 owner.Variable = var;
Jordan Rosee10f4d32012-09-15 02:48:31 +00005375 if (ref)
5376 owner.setLocsFrom(ref);
John McCallf85e1932011-06-15 23:02:42 +00005377 return true;
5378}
5379
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00005380static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCallf85e1932011-06-15 23:02:42 +00005381 while (true) {
5382 e = e->IgnoreParens();
5383 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
5384 switch (cast->getCastKind()) {
5385 case CK_BitCast:
5386 case CK_LValueBitCast:
5387 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00005388 case CK_ARCReclaimReturnedObject:
John McCallf85e1932011-06-15 23:02:42 +00005389 e = cast->getSubExpr();
5390 continue;
5391
John McCallf85e1932011-06-15 23:02:42 +00005392 default:
5393 return false;
5394 }
5395 }
5396
5397 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
5398 ObjCIvarDecl *ivar = ref->getDecl();
5399 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
5400 return false;
5401
5402 // Try to find a retain cycle in the base.
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00005403 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCallf85e1932011-06-15 23:02:42 +00005404 return false;
5405
5406 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
5407 owner.Indirect = true;
5408 return true;
5409 }
5410
5411 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
5412 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
5413 if (!var) return false;
5414 return considerVariable(var, ref, owner);
5415 }
5416
John McCallf85e1932011-06-15 23:02:42 +00005417 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
5418 if (member->isArrow()) return false;
5419
5420 // Don't count this as an indirect ownership.
5421 e = member->getBase();
5422 continue;
5423 }
5424
John McCall4b9c2d22011-11-06 09:01:30 +00005425 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
5426 // Only pay attention to pseudo-objects on property references.
5427 ObjCPropertyRefExpr *pre
5428 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
5429 ->IgnoreParens());
5430 if (!pre) return false;
5431 if (pre->isImplicitProperty()) return false;
5432 ObjCPropertyDecl *property = pre->getExplicitProperty();
5433 if (!property->isRetaining() &&
5434 !(property->getPropertyIvarDecl() &&
5435 property->getPropertyIvarDecl()->getType()
5436 .getObjCLifetime() == Qualifiers::OCL_Strong))
5437 return false;
5438
5439 owner.Indirect = true;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00005440 if (pre->isSuperReceiver()) {
5441 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
5442 if (!owner.Variable)
5443 return false;
5444 owner.Loc = pre->getLocation();
5445 owner.Range = pre->getSourceRange();
5446 return true;
5447 }
John McCall4b9c2d22011-11-06 09:01:30 +00005448 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
5449 ->getSourceExpr());
5450 continue;
5451 }
5452
John McCallf85e1932011-06-15 23:02:42 +00005453 // Array ivars?
5454
5455 return false;
5456 }
5457}
5458
5459namespace {
5460 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
5461 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
5462 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
5463 Variable(variable), Capturer(0) {}
5464
5465 VarDecl *Variable;
5466 Expr *Capturer;
5467
5468 void VisitDeclRefExpr(DeclRefExpr *ref) {
5469 if (ref->getDecl() == Variable && !Capturer)
5470 Capturer = ref;
5471 }
5472
John McCallf85e1932011-06-15 23:02:42 +00005473 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
5474 if (Capturer) return;
5475 Visit(ref->getBase());
5476 if (Capturer && ref->isFreeIvar())
5477 Capturer = ref;
5478 }
5479
5480 void VisitBlockExpr(BlockExpr *block) {
5481 // Look inside nested blocks
5482 if (block->getBlockDecl()->capturesVariable(Variable))
5483 Visit(block->getBlockDecl()->getBody());
5484 }
Fariborz Jahanian7e2e4c32012-08-31 20:04:47 +00005485
5486 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
5487 if (Capturer) return;
5488 if (OVE->getSourceExpr())
5489 Visit(OVE->getSourceExpr());
5490 }
John McCallf85e1932011-06-15 23:02:42 +00005491 };
5492}
5493
5494/// Check whether the given argument is a block which captures a
5495/// variable.
5496static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
5497 assert(owner.Variable && owner.Loc.isValid());
5498
5499 e = e->IgnoreParenCasts();
Jordan Rose1fac58a2012-09-17 17:54:30 +00005500
5501 // Look through [^{...} copy] and Block_copy(^{...}).
5502 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
5503 Selector Cmd = ME->getSelector();
5504 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
5505 e = ME->getInstanceReceiver();
5506 if (!e)
5507 return 0;
5508 e = e->IgnoreParenCasts();
5509 }
5510 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
5511 if (CE->getNumArgs() == 1) {
5512 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
5513 if (Fn && Fn->getIdentifier()->isStr("_Block_copy"))
5514 e = CE->getArg(0)->IgnoreParenCasts();
5515 }
5516 }
5517
John McCallf85e1932011-06-15 23:02:42 +00005518 BlockExpr *block = dyn_cast<BlockExpr>(e);
5519 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
5520 return 0;
5521
5522 FindCaptureVisitor visitor(S.Context, owner.Variable);
5523 visitor.Visit(block->getBlockDecl()->getBody());
5524 return visitor.Capturer;
5525}
5526
5527static void diagnoseRetainCycle(Sema &S, Expr *capturer,
5528 RetainCycleOwner &owner) {
5529 assert(capturer);
5530 assert(owner.Variable && owner.Loc.isValid());
5531
5532 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
5533 << owner.Variable << capturer->getSourceRange();
5534 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
5535 << owner.Indirect << owner.Range;
5536}
5537
5538/// Check for a keyword selector that starts with the word 'add' or
5539/// 'set'.
5540static bool isSetterLikeSelector(Selector sel) {
5541 if (sel.isUnarySelector()) return false;
5542
Chris Lattner5f9e2722011-07-23 10:55:15 +00005543 StringRef str = sel.getNameForSlot(0);
John McCallf85e1932011-06-15 23:02:42 +00005544 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00005545 if (str.startswith("set"))
John McCallf85e1932011-06-15 23:02:42 +00005546 str = str.substr(3);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00005547 else if (str.startswith("add")) {
5548 // Specially whitelist 'addOperationWithBlock:'.
5549 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
5550 return false;
5551 str = str.substr(3);
5552 }
John McCallf85e1932011-06-15 23:02:42 +00005553 else
5554 return false;
5555
5556 if (str.empty()) return true;
5557 return !islower(str.front());
5558}
5559
5560/// Check a message send to see if it's likely to cause a retain cycle.
5561void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
5562 // Only check instance methods whose selector looks like a setter.
5563 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
5564 return;
5565
5566 // Try to find a variable that the receiver is strongly owned by.
5567 RetainCycleOwner owner;
5568 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00005569 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCallf85e1932011-06-15 23:02:42 +00005570 return;
5571 } else {
5572 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
5573 owner.Variable = getCurMethodDecl()->getSelfDecl();
5574 owner.Loc = msg->getSuperLoc();
5575 owner.Range = msg->getSuperLoc();
5576 }
5577
5578 // Check whether the receiver is captured by any of the arguments.
5579 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
5580 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
5581 return diagnoseRetainCycle(*this, capturer, owner);
5582}
5583
5584/// Check a property assign to see if it's likely to cause a retain cycle.
5585void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
5586 RetainCycleOwner owner;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00005587 if (!findRetainCycleOwner(*this, receiver, owner))
John McCallf85e1932011-06-15 23:02:42 +00005588 return;
5589
5590 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
5591 diagnoseRetainCycle(*this, capturer, owner);
5592}
5593
Jordan Rosee10f4d32012-09-15 02:48:31 +00005594void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
5595 RetainCycleOwner Owner;
5596 if (!considerVariable(Var, /*DeclRefExpr=*/0, Owner))
5597 return;
5598
5599 // Because we don't have an expression for the variable, we have to set the
5600 // location explicitly here.
5601 Owner.Loc = Var->getLocation();
5602 Owner.Range = Var->getSourceRange();
5603
5604 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
5605 diagnoseRetainCycle(*this, Capturer, Owner);
5606}
5607
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005608bool Sema::checkUnsafeAssigns(SourceLocation Loc,
John McCallf85e1932011-06-15 23:02:42 +00005609 QualType LHS, Expr *RHS) {
5610 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
5611 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005612 return false;
5613 // strip off any implicit cast added to get to the one arc-specific
5614 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00005615 if (cast->getCastKind() == CK_ARCConsumeObject) {
John McCallf85e1932011-06-15 23:02:42 +00005616 Diag(Loc, diag::warn_arc_retained_assign)
Fariborz Jahanianbd2e27e2012-07-06 21:09:27 +00005617 << (LT == Qualifiers::OCL_ExplicitNone) << 1
John McCallf85e1932011-06-15 23:02:42 +00005618 << RHS->getSourceRange();
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005619 return true;
5620 }
5621 RHS = cast->getSubExpr();
5622 }
5623 return false;
John McCallf85e1932011-06-15 23:02:42 +00005624}
5625
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005626void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
5627 Expr *LHS, Expr *RHS) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00005628 QualType LHSType;
5629 // PropertyRef on LHS type need be directly obtained from
5630 // its declaration as it has a PsuedoType.
5631 ObjCPropertyRefExpr *PRE
5632 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
5633 if (PRE && !PRE->isImplicitProperty()) {
5634 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
5635 if (PD)
5636 LHSType = PD->getType();
5637 }
5638
5639 if (LHSType.isNull())
5640 LHSType = LHS->getType();
Jordan Rose7a270482012-09-28 22:21:35 +00005641
5642 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
5643
5644 if (LT == Qualifiers::OCL_Weak) {
5645 DiagnosticsEngine::Level Level =
5646 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
5647 if (Level != DiagnosticsEngine::Ignored)
5648 getCurFunction()->markSafeWeakUse(LHS);
5649 }
5650
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005651 if (checkUnsafeAssigns(Loc, LHSType, RHS))
5652 return;
Jordan Rose7a270482012-09-28 22:21:35 +00005653
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005654 // FIXME. Check for other life times.
5655 if (LT != Qualifiers::OCL_None)
5656 return;
5657
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00005658 if (PRE) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005659 if (PRE->isImplicitProperty())
5660 return;
5661 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
5662 if (!PD)
5663 return;
5664
5665 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00005666 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
5667 // when 'assign' attribute was not explicitly specified
5668 // by user, ignore it and rely on property type itself
5669 // for lifetime info.
5670 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
5671 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
5672 LHSType->isObjCRetainableType())
5673 return;
5674
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005675 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00005676 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005677 Diag(Loc, diag::warn_arc_retained_property_assign)
5678 << RHS->getSourceRange();
5679 return;
5680 }
5681 RHS = cast->getSubExpr();
5682 }
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00005683 }
Fariborz Jahanianbd2e27e2012-07-06 21:09:27 +00005684 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
5685 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
5686 if (cast->getCastKind() == CK_ARCConsumeObject) {
5687 Diag(Loc, diag::warn_arc_retained_assign)
5688 << 0 << 0<< RHS->getSourceRange();
5689 return;
5690 }
5691 RHS = cast->getSubExpr();
5692 }
5693 }
Fariborz Jahanian921c1432011-06-24 18:25:34 +00005694 }
5695}
Dmitri Gribenko625bb562012-02-14 22:14:32 +00005696
5697//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
5698
5699namespace {
5700bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
5701 SourceLocation StmtLoc,
5702 const NullStmt *Body) {
5703 // Do not warn if the body is a macro that expands to nothing, e.g:
5704 //
5705 // #define CALL(x)
5706 // if (condition)
5707 // CALL(0);
5708 //
5709 if (Body->hasLeadingEmptyMacro())
5710 return false;
5711
5712 // Get line numbers of statement and body.
5713 bool StmtLineInvalid;
5714 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
5715 &StmtLineInvalid);
5716 if (StmtLineInvalid)
5717 return false;
5718
5719 bool BodyLineInvalid;
5720 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
5721 &BodyLineInvalid);
5722 if (BodyLineInvalid)
5723 return false;
5724
5725 // Warn if null statement and body are on the same line.
5726 if (StmtLine != BodyLine)
5727 return false;
5728
5729 return true;
5730}
5731} // Unnamed namespace
5732
5733void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
5734 const Stmt *Body,
5735 unsigned DiagID) {
5736 // Since this is a syntactic check, don't emit diagnostic for template
5737 // instantiations, this just adds noise.
5738 if (CurrentInstantiationScope)
5739 return;
5740
5741 // The body should be a null statement.
5742 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
5743 if (!NBody)
5744 return;
5745
5746 // Do the usual checks.
5747 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
5748 return;
5749
5750 Diag(NBody->getSemiLoc(), DiagID);
5751 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
5752}
5753
5754void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
5755 const Stmt *PossibleBody) {
5756 assert(!CurrentInstantiationScope); // Ensured by caller
5757
5758 SourceLocation StmtLoc;
5759 const Stmt *Body;
5760 unsigned DiagID;
5761 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
5762 StmtLoc = FS->getRParenLoc();
5763 Body = FS->getBody();
5764 DiagID = diag::warn_empty_for_body;
5765 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
5766 StmtLoc = WS->getCond()->getSourceRange().getEnd();
5767 Body = WS->getBody();
5768 DiagID = diag::warn_empty_while_body;
5769 } else
5770 return; // Neither `for' nor `while'.
5771
5772 // The body should be a null statement.
5773 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
5774 if (!NBody)
5775 return;
5776
5777 // Skip expensive checks if diagnostic is disabled.
5778 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
5779 DiagnosticsEngine::Ignored)
5780 return;
5781
5782 // Do the usual checks.
5783 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
5784 return;
5785
5786 // `for(...);' and `while(...);' are popular idioms, so in order to keep
5787 // noise level low, emit diagnostics only if for/while is followed by a
5788 // CompoundStmt, e.g.:
5789 // for (int i = 0; i < n; i++);
5790 // {
5791 // a(i);
5792 // }
5793 // or if for/while is followed by a statement with more indentation
5794 // than for/while itself:
5795 // for (int i = 0; i < n; i++);
5796 // a(i);
5797 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
5798 if (!ProbableTypo) {
5799 bool BodyColInvalid;
5800 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
5801 PossibleBody->getLocStart(),
5802 &BodyColInvalid);
5803 if (BodyColInvalid)
5804 return;
5805
5806 bool StmtColInvalid;
5807 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
5808 S->getLocStart(),
5809 &StmtColInvalid);
5810 if (StmtColInvalid)
5811 return;
5812
5813 if (BodyCol > StmtCol)
5814 ProbableTypo = true;
5815 }
5816
5817 if (ProbableTypo) {
5818 Diag(NBody->getSemiLoc(), DiagID);
5819 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
5820 }
5821}
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00005822
5823//===--- Layout compatibility ----------------------------------------------//
5824
5825namespace {
5826
5827bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
5828
5829/// \brief Check if two enumeration types are layout-compatible.
5830bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
5831 // C++11 [dcl.enum] p8:
5832 // Two enumeration types are layout-compatible if they have the same
5833 // underlying type.
5834 return ED1->isComplete() && ED2->isComplete() &&
5835 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
5836}
5837
5838/// \brief Check if two fields are layout-compatible.
5839bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
5840 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
5841 return false;
5842
5843 if (Field1->isBitField() != Field2->isBitField())
5844 return false;
5845
5846 if (Field1->isBitField()) {
5847 // Make sure that the bit-fields are the same length.
5848 unsigned Bits1 = Field1->getBitWidthValue(C);
5849 unsigned Bits2 = Field2->getBitWidthValue(C);
5850
5851 if (Bits1 != Bits2)
5852 return false;
5853 }
5854
5855 return true;
5856}
5857
5858/// \brief Check if two standard-layout structs are layout-compatible.
5859/// (C++11 [class.mem] p17)
5860bool isLayoutCompatibleStruct(ASTContext &C,
5861 RecordDecl *RD1,
5862 RecordDecl *RD2) {
5863 // If both records are C++ classes, check that base classes match.
5864 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
5865 // If one of records is a CXXRecordDecl we are in C++ mode,
5866 // thus the other one is a CXXRecordDecl, too.
5867 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
5868 // Check number of base classes.
5869 if (D1CXX->getNumBases() != D2CXX->getNumBases())
5870 return false;
5871
5872 // Check the base classes.
5873 for (CXXRecordDecl::base_class_const_iterator
5874 Base1 = D1CXX->bases_begin(),
5875 BaseEnd1 = D1CXX->bases_end(),
5876 Base2 = D2CXX->bases_begin();
5877 Base1 != BaseEnd1;
5878 ++Base1, ++Base2) {
5879 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
5880 return false;
5881 }
5882 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
5883 // If only RD2 is a C++ class, it should have zero base classes.
5884 if (D2CXX->getNumBases() > 0)
5885 return false;
5886 }
5887
5888 // Check the fields.
5889 RecordDecl::field_iterator Field2 = RD2->field_begin(),
5890 Field2End = RD2->field_end(),
5891 Field1 = RD1->field_begin(),
5892 Field1End = RD1->field_end();
5893 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
5894 if (!isLayoutCompatible(C, *Field1, *Field2))
5895 return false;
5896 }
5897 if (Field1 != Field1End || Field2 != Field2End)
5898 return false;
5899
5900 return true;
5901}
5902
5903/// \brief Check if two standard-layout unions are layout-compatible.
5904/// (C++11 [class.mem] p18)
5905bool isLayoutCompatibleUnion(ASTContext &C,
5906 RecordDecl *RD1,
5907 RecordDecl *RD2) {
5908 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
5909 for (RecordDecl::field_iterator Field2 = RD2->field_begin(),
5910 Field2End = RD2->field_end();
5911 Field2 != Field2End; ++Field2) {
5912 UnmatchedFields.insert(*Field2);
5913 }
5914
5915 for (RecordDecl::field_iterator Field1 = RD1->field_begin(),
5916 Field1End = RD1->field_end();
5917 Field1 != Field1End; ++Field1) {
5918 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
5919 I = UnmatchedFields.begin(),
5920 E = UnmatchedFields.end();
5921
5922 for ( ; I != E; ++I) {
5923 if (isLayoutCompatible(C, *Field1, *I)) {
5924 bool Result = UnmatchedFields.erase(*I);
5925 (void) Result;
5926 assert(Result);
5927 break;
5928 }
5929 }
5930 if (I == E)
5931 return false;
5932 }
5933
5934 return UnmatchedFields.empty();
5935}
5936
5937bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
5938 if (RD1->isUnion() != RD2->isUnion())
5939 return false;
5940
5941 if (RD1->isUnion())
5942 return isLayoutCompatibleUnion(C, RD1, RD2);
5943 else
5944 return isLayoutCompatibleStruct(C, RD1, RD2);
5945}
5946
5947/// \brief Check if two types are layout-compatible in C++11 sense.
5948bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
5949 if (T1.isNull() || T2.isNull())
5950 return false;
5951
5952 // C++11 [basic.types] p11:
5953 // If two types T1 and T2 are the same type, then T1 and T2 are
5954 // layout-compatible types.
5955 if (C.hasSameType(T1, T2))
5956 return true;
5957
5958 T1 = T1.getCanonicalType().getUnqualifiedType();
5959 T2 = T2.getCanonicalType().getUnqualifiedType();
5960
5961 const Type::TypeClass TC1 = T1->getTypeClass();
5962 const Type::TypeClass TC2 = T2->getTypeClass();
5963
5964 if (TC1 != TC2)
5965 return false;
5966
5967 if (TC1 == Type::Enum) {
5968 return isLayoutCompatible(C,
5969 cast<EnumType>(T1)->getDecl(),
5970 cast<EnumType>(T2)->getDecl());
5971 } else if (TC1 == Type::Record) {
5972 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
5973 return false;
5974
5975 return isLayoutCompatible(C,
5976 cast<RecordType>(T1)->getDecl(),
5977 cast<RecordType>(T2)->getDecl());
5978 }
5979
5980 return false;
5981}
5982}
5983
5984//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
5985
5986namespace {
5987/// \brief Given a type tag expression find the type tag itself.
5988///
5989/// \param TypeExpr Type tag expression, as it appears in user's code.
5990///
5991/// \param VD Declaration of an identifier that appears in a type tag.
5992///
5993/// \param MagicValue Type tag magic value.
5994bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
5995 const ValueDecl **VD, uint64_t *MagicValue) {
5996 while(true) {
5997 if (!TypeExpr)
5998 return false;
5999
6000 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
6001
6002 switch (TypeExpr->getStmtClass()) {
6003 case Stmt::UnaryOperatorClass: {
6004 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
6005 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
6006 TypeExpr = UO->getSubExpr();
6007 continue;
6008 }
6009 return false;
6010 }
6011
6012 case Stmt::DeclRefExprClass: {
6013 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
6014 *VD = DRE->getDecl();
6015 return true;
6016 }
6017
6018 case Stmt::IntegerLiteralClass: {
6019 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
6020 llvm::APInt MagicValueAPInt = IL->getValue();
6021 if (MagicValueAPInt.getActiveBits() <= 64) {
6022 *MagicValue = MagicValueAPInt.getZExtValue();
6023 return true;
6024 } else
6025 return false;
6026 }
6027
6028 case Stmt::BinaryConditionalOperatorClass:
6029 case Stmt::ConditionalOperatorClass: {
6030 const AbstractConditionalOperator *ACO =
6031 cast<AbstractConditionalOperator>(TypeExpr);
6032 bool Result;
6033 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
6034 if (Result)
6035 TypeExpr = ACO->getTrueExpr();
6036 else
6037 TypeExpr = ACO->getFalseExpr();
6038 continue;
6039 }
6040 return false;
6041 }
6042
6043 case Stmt::BinaryOperatorClass: {
6044 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
6045 if (BO->getOpcode() == BO_Comma) {
6046 TypeExpr = BO->getRHS();
6047 continue;
6048 }
6049 return false;
6050 }
6051
6052 default:
6053 return false;
6054 }
6055 }
6056}
6057
6058/// \brief Retrieve the C type corresponding to type tag TypeExpr.
6059///
6060/// \param TypeExpr Expression that specifies a type tag.
6061///
6062/// \param MagicValues Registered magic values.
6063///
6064/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
6065/// kind.
6066///
6067/// \param TypeInfo Information about the corresponding C type.
6068///
6069/// \returns true if the corresponding C type was found.
6070bool GetMatchingCType(
6071 const IdentifierInfo *ArgumentKind,
6072 const Expr *TypeExpr, const ASTContext &Ctx,
6073 const llvm::DenseMap<Sema::TypeTagMagicValue,
6074 Sema::TypeTagData> *MagicValues,
6075 bool &FoundWrongKind,
6076 Sema::TypeTagData &TypeInfo) {
6077 FoundWrongKind = false;
6078
6079 // Variable declaration that has type_tag_for_datatype attribute.
6080 const ValueDecl *VD = NULL;
6081
6082 uint64_t MagicValue;
6083
6084 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
6085 return false;
6086
6087 if (VD) {
6088 for (specific_attr_iterator<TypeTagForDatatypeAttr>
6089 I = VD->specific_attr_begin<TypeTagForDatatypeAttr>(),
6090 E = VD->specific_attr_end<TypeTagForDatatypeAttr>();
6091 I != E; ++I) {
6092 if (I->getArgumentKind() != ArgumentKind) {
6093 FoundWrongKind = true;
6094 return false;
6095 }
6096 TypeInfo.Type = I->getMatchingCType();
6097 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
6098 TypeInfo.MustBeNull = I->getMustBeNull();
6099 return true;
6100 }
6101 return false;
6102 }
6103
6104 if (!MagicValues)
6105 return false;
6106
6107 llvm::DenseMap<Sema::TypeTagMagicValue,
6108 Sema::TypeTagData>::const_iterator I =
6109 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
6110 if (I == MagicValues->end())
6111 return false;
6112
6113 TypeInfo = I->second;
6114 return true;
6115}
6116} // unnamed namespace
6117
6118void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
6119 uint64_t MagicValue, QualType Type,
6120 bool LayoutCompatible,
6121 bool MustBeNull) {
6122 if (!TypeTagForDatatypeMagicValues)
6123 TypeTagForDatatypeMagicValues.reset(
6124 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
6125
6126 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
6127 (*TypeTagForDatatypeMagicValues)[Magic] =
6128 TypeTagData(Type, LayoutCompatible, MustBeNull);
6129}
6130
6131namespace {
6132bool IsSameCharType(QualType T1, QualType T2) {
6133 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
6134 if (!BT1)
6135 return false;
6136
6137 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
6138 if (!BT2)
6139 return false;
6140
6141 BuiltinType::Kind T1Kind = BT1->getKind();
6142 BuiltinType::Kind T2Kind = BT2->getKind();
6143
6144 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
6145 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
6146 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
6147 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
6148}
6149} // unnamed namespace
6150
6151void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
6152 const Expr * const *ExprArgs) {
6153 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
6154 bool IsPointerAttr = Attr->getIsPointer();
6155
6156 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
6157 bool FoundWrongKind;
6158 TypeTagData TypeInfo;
6159 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
6160 TypeTagForDatatypeMagicValues.get(),
6161 FoundWrongKind, TypeInfo)) {
6162 if (FoundWrongKind)
6163 Diag(TypeTagExpr->getExprLoc(),
6164 diag::warn_type_tag_for_datatype_wrong_kind)
6165 << TypeTagExpr->getSourceRange();
6166 return;
6167 }
6168
6169 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
6170 if (IsPointerAttr) {
6171 // Skip implicit cast of pointer to `void *' (as a function argument).
6172 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
6173 if (ICE->getType()->isVoidPointerType())
6174 ArgumentExpr = ICE->getSubExpr();
6175 }
6176 QualType ArgumentType = ArgumentExpr->getType();
6177
6178 // Passing a `void*' pointer shouldn't trigger a warning.
6179 if (IsPointerAttr && ArgumentType->isVoidPointerType())
6180 return;
6181
6182 if (TypeInfo.MustBeNull) {
6183 // Type tag with matching void type requires a null pointer.
6184 if (!ArgumentExpr->isNullPointerConstant(Context,
6185 Expr::NPC_ValueDependentIsNotNull)) {
6186 Diag(ArgumentExpr->getExprLoc(),
6187 diag::warn_type_safety_null_pointer_required)
6188 << ArgumentKind->getName()
6189 << ArgumentExpr->getSourceRange()
6190 << TypeTagExpr->getSourceRange();
6191 }
6192 return;
6193 }
6194
6195 QualType RequiredType = TypeInfo.Type;
6196 if (IsPointerAttr)
6197 RequiredType = Context.getPointerType(RequiredType);
6198
6199 bool mismatch = false;
6200 if (!TypeInfo.LayoutCompatible) {
6201 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
6202
6203 // C++11 [basic.fundamental] p1:
6204 // Plain char, signed char, and unsigned char are three distinct types.
6205 //
6206 // But we treat plain `char' as equivalent to `signed char' or `unsigned
6207 // char' depending on the current char signedness mode.
6208 if (mismatch)
6209 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
6210 RequiredType->getPointeeType())) ||
6211 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
6212 mismatch = false;
6213 } else
6214 if (IsPointerAttr)
6215 mismatch = !isLayoutCompatible(Context,
6216 ArgumentType->getPointeeType(),
6217 RequiredType->getPointeeType());
6218 else
6219 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
6220
6221 if (mismatch)
6222 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
6223 << ArgumentType << ArgumentKind->getName()
6224 << TypeInfo.LayoutCompatible << RequiredType
6225 << ArgumentExpr->getSourceRange()
6226 << TypeTagExpr->getSourceRange();
6227}