blob: a48a7b273e4f358acc1dd9074ab0e4b398b54b91 [file] [log] [blame]
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-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 Lattnerb87b1b32007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
Mike Stump11289f42009-09-09 15:08:12 +000010// This file implements extra semantic analysis beyond what is enforced
Chris Lattnerb87b1b32007-08-10 20:18:51 +000011// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
John McCall83024632010-08-25 22:03:47 +000015#include "clang/Sema/SemaInternal.h"
Chris Lattnerb87b1b32007-08-10 20:18:51 +000016#include "clang/AST/ASTContext.h"
Ken Dyck40775002010-01-11 17:06:35 +000017#include "clang/AST/CharUnits.h"
John McCall28a0cf72010-08-25 07:42:41 +000018#include "clang/AST/DeclCXX.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000019#include "clang/AST/DeclObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/AST/EvaluatedExprVisitor.h"
David Blaikie7555b6a2012-05-15 16:56:36 +000021#include "clang/AST/Expr.h"
Ted Kremenekc81614d2007-08-20 16:18:38 +000022#include "clang/AST/ExprCXX.h"
Ted Kremenek34f664d2008-06-16 18:00:42 +000023#include "clang/AST/ExprObjC.h"
Mike Stump0c2ec772010-01-21 03:59:47 +000024#include "clang/AST/StmtCXX.h"
25#include "clang/AST/StmtObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/Analysis/Analyses/FormatString.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000027#include "clang/Basic/CharInfo.h"
Eric Christopher8d0c6212010-04-17 02:26:23 +000028#include "clang/Basic/TargetBuiltins.h"
Nate Begeman4904e322010-06-08 02:47:44 +000029#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000030#include "clang/Lex/Preprocessor.h"
31#include "clang/Sema/Initialization.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "clang/Sema/Lookup.h"
33#include "clang/Sema/ScopeInfo.h"
34#include "clang/Sema/Sema.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000035#include "llvm/ADT/STLExtras.h"
Richard Smithd7293d72013-08-05 18:49:43 +000036#include "llvm/ADT/SmallBitVector.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000037#include "llvm/ADT/SmallString.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000038#include "llvm/Support/ConvertUTF.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000039#include "llvm/Support/raw_ostream.h"
Zhongxing Xu050379b2009-05-20 01:55:10 +000040#include <limits>
Chris Lattnerb87b1b32007-08-10 20:18:51 +000041using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000042using namespace sema;
Chris Lattnerb87b1b32007-08-10 20:18:51 +000043
Chris Lattnera26fb342009-02-18 17:49:48 +000044SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
45 unsigned ByteNo) const {
Chris Lattnere925d612010-11-17 07:37:15 +000046 return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +000047 PP.getLangOpts(), PP.getTargetInfo());
Chris Lattnera26fb342009-02-18 17:49:48 +000048}
49
John McCallbebede42011-02-26 05:39:39 +000050/// Checks that a call expression's argument count is the desired number.
51/// This is useful when doing custom type-checking. Returns true on error.
52static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
53 unsigned argCount = call->getNumArgs();
54 if (argCount == desiredArgCount) return false;
55
56 if (argCount < desiredArgCount)
57 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
58 << 0 /*function call*/ << desiredArgCount << argCount
59 << call->getSourceRange();
60
61 // Highlight all the excess arguments.
62 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
63 call->getArg(argCount - 1)->getLocEnd());
64
65 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
66 << 0 /*function call*/ << desiredArgCount << argCount
67 << call->getArg(1)->getSourceRange();
68}
69
Julien Lerouge4a5b4442012-04-28 17:39:16 +000070/// Check that the first argument to __builtin_annotation is an integer
71/// and the second argument is a non-wide string literal.
72static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
73 if (checkArgCount(S, TheCall, 2))
74 return true;
75
76 // First argument should be an integer.
77 Expr *ValArg = TheCall->getArg(0);
78 QualType Ty = ValArg->getType();
79 if (!Ty->isIntegerType()) {
80 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
81 << ValArg->getSourceRange();
Julien Lerouge5a6b6982011-09-09 22:41:49 +000082 return true;
83 }
Julien Lerouge4a5b4442012-04-28 17:39:16 +000084
85 // Second argument should be a constant string.
86 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
87 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
88 if (!Literal || !Literal->isAscii()) {
89 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
90 << StrArg->getSourceRange();
91 return true;
92 }
93
94 TheCall->setType(Ty);
Julien Lerouge5a6b6982011-09-09 22:41:49 +000095 return false;
96}
97
Richard Smith6cbd65d2013-07-11 02:27:57 +000098/// Check that the argument to __builtin_addressof is a glvalue, and set the
99/// result type to the corresponding pointer type.
100static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
101 if (checkArgCount(S, TheCall, 1))
102 return true;
103
104 ExprResult Arg(S.Owned(TheCall->getArg(0)));
105 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
106 if (ResultType.isNull())
107 return true;
108
109 TheCall->setArg(0, Arg.take());
110 TheCall->setType(ResultType);
111 return false;
112}
113
John McCalldadc5752010-08-24 06:29:42 +0000114ExprResult
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000115Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
John McCalldadc5752010-08-24 06:29:42 +0000116 ExprResult TheCallResult(Owned(TheCall));
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000117
Chris Lattner3be167f2010-10-01 23:23:24 +0000118 // Find out if any arguments are required to be integer constant expressions.
119 unsigned ICEArguments = 0;
120 ASTContext::GetBuiltinTypeError Error;
121 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
122 if (Error != ASTContext::GE_None)
123 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
124
125 // If any arguments are required to be ICE's, check and diagnose.
126 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
127 // Skip arguments not required to be ICE's.
128 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
129
130 llvm::APSInt Result;
131 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
132 return true;
133 ICEArguments &= ~(1 << ArgNo);
134 }
135
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000136 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000137 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000138 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000139 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000140 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000141 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000142 break;
Ted Kremeneka174c522008-07-09 17:58:53 +0000143 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000144 case Builtin::BI__builtin_va_start:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000145 if (SemaBuiltinVAStart(TheCall))
146 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000147 break;
Chris Lattner2da14fb2007-12-20 00:26:33 +0000148 case Builtin::BI__builtin_isgreater:
149 case Builtin::BI__builtin_isgreaterequal:
150 case Builtin::BI__builtin_isless:
151 case Builtin::BI__builtin_islessequal:
152 case Builtin::BI__builtin_islessgreater:
153 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000154 if (SemaBuiltinUnorderedCompare(TheCall))
155 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000156 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000157 case Builtin::BI__builtin_fpclassify:
158 if (SemaBuiltinFPClassification(TheCall, 6))
159 return ExprError();
160 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000161 case Builtin::BI__builtin_isfinite:
162 case Builtin::BI__builtin_isinf:
163 case Builtin::BI__builtin_isinf_sign:
164 case Builtin::BI__builtin_isnan:
165 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000166 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000167 return ExprError();
168 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000169 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000170 return SemaBuiltinShuffleVector(TheCall);
171 // TheCall will be freed by the smart pointer here, but that's fine, since
172 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000173 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000174 if (SemaBuiltinPrefetch(TheCall))
175 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000176 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000177 case Builtin::BI__builtin_object_size:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000178 if (SemaBuiltinObjectSize(TheCall))
179 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000180 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000181 case Builtin::BI__builtin_longjmp:
182 if (SemaBuiltinLongjmp(TheCall))
183 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000184 break;
John McCallbebede42011-02-26 05:39:39 +0000185
186 case Builtin::BI__builtin_classify_type:
187 if (checkArgCount(*this, TheCall, 1)) return true;
188 TheCall->setType(Context.IntTy);
189 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000190 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000191 if (checkArgCount(*this, TheCall, 1)) return true;
192 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000193 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000194 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000195 case Builtin::BI__sync_fetch_and_add_1:
196 case Builtin::BI__sync_fetch_and_add_2:
197 case Builtin::BI__sync_fetch_and_add_4:
198 case Builtin::BI__sync_fetch_and_add_8:
199 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000200 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000201 case Builtin::BI__sync_fetch_and_sub_1:
202 case Builtin::BI__sync_fetch_and_sub_2:
203 case Builtin::BI__sync_fetch_and_sub_4:
204 case Builtin::BI__sync_fetch_and_sub_8:
205 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000206 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000207 case Builtin::BI__sync_fetch_and_or_1:
208 case Builtin::BI__sync_fetch_and_or_2:
209 case Builtin::BI__sync_fetch_and_or_4:
210 case Builtin::BI__sync_fetch_and_or_8:
211 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000212 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000213 case Builtin::BI__sync_fetch_and_and_1:
214 case Builtin::BI__sync_fetch_and_and_2:
215 case Builtin::BI__sync_fetch_and_and_4:
216 case Builtin::BI__sync_fetch_and_and_8:
217 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000218 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000219 case Builtin::BI__sync_fetch_and_xor_1:
220 case Builtin::BI__sync_fetch_and_xor_2:
221 case Builtin::BI__sync_fetch_and_xor_4:
222 case Builtin::BI__sync_fetch_and_xor_8:
223 case Builtin::BI__sync_fetch_and_xor_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000224 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000225 case Builtin::BI__sync_add_and_fetch_1:
226 case Builtin::BI__sync_add_and_fetch_2:
227 case Builtin::BI__sync_add_and_fetch_4:
228 case Builtin::BI__sync_add_and_fetch_8:
229 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000230 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000231 case Builtin::BI__sync_sub_and_fetch_1:
232 case Builtin::BI__sync_sub_and_fetch_2:
233 case Builtin::BI__sync_sub_and_fetch_4:
234 case Builtin::BI__sync_sub_and_fetch_8:
235 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000236 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000237 case Builtin::BI__sync_and_and_fetch_1:
238 case Builtin::BI__sync_and_and_fetch_2:
239 case Builtin::BI__sync_and_and_fetch_4:
240 case Builtin::BI__sync_and_and_fetch_8:
241 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000242 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000243 case Builtin::BI__sync_or_and_fetch_1:
244 case Builtin::BI__sync_or_and_fetch_2:
245 case Builtin::BI__sync_or_and_fetch_4:
246 case Builtin::BI__sync_or_and_fetch_8:
247 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000248 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000249 case Builtin::BI__sync_xor_and_fetch_1:
250 case Builtin::BI__sync_xor_and_fetch_2:
251 case Builtin::BI__sync_xor_and_fetch_4:
252 case Builtin::BI__sync_xor_and_fetch_8:
253 case Builtin::BI__sync_xor_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000254 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000255 case Builtin::BI__sync_val_compare_and_swap_1:
256 case Builtin::BI__sync_val_compare_and_swap_2:
257 case Builtin::BI__sync_val_compare_and_swap_4:
258 case Builtin::BI__sync_val_compare_and_swap_8:
259 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000260 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000261 case Builtin::BI__sync_bool_compare_and_swap_1:
262 case Builtin::BI__sync_bool_compare_and_swap_2:
263 case Builtin::BI__sync_bool_compare_and_swap_4:
264 case Builtin::BI__sync_bool_compare_and_swap_8:
265 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000266 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000267 case Builtin::BI__sync_lock_test_and_set_1:
268 case Builtin::BI__sync_lock_test_and_set_2:
269 case Builtin::BI__sync_lock_test_and_set_4:
270 case Builtin::BI__sync_lock_test_and_set_8:
271 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000272 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000273 case Builtin::BI__sync_lock_release_1:
274 case Builtin::BI__sync_lock_release_2:
275 case Builtin::BI__sync_lock_release_4:
276 case Builtin::BI__sync_lock_release_8:
277 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000278 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000279 case Builtin::BI__sync_swap_1:
280 case Builtin::BI__sync_swap_2:
281 case Builtin::BI__sync_swap_4:
282 case Builtin::BI__sync_swap_8:
283 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000284 return SemaBuiltinAtomicOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +0000285#define BUILTIN(ID, TYPE, ATTRS)
286#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
287 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000288 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +0000289#include "clang/Basic/Builtins.def"
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000290 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000291 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000292 return ExprError();
293 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +0000294 case Builtin::BI__builtin_addressof:
295 if (SemaBuiltinAddressof(*this, TheCall))
296 return ExprError();
297 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000298 }
299
300 // Since the target specific builtins for each arch overlap, only check those
301 // of the arch we are compiling for.
302 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000303 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +0000304 case llvm::Triple::arm:
305 case llvm::Triple::thumb:
306 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
307 return ExprError();
308 break;
Tim Northover2fe823a2013-08-01 09:23:19 +0000309 case llvm::Triple::aarch64:
310 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
311 return ExprError();
312 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000313 case llvm::Triple::mips:
314 case llvm::Triple::mipsel:
315 case llvm::Triple::mips64:
316 case llvm::Triple::mips64el:
317 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
318 return ExprError();
319 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000320 case llvm::Triple::x86:
321 case llvm::Triple::x86_64:
322 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
323 return ExprError();
324 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000325 default:
326 break;
327 }
328 }
329
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000330 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +0000331}
332
Nate Begeman91e1fea2010-06-14 05:21:25 +0000333// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +0000334static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +0000335 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +0000336 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +0000337 switch (Type.getEltType()) {
338 case NeonTypeFlags::Int8:
339 case NeonTypeFlags::Poly8:
340 return shift ? 7 : (8 << IsQuad) - 1;
341 case NeonTypeFlags::Int16:
342 case NeonTypeFlags::Poly16:
343 return shift ? 15 : (4 << IsQuad) - 1;
344 case NeonTypeFlags::Int32:
345 return shift ? 31 : (2 << IsQuad) - 1;
346 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +0000347 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +0000348 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000349 case NeonTypeFlags::Poly128:
350 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +0000351 case NeonTypeFlags::Float16:
352 assert(!shift && "cannot shift float types!");
353 return (4 << IsQuad) - 1;
354 case NeonTypeFlags::Float32:
355 assert(!shift && "cannot shift float types!");
356 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000357 case NeonTypeFlags::Float64:
358 assert(!shift && "cannot shift float types!");
359 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000360 }
David Blaikie8a40f702012-01-17 06:56:22 +0000361 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +0000362}
363
Bob Wilsone4d77232011-11-08 05:04:11 +0000364/// getNeonEltType - Return the QualType corresponding to the elements of
365/// the vector type specified by the NeonTypeFlags. This is used to check
366/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +0000367static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
368 bool IsAArch64) {
Bob Wilsone4d77232011-11-08 05:04:11 +0000369 switch (Flags.getEltType()) {
370 case NeonTypeFlags::Int8:
371 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
372 case NeonTypeFlags::Int16:
373 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
374 case NeonTypeFlags::Int32:
375 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
376 case NeonTypeFlags::Int64:
377 return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy;
378 case NeonTypeFlags::Poly8:
Kevin Qincaac85e2013-11-14 03:29:16 +0000379 return IsAArch64 ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000380 case NeonTypeFlags::Poly16:
Kevin Qincaac85e2013-11-14 03:29:16 +0000381 return IsAArch64 ? Context.UnsignedShortTy : Context.ShortTy;
382 case NeonTypeFlags::Poly64:
383 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000384 case NeonTypeFlags::Poly128:
385 break;
Bob Wilsone4d77232011-11-08 05:04:11 +0000386 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +0000387 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000388 case NeonTypeFlags::Float32:
389 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +0000390 case NeonTypeFlags::Float64:
391 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000392 }
David Blaikie8a40f702012-01-17 06:56:22 +0000393 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +0000394}
395
Tim Northover12670412014-02-19 10:37:05 +0000396bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +0000397 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +0000398 uint64_t mask = 0;
399 unsigned TV = 0;
400 int PtrArgNum = -1;
401 bool HasConstPtr = false;
402 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +0000403#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000404#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000405#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000406 }
407
408 // For NEON intrinsics which are overloaded on vector element type, validate
409 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +0000410 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000411 if (mask) {
412 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
413 return true;
414
415 TV = Result.getLimitedValue(64);
416 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
417 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +0000418 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +0000419 }
420
421 if (PtrArgNum >= 0) {
422 // Check that pointer arguments have the specified type.
423 Expr *Arg = TheCall->getArg(PtrArgNum);
424 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
425 Arg = ICE->getSubExpr();
426 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
427 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +0000428
429 bool IsAArch64 =
430 Context.getTargetInfo().getTriple().getArch() == llvm::Triple::aarch64;
431 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context, IsAArch64);
Tim Northover2fe823a2013-08-01 09:23:19 +0000432 if (HasConstPtr)
433 EltTy = EltTy.withConst();
434 QualType LHSTy = Context.getPointerType(EltTy);
435 AssignConvertType ConvTy;
436 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
437 if (RHS.isInvalid())
438 return true;
439 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
440 RHS.get(), AA_Assigning))
441 return true;
442 }
443
444 // For NEON intrinsics which take an immediate value as part of the
445 // instruction, range check them here.
446 unsigned i = 0, l = 0, u = 0;
447 switch (BuiltinID) {
448 default:
449 return false;
Tim Northover12670412014-02-19 10:37:05 +0000450#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000451#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000452#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000453 }
454 ;
455
456 // We can't check the value of a dependent argument.
457 if (TheCall->getArg(i)->isTypeDependent() ||
458 TheCall->getArg(i)->isValueDependent())
459 return false;
460
461 // Check that the immediate argument is actually a constant.
462 if (SemaBuiltinConstantArg(TheCall, i, Result))
463 return true;
464
465 // Range check against the upper/lower values for this isntruction.
466 unsigned Val = Result.getZExtValue();
467 if (Val < l || Val > (u + l))
468 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
469 << l << u + l << TheCall->getArg(i)->getSourceRange();
470
471 return false;
472}
473
Tim Northover12670412014-02-19 10:37:05 +0000474bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
475 CallExpr *TheCall) {
476 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
477 return true;
478
479 return false;
480}
481
Tim Northover6aacd492013-07-16 09:47:53 +0000482bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall) {
483 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
484 BuiltinID == ARM::BI__builtin_arm_strex) &&
485 "unexpected ARM builtin");
486 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex;
487
488 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
489
490 // Ensure that we have the proper number of arguments.
491 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
492 return true;
493
494 // Inspect the pointer argument of the atomic builtin. This should always be
495 // a pointer type, whose element is an integral scalar or pointer type.
496 // Because it is a pointer type, we don't have to worry about any implicit
497 // casts here.
498 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
499 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
500 if (PointerArgRes.isInvalid())
501 return true;
502 PointerArg = PointerArgRes.take();
503
504 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
505 if (!pointerType) {
506 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
507 << PointerArg->getType() << PointerArg->getSourceRange();
508 return true;
509 }
510
511 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
512 // task is to insert the appropriate casts into the AST. First work out just
513 // what the appropriate type is.
514 QualType ValType = pointerType->getPointeeType();
515 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
516 if (IsLdrex)
517 AddrType.addConst();
518
519 // Issue a warning if the cast is dodgy.
520 CastKind CastNeeded = CK_NoOp;
521 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
522 CastNeeded = CK_BitCast;
523 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
524 << PointerArg->getType()
525 << Context.getPointerType(AddrType)
526 << AA_Passing << PointerArg->getSourceRange();
527 }
528
529 // Finally, do the cast and replace the argument with the corrected version.
530 AddrType = Context.getPointerType(AddrType);
531 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
532 if (PointerArgRes.isInvalid())
533 return true;
534 PointerArg = PointerArgRes.take();
535
536 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
537
538 // In general, we allow ints, floats and pointers to be loaded and stored.
539 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
540 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
541 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
542 << PointerArg->getType() << PointerArg->getSourceRange();
543 return true;
544 }
545
546 // But ARM doesn't have instructions to deal with 128-bit versions.
547 if (Context.getTypeSize(ValType) > 64) {
548 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
549 << PointerArg->getType() << PointerArg->getSourceRange();
550 return true;
551 }
552
553 switch (ValType.getObjCLifetime()) {
554 case Qualifiers::OCL_None:
555 case Qualifiers::OCL_ExplicitNone:
556 // okay
557 break;
558
559 case Qualifiers::OCL_Weak:
560 case Qualifiers::OCL_Strong:
561 case Qualifiers::OCL_Autoreleasing:
562 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
563 << ValType << PointerArg->getSourceRange();
564 return true;
565 }
566
567
568 if (IsLdrex) {
569 TheCall->setType(ValType);
570 return false;
571 }
572
573 // Initialize the argument to be stored.
574 ExprResult ValArg = TheCall->getArg(0);
575 InitializedEntity Entity = InitializedEntity::InitializeParameter(
576 Context, ValType, /*consume*/ false);
577 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
578 if (ValArg.isInvalid())
579 return true;
Tim Northover6aacd492013-07-16 09:47:53 +0000580 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +0000581
582 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
583 // but the custom checker bypasses all default analysis.
584 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +0000585 return false;
586}
587
Nate Begeman4904e322010-06-08 02:47:44 +0000588bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +0000589 llvm::APSInt Result;
590
Tim Northover6aacd492013-07-16 09:47:53 +0000591 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
592 BuiltinID == ARM::BI__builtin_arm_strex) {
593 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall);
594 }
595
Tim Northover12670412014-02-19 10:37:05 +0000596 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
597 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +0000598
Nate Begemand773fe62010-06-13 04:47:52 +0000599 // For NEON intrinsics which take an immediate value as part of the
600 // instruction, range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +0000601 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +0000602 switch (BuiltinID) {
603 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +0000604 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
605 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +0000606 case ARM::BI__builtin_arm_vcvtr_f:
607 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +0000608 case ARM::BI__builtin_arm_dmb:
609 case ARM::BI__builtin_arm_dsb: l = 0; u = 15; break;
Nate Begemand773fe62010-06-13 04:47:52 +0000610 };
611
Douglas Gregor98c3cfc2012-06-29 01:05:22 +0000612 // We can't check the value of a dependent argument.
613 if (TheCall->getArg(i)->isTypeDependent() ||
614 TheCall->getArg(i)->isValueDependent())
615 return false;
616
Nate Begeman91e1fea2010-06-14 05:21:25 +0000617 // Check that the immediate argument is actually a constant.
Nate Begemand773fe62010-06-13 04:47:52 +0000618 if (SemaBuiltinConstantArg(TheCall, i, Result))
619 return true;
620
Nate Begeman91e1fea2010-06-14 05:21:25 +0000621 // Range check against the upper/lower values for this isntruction.
Nate Begemand773fe62010-06-13 04:47:52 +0000622 unsigned Val = Result.getZExtValue();
Nate Begeman91e1fea2010-06-14 05:21:25 +0000623 if (Val < l || Val > (u + l))
Nate Begemand773fe62010-06-13 04:47:52 +0000624 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramere8394df2010-08-11 14:47:12 +0000625 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begemand773fe62010-06-13 04:47:52 +0000626
Nate Begemanf568b072010-08-03 21:32:34 +0000627 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman4904e322010-06-08 02:47:44 +0000628 return false;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000629}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000630
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000631bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
632 unsigned i = 0, l = 0, u = 0;
633 switch (BuiltinID) {
634 default: return false;
635 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
636 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +0000637 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
638 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
639 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
640 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
641 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000642 };
643
644 // We can't check the value of a dependent argument.
645 if (TheCall->getArg(i)->isTypeDependent() ||
646 TheCall->getArg(i)->isValueDependent())
647 return false;
648
649 // Check that the immediate argument is actually a constant.
650 llvm::APSInt Result;
651 if (SemaBuiltinConstantArg(TheCall, i, Result))
652 return true;
653
654 // Range check against the upper/lower values for this instruction.
655 unsigned Val = Result.getZExtValue();
656 if (Val < l || Val > u)
657 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
658 << l << u << TheCall->getArg(i)->getSourceRange();
659
660 return false;
661}
662
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000663bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
664 switch (BuiltinID) {
665 case X86::BI_mm_prefetch:
666 return SemaBuiltinMMPrefetch(TheCall);
667 break;
668 }
669 return false;
670}
671
Richard Smith55ce3522012-06-25 20:30:08 +0000672/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
673/// parameter with the FormatAttr's correct format_idx and firstDataArg.
674/// Returns true when the format fits the function and the FormatStringInfo has
675/// been populated.
676bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
677 FormatStringInfo *FSI) {
678 FSI->HasVAListArg = Format->getFirstArg() == 0;
679 FSI->FormatIdx = Format->getFormatIdx() - 1;
680 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000681
Richard Smith55ce3522012-06-25 20:30:08 +0000682 // The way the format attribute works in GCC, the implicit this argument
683 // of member functions is counted. However, it doesn't appear in our own
684 // lists, so decrement format_idx in that case.
685 if (IsCXXMember) {
686 if(FSI->FormatIdx == 0)
687 return false;
688 --FSI->FormatIdx;
689 if (FSI->FirstDataArg != 0)
690 --FSI->FirstDataArg;
691 }
692 return true;
693}
Mike Stump11289f42009-09-09 15:08:12 +0000694
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000695/// Checks if a the given expression evaluates to null.
696///
697/// \brief Returns true if the value evaluates to null.
698static bool CheckNonNullExpr(Sema &S,
699 const Expr *Expr) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000700 // As a special case, transparent unions initialized with zero are
701 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000702 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000703 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
704 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000705 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000706 if (const InitListExpr *ILE =
707 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000708 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +0000709 }
710
711 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +0000712 return (!Expr->isValueDependent() &&
713 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
714 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000715}
716
717static void CheckNonNullArgument(Sema &S,
718 const Expr *ArgExpr,
719 SourceLocation CallSiteLoc) {
720 if (CheckNonNullExpr(S, ArgExpr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000721 S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
722}
723
Ted Kremenek2bc73332014-01-17 06:24:43 +0000724static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +0000725 const NamedDecl *FDecl,
Ted Kremenek2bc73332014-01-17 06:24:43 +0000726 const Expr * const *ExprArgs,
727 SourceLocation CallSiteLoc) {
Ted Kremenek9aedc152014-01-17 06:24:56 +0000728 // Check the attributes attached to the method/function itself.
Ted Kremeneka146db32014-01-17 06:24:47 +0000729 for (specific_attr_iterator<NonNullAttr>
730 I = FDecl->specific_attr_begin<NonNullAttr>(),
731 E = FDecl->specific_attr_end<NonNullAttr>(); I != E; ++I) {
Ted Kremenek2bc73332014-01-17 06:24:43 +0000732
Ted Kremeneka146db32014-01-17 06:24:47 +0000733 const NonNullAttr *NonNull = *I;
734 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
735 e = NonNull->args_end();
736 i != e; ++i) {
737 CheckNonNullArgument(S, ExprArgs[*i], CallSiteLoc);
Ted Kremenek2bc73332014-01-17 06:24:43 +0000738 }
Ted Kremenek2bc73332014-01-17 06:24:43 +0000739 }
Ted Kremenek9aedc152014-01-17 06:24:56 +0000740
741 // Check the attributes on the parameters.
742 ArrayRef<ParmVarDecl*> parms;
743 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
744 parms = FD->parameters();
745 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(FDecl))
746 parms = MD->parameters();
747
748 unsigned argIndex = 0;
749 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
750 I != E; ++I, ++argIndex) {
751 const ParmVarDecl *PVD = *I;
752 if (PVD->hasAttr<NonNullAttr>())
753 CheckNonNullArgument(S, ExprArgs[argIndex], CallSiteLoc);
754 }
Ted Kremenek2bc73332014-01-17 06:24:43 +0000755}
756
Richard Smith55ce3522012-06-25 20:30:08 +0000757/// Handles the checks for format strings, non-POD arguments to vararg
758/// functions, and NULL arguments passed to non-NULL parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +0000759void Sema::checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
760 unsigned NumParams, bool IsMemberFunction,
761 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +0000762 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +0000763 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +0000764 if (CurContext->isDependentContext())
765 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000766
Ted Kremenekb8176da2010-09-09 04:33:05 +0000767 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +0000768 llvm::SmallBitVector CheckedVarArgs;
769 if (FDecl) {
Richard Trieu41bc0992013-06-22 00:20:41 +0000770 for (specific_attr_iterator<FormatAttr>
Benjamin Kramerf62e81d2013-08-08 11:08:26 +0000771 I = FDecl->specific_attr_begin<FormatAttr>(),
772 E = FDecl->specific_attr_end<FormatAttr>();
Benjamin Kramer989ab8b2013-08-09 09:39:17 +0000773 I != E; ++I) {
774 // Only create vector if there are format attributes.
775 CheckedVarArgs.resize(Args.size());
776
Benjamin Kramerf62e81d2013-08-08 11:08:26 +0000777 CheckFormatArguments(*I, Args, IsMemberFunction, CallType, Loc, Range,
778 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +0000779 }
Richard Smithd7293d72013-08-05 18:49:43 +0000780 }
Richard Smith55ce3522012-06-25 20:30:08 +0000781
782 // Refuse POD arguments that weren't caught by the format string
783 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +0000784 if (CallType != VariadicDoesNotApply) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000785 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +0000786 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +0000787 if (const Expr *Arg = Args[ArgIdx]) {
788 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
789 checkVariadicArgument(Arg, CallType);
790 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +0000791 }
Richard Smithd7293d72013-08-05 18:49:43 +0000792 }
Mike Stump11289f42009-09-09 15:08:12 +0000793
Richard Trieu41bc0992013-06-22 00:20:41 +0000794 if (FDecl) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000795 CheckNonNullArguments(*this, FDecl, Args.data(), Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000796
Richard Trieu41bc0992013-06-22 00:20:41 +0000797 // Type safety checking.
798 for (specific_attr_iterator<ArgumentWithTypeTagAttr>
799 i = FDecl->specific_attr_begin<ArgumentWithTypeTagAttr>(),
800 e = FDecl->specific_attr_end<ArgumentWithTypeTagAttr>();
801 i != e; ++i) {
802 CheckArgumentWithTypeTag(*i, Args.data());
803 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000804 }
Richard Smith55ce3522012-06-25 20:30:08 +0000805}
806
807/// CheckConstructorCall - Check a constructor call for correctness and safety
808/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +0000809void Sema::CheckConstructorCall(FunctionDecl *FDecl,
810 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +0000811 const FunctionProtoType *Proto,
812 SourceLocation Loc) {
813 VariadicCallType CallType =
814 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Alp Toker9cacbab2014-01-20 20:26:09 +0000815 checkCall(FDecl, Args, Proto->getNumParams(),
Richard Smith55ce3522012-06-25 20:30:08 +0000816 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
817}
818
819/// CheckFunctionCall - Check a direct function call for various correctness
820/// and safety properties not strictly enforced by the C type system.
821bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
822 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +0000823 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
824 isa<CXXMethodDecl>(FDecl);
825 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
826 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +0000827 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
828 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +0000829 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Eli Friedman726d11c2012-10-11 00:30:58 +0000830 Expr** Args = TheCall->getArgs();
831 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +0000832 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +0000833 // If this is a call to a member operator, hide the first argument
834 // from checkCall.
835 // FIXME: Our choice of AST representation here is less than ideal.
836 ++Args;
837 --NumArgs;
838 }
Alp Toker9cacbab2014-01-20 20:26:09 +0000839 checkCall(FDecl, llvm::makeArrayRef<const Expr *>(Args, NumArgs), NumParams,
Richard Smith55ce3522012-06-25 20:30:08 +0000840 IsMemberFunction, TheCall->getRParenLoc(),
841 TheCall->getCallee()->getSourceRange(), CallType);
842
843 IdentifierInfo *FnInfo = FDecl->getIdentifier();
844 // None of the checks below are needed for functions that don't have
845 // simple names (e.g., C++ conversion functions).
846 if (!FnInfo)
847 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000848
Anna Zaks22122702012-01-17 00:37:07 +0000849 unsigned CMId = FDecl->getMemoryFunctionKind();
850 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +0000851 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +0000852
Anna Zaks201d4892012-01-13 21:52:01 +0000853 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +0000854 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +0000855 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +0000856 else if (CMId == Builtin::BIstrncat)
857 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +0000858 else
Anna Zaks22122702012-01-17 00:37:07 +0000859 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +0000860
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000861 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +0000862}
863
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000864bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +0000865 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +0000866 VariadicCallType CallType =
867 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000868
Dmitri Gribenko1debc462013-05-05 19:42:09 +0000869 checkCall(Method, Args, Method->param_size(),
Richard Smith55ce3522012-06-25 20:30:08 +0000870 /*IsMemberFunction=*/false,
871 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000872
873 return false;
874}
875
Richard Trieu664c4c62013-06-20 21:03:13 +0000876bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
877 const FunctionProtoType *Proto) {
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000878 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
879 if (!V)
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000880 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000881
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000882 QualType Ty = V->getType();
Richard Trieu664c4c62013-06-20 21:03:13 +0000883 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000884 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000885
Richard Trieu664c4c62013-06-20 21:03:13 +0000886 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +0000887 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +0000888 CallType = VariadicDoesNotApply;
889 } else if (Ty->isBlockPointerType()) {
890 CallType = VariadicBlock;
891 } else { // Ty->isFunctionPointerType()
892 CallType = VariadicFunction;
893 }
Alp Toker9cacbab2014-01-20 20:26:09 +0000894 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000895
Alp Toker9cacbab2014-01-20 20:26:09 +0000896 checkCall(NDecl, llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
897 TheCall->getNumArgs()),
898 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +0000899 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +0000900
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000901 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000902}
903
Richard Trieu41bc0992013-06-22 00:20:41 +0000904/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
905/// such as function pointers returned from functions.
906bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
907 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/0, Proto,
908 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +0000909 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Richard Trieu41bc0992013-06-22 00:20:41 +0000910
Alp Toker9cacbab2014-01-20 20:26:09 +0000911 checkCall(/*FDecl=*/0, llvm::makeArrayRef<const Expr *>(
912 TheCall->getArgs(), TheCall->getNumArgs()),
913 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +0000914 TheCall->getCallee()->getSourceRange(), CallType);
915
916 return false;
917}
918
Richard Smithfeea8832012-04-12 05:08:17 +0000919ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
920 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000921 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
922 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000923
Richard Smithfeea8832012-04-12 05:08:17 +0000924 // All these operations take one of the following forms:
925 enum {
926 // C __c11_atomic_init(A *, C)
927 Init,
928 // C __c11_atomic_load(A *, int)
929 Load,
930 // void __atomic_load(A *, CP, int)
931 Copy,
932 // C __c11_atomic_add(A *, M, int)
933 Arithmetic,
934 // C __atomic_exchange_n(A *, CP, int)
935 Xchg,
936 // void __atomic_exchange(A *, C *, CP, int)
937 GNUXchg,
938 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
939 C11CmpXchg,
940 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
941 GNUCmpXchg
942 } Form = Init;
943 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
944 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
945 // where:
946 // C is an appropriate type,
947 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
948 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
949 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
950 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000951
Richard Smithfeea8832012-04-12 05:08:17 +0000952 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
953 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
954 && "need to update code for modified C11 atomics");
955 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
956 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
957 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
958 Op == AtomicExpr::AO__atomic_store_n ||
959 Op == AtomicExpr::AO__atomic_exchange_n ||
960 Op == AtomicExpr::AO__atomic_compare_exchange_n;
961 bool IsAddSub = false;
962
963 switch (Op) {
964 case AtomicExpr::AO__c11_atomic_init:
965 Form = Init;
966 break;
967
968 case AtomicExpr::AO__c11_atomic_load:
969 case AtomicExpr::AO__atomic_load_n:
970 Form = Load;
971 break;
972
973 case AtomicExpr::AO__c11_atomic_store:
974 case AtomicExpr::AO__atomic_load:
975 case AtomicExpr::AO__atomic_store:
976 case AtomicExpr::AO__atomic_store_n:
977 Form = Copy;
978 break;
979
980 case AtomicExpr::AO__c11_atomic_fetch_add:
981 case AtomicExpr::AO__c11_atomic_fetch_sub:
982 case AtomicExpr::AO__atomic_fetch_add:
983 case AtomicExpr::AO__atomic_fetch_sub:
984 case AtomicExpr::AO__atomic_add_fetch:
985 case AtomicExpr::AO__atomic_sub_fetch:
986 IsAddSub = true;
987 // Fall through.
988 case AtomicExpr::AO__c11_atomic_fetch_and:
989 case AtomicExpr::AO__c11_atomic_fetch_or:
990 case AtomicExpr::AO__c11_atomic_fetch_xor:
991 case AtomicExpr::AO__atomic_fetch_and:
992 case AtomicExpr::AO__atomic_fetch_or:
993 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +0000994 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +0000995 case AtomicExpr::AO__atomic_and_fetch:
996 case AtomicExpr::AO__atomic_or_fetch:
997 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +0000998 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +0000999 Form = Arithmetic;
1000 break;
1001
1002 case AtomicExpr::AO__c11_atomic_exchange:
1003 case AtomicExpr::AO__atomic_exchange_n:
1004 Form = Xchg;
1005 break;
1006
1007 case AtomicExpr::AO__atomic_exchange:
1008 Form = GNUXchg;
1009 break;
1010
1011 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1012 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1013 Form = C11CmpXchg;
1014 break;
1015
1016 case AtomicExpr::AO__atomic_compare_exchange:
1017 case AtomicExpr::AO__atomic_compare_exchange_n:
1018 Form = GNUCmpXchg;
1019 break;
1020 }
1021
1022 // Check we have the right number of arguments.
1023 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001024 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001025 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001026 << TheCall->getCallee()->getSourceRange();
1027 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00001028 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1029 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001030 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001031 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001032 << TheCall->getCallee()->getSourceRange();
1033 return ExprError();
1034 }
1035
Richard Smithfeea8832012-04-12 05:08:17 +00001036 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001037 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001038 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1039 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1040 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00001041 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001042 << Ptr->getType() << Ptr->getSourceRange();
1043 return ExprError();
1044 }
1045
Richard Smithfeea8832012-04-12 05:08:17 +00001046 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1047 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1048 QualType ValType = AtomTy; // 'C'
1049 if (IsC11) {
1050 if (!AtomTy->isAtomicType()) {
1051 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1052 << Ptr->getType() << Ptr->getSourceRange();
1053 return ExprError();
1054 }
Richard Smithe00921a2012-09-15 06:09:58 +00001055 if (AtomTy.isConstQualified()) {
1056 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1057 << Ptr->getType() << Ptr->getSourceRange();
1058 return ExprError();
1059 }
Richard Smithfeea8832012-04-12 05:08:17 +00001060 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001061 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001062
Richard Smithfeea8832012-04-12 05:08:17 +00001063 // For an arithmetic operation, the implied arithmetic must be well-formed.
1064 if (Form == Arithmetic) {
1065 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1066 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1067 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1068 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1069 return ExprError();
1070 }
1071 if (!IsAddSub && !ValType->isIntegerType()) {
1072 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1073 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1074 return ExprError();
1075 }
1076 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1077 // For __atomic_*_n operations, the value type must be a scalar integral or
1078 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001079 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00001080 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1081 return ExprError();
1082 }
1083
Eli Friedmanaa769812013-09-11 03:49:34 +00001084 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1085 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00001086 // For GNU atomics, require a trivially-copyable type. This is not part of
1087 // the GNU atomics specification, but we enforce it for sanity.
1088 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001089 << Ptr->getType() << Ptr->getSourceRange();
1090 return ExprError();
1091 }
1092
Richard Smithfeea8832012-04-12 05:08:17 +00001093 // FIXME: For any builtin other than a load, the ValType must not be
1094 // const-qualified.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001095
1096 switch (ValType.getObjCLifetime()) {
1097 case Qualifiers::OCL_None:
1098 case Qualifiers::OCL_ExplicitNone:
1099 // okay
1100 break;
1101
1102 case Qualifiers::OCL_Weak:
1103 case Qualifiers::OCL_Strong:
1104 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00001105 // FIXME: Can this happen? By this point, ValType should be known
1106 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001107 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1108 << ValType << Ptr->getSourceRange();
1109 return ExprError();
1110 }
1111
1112 QualType ResultType = ValType;
Richard Smithfeea8832012-04-12 05:08:17 +00001113 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001114 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00001115 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001116 ResultType = Context.BoolTy;
1117
Richard Smithfeea8832012-04-12 05:08:17 +00001118 // The type of a parameter passed 'by value'. In the GNU atomics, such
1119 // arguments are actually passed as pointers.
1120 QualType ByValType = ValType; // 'CP'
1121 if (!IsC11 && !IsN)
1122 ByValType = Ptr->getType();
1123
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001124 // The first argument --- the pointer --- has a fixed type; we
1125 // deduce the types of the rest of the arguments accordingly. Walk
1126 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00001127 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001128 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00001129 if (i < NumVals[Form] + 1) {
1130 switch (i) {
1131 case 1:
1132 // The second argument is the non-atomic operand. For arithmetic, this
1133 // is always passed by value, and for a compare_exchange it is always
1134 // passed by address. For the rest, GNU uses by-address and C11 uses
1135 // by-value.
1136 assert(Form != Load);
1137 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1138 Ty = ValType;
1139 else if (Form == Copy || Form == Xchg)
1140 Ty = ByValType;
1141 else if (Form == Arithmetic)
1142 Ty = Context.getPointerDiffType();
1143 else
1144 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1145 break;
1146 case 2:
1147 // The third argument to compare_exchange / GNU exchange is a
1148 // (pointer to a) desired value.
1149 Ty = ByValType;
1150 break;
1151 case 3:
1152 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1153 Ty = Context.BoolTy;
1154 break;
1155 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001156 } else {
1157 // The order(s) are always converted to int.
1158 Ty = Context.IntTy;
1159 }
Richard Smithfeea8832012-04-12 05:08:17 +00001160
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001161 InitializedEntity Entity =
1162 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00001163 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001164 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1165 if (Arg.isInvalid())
1166 return true;
1167 TheCall->setArg(i, Arg.get());
1168 }
1169
Richard Smithfeea8832012-04-12 05:08:17 +00001170 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001171 SmallVector<Expr*, 5> SubExprs;
1172 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00001173 switch (Form) {
1174 case Init:
1175 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00001176 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001177 break;
1178 case Load:
1179 SubExprs.push_back(TheCall->getArg(1)); // Order
1180 break;
1181 case Copy:
1182 case Arithmetic:
1183 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001184 SubExprs.push_back(TheCall->getArg(2)); // Order
1185 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001186 break;
1187 case GNUXchg:
1188 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1189 SubExprs.push_back(TheCall->getArg(3)); // Order
1190 SubExprs.push_back(TheCall->getArg(1)); // Val1
1191 SubExprs.push_back(TheCall->getArg(2)); // Val2
1192 break;
1193 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001194 SubExprs.push_back(TheCall->getArg(3)); // Order
1195 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001196 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00001197 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00001198 break;
1199 case GNUCmpXchg:
1200 SubExprs.push_back(TheCall->getArg(4)); // Order
1201 SubExprs.push_back(TheCall->getArg(1)); // Val1
1202 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1203 SubExprs.push_back(TheCall->getArg(2)); // Val2
1204 SubExprs.push_back(TheCall->getArg(3)); // Weak
1205 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001206 }
Fariborz Jahanian615de762013-05-28 17:37:39 +00001207
1208 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1209 SubExprs, ResultType, Op,
1210 TheCall->getRParenLoc());
1211
1212 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1213 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1214 Context.AtomicUsesUnsupportedLibcall(AE))
1215 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1216 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001217
Fariborz Jahanian615de762013-05-28 17:37:39 +00001218 return Owned(AE);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001219}
1220
1221
John McCall29ad95b2011-08-27 01:09:30 +00001222/// checkBuiltinArgument - Given a call to a builtin function, perform
1223/// normal type-checking on the given argument, updating the call in
1224/// place. This is useful when a builtin function requires custom
1225/// type-checking for some of its arguments but not necessarily all of
1226/// them.
1227///
1228/// Returns true on error.
1229static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1230 FunctionDecl *Fn = E->getDirectCallee();
1231 assert(Fn && "builtin call without direct callee!");
1232
1233 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1234 InitializedEntity Entity =
1235 InitializedEntity::InitializeParameter(S.Context, Param);
1236
1237 ExprResult Arg = E->getArg(0);
1238 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1239 if (Arg.isInvalid())
1240 return true;
1241
1242 E->setArg(ArgIndex, Arg.take());
1243 return false;
1244}
1245
Chris Lattnerdc046542009-05-08 06:58:22 +00001246/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1247/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1248/// type of its first argument. The main ActOnCallExpr routines have already
1249/// promoted the types of arguments because all of these calls are prototyped as
1250/// void(...).
1251///
1252/// This function goes through and does final semantic checking for these
1253/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00001254ExprResult
1255Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001256 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00001257 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1258 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1259
1260 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001261 if (TheCall->getNumArgs() < 1) {
1262 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1263 << 0 << 1 << TheCall->getNumArgs()
1264 << TheCall->getCallee()->getSourceRange();
1265 return ExprError();
1266 }
Mike Stump11289f42009-09-09 15:08:12 +00001267
Chris Lattnerdc046542009-05-08 06:58:22 +00001268 // Inspect the first argument of the atomic builtin. This should always be
1269 // a pointer type, whose element is an integral scalar or pointer type.
1270 // Because it is a pointer type, we don't have to worry about any implicit
1271 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001272 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00001273 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00001274 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1275 if (FirstArgResult.isInvalid())
1276 return ExprError();
1277 FirstArg = FirstArgResult.take();
1278 TheCall->setArg(0, FirstArg);
1279
John McCall31168b02011-06-15 23:02:42 +00001280 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1281 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001282 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1283 << FirstArg->getType() << FirstArg->getSourceRange();
1284 return ExprError();
1285 }
Mike Stump11289f42009-09-09 15:08:12 +00001286
John McCall31168b02011-06-15 23:02:42 +00001287 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00001288 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001289 !ValType->isBlockPointerType()) {
1290 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1291 << FirstArg->getType() << FirstArg->getSourceRange();
1292 return ExprError();
1293 }
Chris Lattnerdc046542009-05-08 06:58:22 +00001294
John McCall31168b02011-06-15 23:02:42 +00001295 switch (ValType.getObjCLifetime()) {
1296 case Qualifiers::OCL_None:
1297 case Qualifiers::OCL_ExplicitNone:
1298 // okay
1299 break;
1300
1301 case Qualifiers::OCL_Weak:
1302 case Qualifiers::OCL_Strong:
1303 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00001304 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00001305 << ValType << FirstArg->getSourceRange();
1306 return ExprError();
1307 }
1308
John McCallb50451a2011-10-05 07:41:44 +00001309 // Strip any qualifiers off ValType.
1310 ValType = ValType.getUnqualifiedType();
1311
Chandler Carruth3973af72010-07-18 20:54:12 +00001312 // The majority of builtins return a value, but a few have special return
1313 // types, so allow them to override appropriately below.
1314 QualType ResultType = ValType;
1315
Chris Lattnerdc046542009-05-08 06:58:22 +00001316 // We need to figure out which concrete builtin this maps onto. For example,
1317 // __sync_fetch_and_add with a 2 byte object turns into
1318 // __sync_fetch_and_add_2.
1319#define BUILTIN_ROW(x) \
1320 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1321 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00001322
Chris Lattnerdc046542009-05-08 06:58:22 +00001323 static const unsigned BuiltinIndices[][5] = {
1324 BUILTIN_ROW(__sync_fetch_and_add),
1325 BUILTIN_ROW(__sync_fetch_and_sub),
1326 BUILTIN_ROW(__sync_fetch_and_or),
1327 BUILTIN_ROW(__sync_fetch_and_and),
1328 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump11289f42009-09-09 15:08:12 +00001329
Chris Lattnerdc046542009-05-08 06:58:22 +00001330 BUILTIN_ROW(__sync_add_and_fetch),
1331 BUILTIN_ROW(__sync_sub_and_fetch),
1332 BUILTIN_ROW(__sync_and_and_fetch),
1333 BUILTIN_ROW(__sync_or_and_fetch),
1334 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00001335
Chris Lattnerdc046542009-05-08 06:58:22 +00001336 BUILTIN_ROW(__sync_val_compare_and_swap),
1337 BUILTIN_ROW(__sync_bool_compare_and_swap),
1338 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00001339 BUILTIN_ROW(__sync_lock_release),
1340 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00001341 };
Mike Stump11289f42009-09-09 15:08:12 +00001342#undef BUILTIN_ROW
1343
Chris Lattnerdc046542009-05-08 06:58:22 +00001344 // Determine the index of the size.
1345 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00001346 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00001347 case 1: SizeIndex = 0; break;
1348 case 2: SizeIndex = 1; break;
1349 case 4: SizeIndex = 2; break;
1350 case 8: SizeIndex = 3; break;
1351 case 16: SizeIndex = 4; break;
1352 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001353 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1354 << FirstArg->getType() << FirstArg->getSourceRange();
1355 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00001356 }
Mike Stump11289f42009-09-09 15:08:12 +00001357
Chris Lattnerdc046542009-05-08 06:58:22 +00001358 // Each of these builtins has one pointer argument, followed by some number of
1359 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1360 // that we ignore. Find out which row of BuiltinIndices to read from as well
1361 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00001362 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00001363 unsigned BuiltinIndex, NumFixed = 1;
1364 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00001365 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00001366 case Builtin::BI__sync_fetch_and_add:
1367 case Builtin::BI__sync_fetch_and_add_1:
1368 case Builtin::BI__sync_fetch_and_add_2:
1369 case Builtin::BI__sync_fetch_and_add_4:
1370 case Builtin::BI__sync_fetch_and_add_8:
1371 case Builtin::BI__sync_fetch_and_add_16:
1372 BuiltinIndex = 0;
1373 break;
1374
1375 case Builtin::BI__sync_fetch_and_sub:
1376 case Builtin::BI__sync_fetch_and_sub_1:
1377 case Builtin::BI__sync_fetch_and_sub_2:
1378 case Builtin::BI__sync_fetch_and_sub_4:
1379 case Builtin::BI__sync_fetch_and_sub_8:
1380 case Builtin::BI__sync_fetch_and_sub_16:
1381 BuiltinIndex = 1;
1382 break;
1383
1384 case Builtin::BI__sync_fetch_and_or:
1385 case Builtin::BI__sync_fetch_and_or_1:
1386 case Builtin::BI__sync_fetch_and_or_2:
1387 case Builtin::BI__sync_fetch_and_or_4:
1388 case Builtin::BI__sync_fetch_and_or_8:
1389 case Builtin::BI__sync_fetch_and_or_16:
1390 BuiltinIndex = 2;
1391 break;
1392
1393 case Builtin::BI__sync_fetch_and_and:
1394 case Builtin::BI__sync_fetch_and_and_1:
1395 case Builtin::BI__sync_fetch_and_and_2:
1396 case Builtin::BI__sync_fetch_and_and_4:
1397 case Builtin::BI__sync_fetch_and_and_8:
1398 case Builtin::BI__sync_fetch_and_and_16:
1399 BuiltinIndex = 3;
1400 break;
Mike Stump11289f42009-09-09 15:08:12 +00001401
Douglas Gregor73722482011-11-28 16:30:08 +00001402 case Builtin::BI__sync_fetch_and_xor:
1403 case Builtin::BI__sync_fetch_and_xor_1:
1404 case Builtin::BI__sync_fetch_and_xor_2:
1405 case Builtin::BI__sync_fetch_and_xor_4:
1406 case Builtin::BI__sync_fetch_and_xor_8:
1407 case Builtin::BI__sync_fetch_and_xor_16:
1408 BuiltinIndex = 4;
1409 break;
1410
1411 case Builtin::BI__sync_add_and_fetch:
1412 case Builtin::BI__sync_add_and_fetch_1:
1413 case Builtin::BI__sync_add_and_fetch_2:
1414 case Builtin::BI__sync_add_and_fetch_4:
1415 case Builtin::BI__sync_add_and_fetch_8:
1416 case Builtin::BI__sync_add_and_fetch_16:
1417 BuiltinIndex = 5;
1418 break;
1419
1420 case Builtin::BI__sync_sub_and_fetch:
1421 case Builtin::BI__sync_sub_and_fetch_1:
1422 case Builtin::BI__sync_sub_and_fetch_2:
1423 case Builtin::BI__sync_sub_and_fetch_4:
1424 case Builtin::BI__sync_sub_and_fetch_8:
1425 case Builtin::BI__sync_sub_and_fetch_16:
1426 BuiltinIndex = 6;
1427 break;
1428
1429 case Builtin::BI__sync_and_and_fetch:
1430 case Builtin::BI__sync_and_and_fetch_1:
1431 case Builtin::BI__sync_and_and_fetch_2:
1432 case Builtin::BI__sync_and_and_fetch_4:
1433 case Builtin::BI__sync_and_and_fetch_8:
1434 case Builtin::BI__sync_and_and_fetch_16:
1435 BuiltinIndex = 7;
1436 break;
1437
1438 case Builtin::BI__sync_or_and_fetch:
1439 case Builtin::BI__sync_or_and_fetch_1:
1440 case Builtin::BI__sync_or_and_fetch_2:
1441 case Builtin::BI__sync_or_and_fetch_4:
1442 case Builtin::BI__sync_or_and_fetch_8:
1443 case Builtin::BI__sync_or_and_fetch_16:
1444 BuiltinIndex = 8;
1445 break;
1446
1447 case Builtin::BI__sync_xor_and_fetch:
1448 case Builtin::BI__sync_xor_and_fetch_1:
1449 case Builtin::BI__sync_xor_and_fetch_2:
1450 case Builtin::BI__sync_xor_and_fetch_4:
1451 case Builtin::BI__sync_xor_and_fetch_8:
1452 case Builtin::BI__sync_xor_and_fetch_16:
1453 BuiltinIndex = 9;
1454 break;
Mike Stump11289f42009-09-09 15:08:12 +00001455
Chris Lattnerdc046542009-05-08 06:58:22 +00001456 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001457 case Builtin::BI__sync_val_compare_and_swap_1:
1458 case Builtin::BI__sync_val_compare_and_swap_2:
1459 case Builtin::BI__sync_val_compare_and_swap_4:
1460 case Builtin::BI__sync_val_compare_and_swap_8:
1461 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001462 BuiltinIndex = 10;
Chris Lattnerdc046542009-05-08 06:58:22 +00001463 NumFixed = 2;
1464 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001465
Chris Lattnerdc046542009-05-08 06:58:22 +00001466 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001467 case Builtin::BI__sync_bool_compare_and_swap_1:
1468 case Builtin::BI__sync_bool_compare_and_swap_2:
1469 case Builtin::BI__sync_bool_compare_and_swap_4:
1470 case Builtin::BI__sync_bool_compare_and_swap_8:
1471 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001472 BuiltinIndex = 11;
Chris Lattnerdc046542009-05-08 06:58:22 +00001473 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00001474 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001475 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001476
1477 case Builtin::BI__sync_lock_test_and_set:
1478 case Builtin::BI__sync_lock_test_and_set_1:
1479 case Builtin::BI__sync_lock_test_and_set_2:
1480 case Builtin::BI__sync_lock_test_and_set_4:
1481 case Builtin::BI__sync_lock_test_and_set_8:
1482 case Builtin::BI__sync_lock_test_and_set_16:
1483 BuiltinIndex = 12;
1484 break;
1485
Chris Lattnerdc046542009-05-08 06:58:22 +00001486 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00001487 case Builtin::BI__sync_lock_release_1:
1488 case Builtin::BI__sync_lock_release_2:
1489 case Builtin::BI__sync_lock_release_4:
1490 case Builtin::BI__sync_lock_release_8:
1491 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001492 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00001493 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00001494 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001495 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001496
1497 case Builtin::BI__sync_swap:
1498 case Builtin::BI__sync_swap_1:
1499 case Builtin::BI__sync_swap_2:
1500 case Builtin::BI__sync_swap_4:
1501 case Builtin::BI__sync_swap_8:
1502 case Builtin::BI__sync_swap_16:
1503 BuiltinIndex = 14;
1504 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00001505 }
Mike Stump11289f42009-09-09 15:08:12 +00001506
Chris Lattnerdc046542009-05-08 06:58:22 +00001507 // Now that we know how many fixed arguments we expect, first check that we
1508 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001509 if (TheCall->getNumArgs() < 1+NumFixed) {
1510 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1511 << 0 << 1+NumFixed << TheCall->getNumArgs()
1512 << TheCall->getCallee()->getSourceRange();
1513 return ExprError();
1514 }
Mike Stump11289f42009-09-09 15:08:12 +00001515
Chris Lattner5b9241b2009-05-08 15:36:58 +00001516 // Get the decl for the concrete builtin from this, we can tell what the
1517 // concrete integer type we should convert to is.
1518 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1519 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001520 FunctionDecl *NewBuiltinDecl;
1521 if (NewBuiltinID == BuiltinID)
1522 NewBuiltinDecl = FDecl;
1523 else {
1524 // Perform builtin lookup to avoid redeclaring it.
1525 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1526 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1527 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1528 assert(Res.getFoundDecl());
1529 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
1530 if (NewBuiltinDecl == 0)
1531 return ExprError();
1532 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001533
John McCallcf142162010-08-07 06:22:56 +00001534 // The first argument --- the pointer --- has a fixed type; we
1535 // deduce the types of the rest of the arguments accordingly. Walk
1536 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00001537 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00001538 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00001539
Chris Lattnerdc046542009-05-08 06:58:22 +00001540 // GCC does an implicit conversion to the pointer or integer ValType. This
1541 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00001542 // Initialize the argument.
1543 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1544 ValType, /*consume*/ false);
1545 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00001546 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001547 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001548
Chris Lattnerdc046542009-05-08 06:58:22 +00001549 // Okay, we have something that *can* be converted to the right type. Check
1550 // to see if there is a potentially weird extension going on here. This can
1551 // happen when you do an atomic operation on something like an char* and
1552 // pass in 42. The 42 gets converted to char. This is even more strange
1553 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00001554 // FIXME: Do this check.
John McCallb50451a2011-10-05 07:41:44 +00001555 TheCall->setArg(i+1, Arg.take());
Chris Lattnerdc046542009-05-08 06:58:22 +00001556 }
Mike Stump11289f42009-09-09 15:08:12 +00001557
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001558 ASTContext& Context = this->getASTContext();
1559
1560 // Create a new DeclRefExpr to refer to the new decl.
1561 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1562 Context,
1563 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001564 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001565 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00001566 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001567 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00001568 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001569 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00001570
Chris Lattnerdc046542009-05-08 06:58:22 +00001571 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00001572 // FIXME: This loses syntactic information.
1573 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1574 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1575 CK_BuiltinFnToFnPtr);
John Wiegley01296292011-04-08 18:41:53 +00001576 TheCall->setCallee(PromotedCall.take());
Mike Stump11289f42009-09-09 15:08:12 +00001577
Chandler Carruthbc8cab12010-07-18 07:23:17 +00001578 // Change the result type of the call to match the original value type. This
1579 // is arbitrary, but the codegen for these builtins ins design to handle it
1580 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00001581 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001582
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001583 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00001584}
1585
Chris Lattner6436fb62009-02-18 06:01:06 +00001586/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00001587/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00001588/// Note: It might also make sense to do the UTF-16 conversion here (would
1589/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00001590bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00001591 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00001592 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1593
Douglas Gregorfb65e592011-07-27 05:40:30 +00001594 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00001595 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1596 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00001597 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00001598 }
Mike Stump11289f42009-09-09 15:08:12 +00001599
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001600 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001601 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001602 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001603 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00001604 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001605 UTF16 *ToPtr = &ToBuf[0];
1606
1607 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1608 &ToPtr, ToPtr + NumBytes,
1609 strictConversion);
1610 // Check for conversion failure.
1611 if (Result != conversionOK)
1612 Diag(Arg->getLocStart(),
1613 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1614 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00001615 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001616}
1617
Chris Lattnere202e6a2007-12-20 00:05:45 +00001618/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1619/// Emit an error and return true on failure, return false on success.
Chris Lattner08464942007-12-28 05:29:59 +00001620bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1621 Expr *Fn = TheCall->getCallee();
1622 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00001623 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001624 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001625 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1626 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00001627 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001628 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00001629 return true;
1630 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00001631
1632 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00001633 return Diag(TheCall->getLocEnd(),
1634 diag::err_typecheck_call_too_few_args_at_least)
1635 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00001636 }
1637
John McCall29ad95b2011-08-27 01:09:30 +00001638 // Type-check the first argument normally.
1639 if (checkBuiltinArgument(*this, TheCall, 0))
1640 return true;
1641
Chris Lattnere202e6a2007-12-20 00:05:45 +00001642 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00001643 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00001644 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00001645 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00001646 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00001647 else if (FunctionDecl *FD = getCurFunctionDecl())
1648 isVariadic = FD->isVariadic();
1649 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001650 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00001651
Chris Lattnere202e6a2007-12-20 00:05:45 +00001652 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00001653 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1654 return true;
1655 }
Mike Stump11289f42009-09-09 15:08:12 +00001656
Chris Lattner43be2e62007-12-19 23:59:04 +00001657 // Verify that the second argument to the builtin is the last argument of the
1658 // current function or method.
1659 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00001660 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00001661
Nico Weber9eea7642013-05-24 23:31:57 +00001662 // These are valid if SecondArgIsLastNamedArgument is false after the next
1663 // block.
1664 QualType Type;
1665 SourceLocation ParamLoc;
1666
Anders Carlsson6a8350b2008-02-11 04:20:54 +00001667 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1668 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00001669 // FIXME: This isn't correct for methods (results in bogus warning).
1670 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00001671 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00001672 if (CurBlock)
1673 LastArg = *(CurBlock->TheDecl->param_end()-1);
1674 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00001675 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00001676 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001677 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00001678 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00001679
1680 Type = PV->getType();
1681 ParamLoc = PV->getLocation();
Chris Lattner43be2e62007-12-19 23:59:04 +00001682 }
1683 }
Mike Stump11289f42009-09-09 15:08:12 +00001684
Chris Lattner43be2e62007-12-19 23:59:04 +00001685 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001686 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +00001687 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weber9eea7642013-05-24 23:31:57 +00001688 else if (Type->isReferenceType()) {
1689 Diag(Arg->getLocStart(),
1690 diag::warn_va_start_of_reference_type_is_undefined);
1691 Diag(ParamLoc, diag::note_parameter_type) << Type;
1692 }
1693
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00001694 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00001695 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00001696}
Chris Lattner43be2e62007-12-19 23:59:04 +00001697
Chris Lattner2da14fb2007-12-20 00:26:33 +00001698/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1699/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00001700bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1701 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00001702 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00001703 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00001704 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00001705 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001706 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001707 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00001708 << SourceRange(TheCall->getArg(2)->getLocStart(),
1709 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00001710
John Wiegley01296292011-04-08 18:41:53 +00001711 ExprResult OrigArg0 = TheCall->getArg(0);
1712 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00001713
Chris Lattner2da14fb2007-12-20 00:26:33 +00001714 // Do standard promotions between the two arguments, returning their common
1715 // type.
Chris Lattner08464942007-12-28 05:29:59 +00001716 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00001717 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1718 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00001719
1720 // Make sure any conversions are pushed back into the call; this is
1721 // type safe since unordered compare builtins are declared as "_Bool
1722 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00001723 TheCall->setArg(0, OrigArg0.get());
1724 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00001725
John Wiegley01296292011-04-08 18:41:53 +00001726 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00001727 return false;
1728
Chris Lattner2da14fb2007-12-20 00:26:33 +00001729 // If the common type isn't a real floating type, then the arguments were
1730 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00001731 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00001732 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001733 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00001734 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1735 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00001736
Chris Lattner2da14fb2007-12-20 00:26:33 +00001737 return false;
1738}
1739
Benjamin Kramer634fc102010-02-15 22:42:31 +00001740/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1741/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00001742/// to check everything. We expect the last argument to be a floating point
1743/// value.
1744bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1745 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00001746 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00001747 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00001748 if (TheCall->getNumArgs() > NumArgs)
1749 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001750 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001751 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00001752 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001753 (*(TheCall->arg_end()-1))->getLocEnd());
1754
Benjamin Kramer64aae502010-02-16 10:07:31 +00001755 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00001756
Eli Friedman7e4faac2009-08-31 20:06:00 +00001757 if (OrigArg->isTypeDependent())
1758 return false;
1759
Chris Lattner68784ef2010-05-06 05:50:07 +00001760 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00001761 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00001762 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001763 diag::err_typecheck_call_invalid_unary_fp)
1764 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001765
Chris Lattner68784ef2010-05-06 05:50:07 +00001766 // If this is an implicit conversion from float -> double, remove it.
1767 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1768 Expr *CastArg = Cast->getSubExpr();
1769 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1770 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1771 "promotion from float to double is the only expected cast here");
1772 Cast->setSubExpr(0);
Chris Lattner68784ef2010-05-06 05:50:07 +00001773 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00001774 }
1775 }
1776
Eli Friedman7e4faac2009-08-31 20:06:00 +00001777 return false;
1778}
1779
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001780/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1781// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00001782ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00001783 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001784 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00001785 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00001786 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1787 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001788
Nate Begemana0110022010-06-08 00:16:34 +00001789 // Determine which of the following types of shufflevector we're checking:
1790 // 1) unary, vector mask: (lhs, mask)
1791 // 2) binary, vector mask: (lhs, rhs, mask)
1792 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1793 QualType resType = TheCall->getArg(0)->getType();
1794 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00001795
Douglas Gregorc25f7662009-05-19 22:10:17 +00001796 if (!TheCall->getArg(0)->isTypeDependent() &&
1797 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00001798 QualType LHSType = TheCall->getArg(0)->getType();
1799 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00001800
Craig Topperbaca3892013-07-29 06:47:04 +00001801 if (!LHSType->isVectorType() || !RHSType->isVectorType())
1802 return ExprError(Diag(TheCall->getLocStart(),
1803 diag::err_shufflevector_non_vector)
1804 << SourceRange(TheCall->getArg(0)->getLocStart(),
1805 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00001806
Nate Begemana0110022010-06-08 00:16:34 +00001807 numElements = LHSType->getAs<VectorType>()->getNumElements();
1808 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00001809
Nate Begemana0110022010-06-08 00:16:34 +00001810 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1811 // with mask. If so, verify that RHS is an integer vector type with the
1812 // same number of elts as lhs.
1813 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00001814 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00001815 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00001816 return ExprError(Diag(TheCall->getLocStart(),
1817 diag::err_shufflevector_incompatible_vector)
1818 << SourceRange(TheCall->getArg(1)->getLocStart(),
1819 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00001820 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00001821 return ExprError(Diag(TheCall->getLocStart(),
1822 diag::err_shufflevector_incompatible_vector)
1823 << SourceRange(TheCall->getArg(0)->getLocStart(),
1824 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00001825 } else if (numElements != numResElements) {
1826 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00001827 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001828 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00001829 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001830 }
1831
1832 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00001833 if (TheCall->getArg(i)->isTypeDependent() ||
1834 TheCall->getArg(i)->isValueDependent())
1835 continue;
1836
Nate Begemana0110022010-06-08 00:16:34 +00001837 llvm::APSInt Result(32);
1838 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1839 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00001840 diag::err_shufflevector_nonconstant_argument)
1841 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001842
Craig Topper50ad5b72013-08-03 17:40:38 +00001843 // Allow -1 which will be translated to undef in the IR.
1844 if (Result.isSigned() && Result.isAllOnesValue())
1845 continue;
1846
Chris Lattner7ab824e2008-08-10 02:05:13 +00001847 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001848 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00001849 diag::err_shufflevector_argument_too_large)
1850 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001851 }
1852
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001853 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001854
Chris Lattner7ab824e2008-08-10 02:05:13 +00001855 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001856 exprs.push_back(TheCall->getArg(i));
1857 TheCall->setArg(i, 0);
1858 }
1859
Benjamin Kramerc215e762012-08-24 11:54:20 +00001860 return Owned(new (Context) ShuffleVectorExpr(Context, exprs, resType,
Ted Kremenek5a201952009-02-07 01:47:29 +00001861 TheCall->getCallee()->getLocStart(),
1862 TheCall->getRParenLoc()));
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001863}
Chris Lattner43be2e62007-12-19 23:59:04 +00001864
Hal Finkelc4d7c822013-09-18 03:29:45 +00001865/// SemaConvertVectorExpr - Handle __builtin_convertvector
1866ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
1867 SourceLocation BuiltinLoc,
1868 SourceLocation RParenLoc) {
1869 ExprValueKind VK = VK_RValue;
1870 ExprObjectKind OK = OK_Ordinary;
1871 QualType DstTy = TInfo->getType();
1872 QualType SrcTy = E->getType();
1873
1874 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
1875 return ExprError(Diag(BuiltinLoc,
1876 diag::err_convertvector_non_vector)
1877 << E->getSourceRange());
1878 if (!DstTy->isVectorType() && !DstTy->isDependentType())
1879 return ExprError(Diag(BuiltinLoc,
1880 diag::err_convertvector_non_vector_type));
1881
1882 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
1883 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
1884 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
1885 if (SrcElts != DstElts)
1886 return ExprError(Diag(BuiltinLoc,
1887 diag::err_convertvector_incompatible_vector)
1888 << E->getSourceRange());
1889 }
1890
1891 return Owned(new (Context) ConvertVectorExpr(E, TInfo, DstTy, VK, OK,
1892 BuiltinLoc, RParenLoc));
1893
1894}
1895
Daniel Dunbarb7257262008-07-21 22:59:13 +00001896/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1897// This is declared to take (const void*, ...) and can take two
1898// optional constant int args.
1899bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00001900 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001901
Chris Lattner3b054132008-11-19 05:08:23 +00001902 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001903 return Diag(TheCall->getLocEnd(),
1904 diag::err_typecheck_call_too_many_args_at_most)
1905 << 0 /*function call*/ << 3 << NumArgs
1906 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001907
1908 // Argument 0 is checked for us and the remaining arguments must be
1909 // constant integers.
Chris Lattner3b054132008-11-19 05:08:23 +00001910 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbarb7257262008-07-21 22:59:13 +00001911 Expr *Arg = TheCall->getArg(i);
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00001912
1913 // We can't check the value of a dependent argument.
1914 if (Arg->isTypeDependent() || Arg->isValueDependent())
1915 continue;
1916
Eli Friedman5efba262009-12-04 00:30:06 +00001917 llvm::APSInt Result;
Eric Christopher8d0c6212010-04-17 02:26:23 +00001918 if (SemaBuiltinConstantArg(TheCall, i, Result))
1919 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001920
Daniel Dunbarb7257262008-07-21 22:59:13 +00001921 // FIXME: gcc issues a warning and rewrites these to 0. These
1922 // seems especially odd for the third argument since the default
1923 // is 3.
Chris Lattner3b054132008-11-19 05:08:23 +00001924 if (i == 1) {
Eli Friedman5efba262009-12-04 00:30:06 +00001925 if (Result.getLimitedValue() > 1)
Chris Lattner3b054132008-11-19 05:08:23 +00001926 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattnerd545ad12009-09-23 06:06:36 +00001927 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001928 } else {
Eli Friedman5efba262009-12-04 00:30:06 +00001929 if (Result.getLimitedValue() > 3)
Chris Lattner3b054132008-11-19 05:08:23 +00001930 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattnerd545ad12009-09-23 06:06:36 +00001931 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001932 }
1933 }
1934
Chris Lattner3b054132008-11-19 05:08:23 +00001935 return false;
Daniel Dunbarb7257262008-07-21 22:59:13 +00001936}
1937
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001938/// SemaBuiltinMMPrefetch - Handle _mm_prefetch.
1939// This is declared to take (const char*, int)
1940bool Sema::SemaBuiltinMMPrefetch(CallExpr *TheCall) {
1941 Expr *Arg = TheCall->getArg(1);
1942
1943 // We can't check the value of a dependent argument.
1944 if (Arg->isTypeDependent() || Arg->isValueDependent())
1945 return false;
1946
1947 llvm::APSInt Result;
1948 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1949 return true;
1950
1951 if (Result.getLimitedValue() > 3)
1952 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1953 << "0" << "3" << Arg->getSourceRange();
1954
1955 return false;
1956}
1957
Eric Christopher8d0c6212010-04-17 02:26:23 +00001958/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1959/// TheCall is a constant expression.
1960bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1961 llvm::APSInt &Result) {
1962 Expr *Arg = TheCall->getArg(ArgNum);
1963 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1964 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1965
1966 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1967
1968 if (!Arg->isIntegerConstantExpr(Result, Context))
1969 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00001970 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00001971
Chris Lattnerd545ad12009-09-23 06:06:36 +00001972 return false;
1973}
1974
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00001975/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1976/// int type). This simply type checks that type is one of the defined
1977/// constants (0-3).
Chris Lattner57540c52011-04-15 05:22:18 +00001978// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00001979bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00001980 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00001981
1982 // We can't check the value of a dependent argument.
1983 if (TheCall->getArg(1)->isTypeDependent() ||
1984 TheCall->getArg(1)->isValueDependent())
1985 return false;
1986
Eric Christopher8d0c6212010-04-17 02:26:23 +00001987 // Check constant-ness first.
1988 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1989 return true;
1990
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00001991 Expr *Arg = TheCall->getArg(1);
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00001992 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattner3b054132008-11-19 05:08:23 +00001993 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1994 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00001995 }
1996
1997 return false;
1998}
1999
Eli Friedmanc97d0142009-05-03 06:04:26 +00002000/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002001/// This checks that val is a constant 1.
2002bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
2003 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00002004 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00002005
Eric Christopher8d0c6212010-04-17 02:26:23 +00002006 // TODO: This is less than ideal. Overload this to take a value.
2007 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2008 return true;
2009
2010 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002011 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
2012 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
2013
2014 return false;
2015}
2016
Richard Smithd7293d72013-08-05 18:49:43 +00002017namespace {
2018enum StringLiteralCheckType {
2019 SLCT_NotALiteral,
2020 SLCT_UncheckedLiteral,
2021 SLCT_CheckedLiteral
2022};
2023}
2024
Richard Smith55ce3522012-06-25 20:30:08 +00002025// Determine if an expression is a string literal or constant string.
2026// If this function returns false on the arguments to a function expecting a
2027// format string, we will usually need to emit a warning.
2028// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00002029static StringLiteralCheckType
2030checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
2031 bool HasVAListArg, unsigned format_idx,
2032 unsigned firstDataArg, Sema::FormatStringType Type,
2033 Sema::VariadicCallType CallType, bool InFunctionCall,
2034 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek808829352010-09-09 03:51:39 +00002035 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00002036 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00002037 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002038
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002039 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00002040
Richard Smithd7293d72013-08-05 18:49:43 +00002041 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00002042 // Technically -Wformat-nonliteral does not warn about this case.
2043 // The behavior of printf and friends in this case is implementation
2044 // dependent. Ideally if the format string cannot be null then
2045 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00002046 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00002047
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002048 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00002049 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002050 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00002051 // The expression is a literal if both sub-expressions were, and it was
2052 // completely checked only if both sub-expressions were checked.
2053 const AbstractConditionalOperator *C =
2054 cast<AbstractConditionalOperator>(E);
2055 StringLiteralCheckType Left =
Richard Smithd7293d72013-08-05 18:49:43 +00002056 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002057 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002058 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002059 if (Left == SLCT_NotALiteral)
2060 return SLCT_NotALiteral;
2061 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00002062 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002063 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002064 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002065 return Left < Right ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002066 }
2067
2068 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00002069 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2070 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002071 }
2072
John McCallc07a0c72011-02-17 10:25:35 +00002073 case Stmt::OpaqueValueExprClass:
2074 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2075 E = src;
2076 goto tryAgain;
2077 }
Richard Smith55ce3522012-06-25 20:30:08 +00002078 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00002079
Ted Kremeneka8890832011-02-24 23:03:04 +00002080 case Stmt::PredefinedExprClass:
2081 // While __func__, etc., are technically not string literals, they
2082 // cannot contain format specifiers and thus are not a security
2083 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00002084 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00002085
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002086 case Stmt::DeclRefExprClass: {
2087 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002088
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002089 // As an exception, do not flag errors for variables binding to
2090 // const string literals.
2091 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2092 bool isConstant = false;
2093 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002094
Richard Smithd7293d72013-08-05 18:49:43 +00002095 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2096 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00002097 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00002098 isConstant = T.isConstant(S.Context) &&
2099 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00002100 } else if (T->isObjCObjectPointerType()) {
2101 // In ObjC, there is usually no "const ObjectPointer" type,
2102 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00002103 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002104 }
Mike Stump11289f42009-09-09 15:08:12 +00002105
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002106 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002107 if (const Expr *Init = VD->getAnyInitializer()) {
2108 // Look through initializers like const char c[] = { "foo" }
2109 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2110 if (InitList->isStringLiteralInit())
2111 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2112 }
Richard Smithd7293d72013-08-05 18:49:43 +00002113 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002114 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002115 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002116 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002117 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002118 }
Mike Stump11289f42009-09-09 15:08:12 +00002119
Anders Carlssonb012ca92009-06-28 19:55:58 +00002120 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2121 // special check to see if the format string is a function parameter
2122 // of the function calling the printf function. If the function
2123 // has an attribute indicating it is a printf-like function, then we
2124 // should suppress warnings concerning non-literals being used in a call
2125 // to a vprintf function. For example:
2126 //
2127 // void
2128 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2129 // va_list ap;
2130 // va_start(ap, fmt);
2131 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2132 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00002133 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002134 if (HasVAListArg) {
2135 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2136 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2137 int PVIndex = PV->getFunctionScopeIndex() + 1;
2138 for (specific_attr_iterator<FormatAttr>
2139 i = ND->specific_attr_begin<FormatAttr>(),
2140 e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) {
2141 FormatAttr *PVFormat = *i;
2142 // adjust for implicit parameter
2143 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2144 if (MD->isInstance())
2145 ++PVIndex;
2146 // We also check if the formats are compatible.
2147 // We can't pass a 'scanf' string to a 'printf' function.
2148 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00002149 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00002150 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002151 }
2152 }
2153 }
2154 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002155 }
Mike Stump11289f42009-09-09 15:08:12 +00002156
Richard Smith55ce3522012-06-25 20:30:08 +00002157 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002158 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002159
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002160 case Stmt::CallExprClass:
2161 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002162 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002163 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2164 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2165 unsigned ArgIndex = FA->getFormatIdx();
2166 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2167 if (MD->isInstance())
2168 --ArgIndex;
2169 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00002170
Richard Smithd7293d72013-08-05 18:49:43 +00002171 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002172 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002173 Type, CallType, InFunctionCall,
2174 CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002175 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2176 unsigned BuiltinID = FD->getBuiltinID();
2177 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2178 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2179 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00002180 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002181 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002182 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002183 InFunctionCall, CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002184 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002185 }
2186 }
Mike Stump11289f42009-09-09 15:08:12 +00002187
Richard Smith55ce3522012-06-25 20:30:08 +00002188 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002189 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002190 case Stmt::ObjCStringLiteralClass:
2191 case Stmt::StringLiteralClass: {
2192 const StringLiteral *StrE = NULL;
Mike Stump11289f42009-09-09 15:08:12 +00002193
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002194 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002195 StrE = ObjCFExpr->getString();
2196 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002197 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002198
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002199 if (StrE) {
Richard Smithd7293d72013-08-05 18:49:43 +00002200 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2201 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002202 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002203 }
Mike Stump11289f42009-09-09 15:08:12 +00002204
Richard Smith55ce3522012-06-25 20:30:08 +00002205 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002206 }
Mike Stump11289f42009-09-09 15:08:12 +00002207
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002208 default:
Richard Smith55ce3522012-06-25 20:30:08 +00002209 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002210 }
2211}
2212
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002213Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00002214 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002215 .Case("scanf", FST_Scanf)
2216 .Cases("printf", "printf0", FST_Printf)
2217 .Cases("NSString", "CFString", FST_NSString)
2218 .Case("strftime", FST_Strftime)
2219 .Case("strfmon", FST_Strfmon)
2220 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
2221 .Default(FST_Unknown);
2222}
2223
Jordan Rose3e0ec582012-07-19 18:10:23 +00002224/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00002225/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002226/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002227bool Sema::CheckFormatArguments(const FormatAttr *Format,
2228 ArrayRef<const Expr *> Args,
2229 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002230 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002231 SourceLocation Loc, SourceRange Range,
2232 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00002233 FormatStringInfo FSI;
2234 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002235 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00002236 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00002237 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002238 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002239}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00002240
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002241bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002242 bool HasVAListArg, unsigned format_idx,
2243 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002244 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002245 SourceLocation Loc, SourceRange Range,
2246 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00002247 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002248 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002249 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00002250 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002251 }
Mike Stump11289f42009-09-09 15:08:12 +00002252
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002253 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002254
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002255 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00002256 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002257 // Dynamically generated format strings are difficult to
2258 // automatically vet at compile time. Requiring that format strings
2259 // are string literals: (1) permits the checking of format strings by
2260 // the compiler and thereby (2) can practically remove the source of
2261 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00002262
Mike Stump11289f42009-09-09 15:08:12 +00002263 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00002264 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00002265 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00002266 // the same format string checking logic for both ObjC and C strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002267 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00002268 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2269 format_idx, firstDataArg, Type, CallType,
2270 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002271 if (CT != SLCT_NotALiteral)
2272 // Literal format string found, check done!
2273 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00002274
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002275 // Strftime is particular as it always uses a single 'time' argument,
2276 // so it is safe to pass a non-literal string.
2277 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00002278 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002279
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002280 // Do not emit diag when the string param is a macro expansion and the
2281 // format is either NSString or CFString. This is a hack to prevent
2282 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2283 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupas2b7da832012-05-04 21:08:08 +00002284 if (Type == FST_NSString &&
2285 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith55ce3522012-06-25 20:30:08 +00002286 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002287
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002288 // If there are no arguments specified, warn with -Wformat-security, otherwise
2289 // warn only with -Wformat-nonliteral.
Eli Friedman0e5d6772013-06-18 18:10:01 +00002290 if (Args.size() == firstDataArg)
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002291 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002292 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002293 << OrigFormatExpr->getSourceRange();
2294 else
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002295 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002296 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002297 << OrigFormatExpr->getSourceRange();
Richard Smith55ce3522012-06-25 20:30:08 +00002298 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002299}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002300
Ted Kremenekab278de2010-01-28 23:39:18 +00002301namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00002302class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2303protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00002304 Sema &S;
2305 const StringLiteral *FExpr;
2306 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002307 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00002308 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00002309 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00002310 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002311 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00002312 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00002313 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00002314 bool usesPositionalArgs;
2315 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00002316 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00002317 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00002318 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002319public:
Ted Kremenek02087932010-07-16 02:11:22 +00002320 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002321 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002322 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002323 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002324 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002325 Sema::VariadicCallType callType,
2326 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremenekab278de2010-01-28 23:39:18 +00002327 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002328 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2329 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002330 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00002331 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00002332 inFunctionCall(inFunctionCall), CallType(callType),
2333 CheckedVarArgs(CheckedVarArgs) {
2334 CoveredArgs.resize(numDataArgs);
2335 CoveredArgs.reset();
2336 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002337
Ted Kremenek019d2242010-01-29 01:50:07 +00002338 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002339
Ted Kremenek02087932010-07-16 02:11:22 +00002340 void HandleIncompleteSpecifier(const char *startSpecifier,
2341 unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002342
Jordan Rose92303592012-09-08 04:00:03 +00002343 void HandleInvalidLengthModifier(
2344 const analyze_format_string::FormatSpecifier &FS,
2345 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00002346 const char *startSpecifier, unsigned specifierLen, unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00002347
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002348 void HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00002349 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002350 const char *startSpecifier, unsigned specifierLen);
2351
2352 void HandleNonStandardConversionSpecifier(
2353 const analyze_format_string::ConversionSpecifier &CS,
2354 const char *startSpecifier, unsigned specifierLen);
2355
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002356 virtual void HandlePosition(const char *startPos, unsigned posLen);
2357
Ted Kremenekd1668192010-02-27 01:41:03 +00002358 virtual void HandleInvalidPosition(const char *startSpecifier,
2359 unsigned specifierLen,
Ted Kremenek02087932010-07-16 02:11:22 +00002360 analyze_format_string::PositionContext p);
Ted Kremenekd1668192010-02-27 01:41:03 +00002361
2362 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
2363
Ted Kremenekab278de2010-01-28 23:39:18 +00002364 void HandleNullChar(const char *nullCharacter);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002365
Richard Trieu03cf7b72011-10-28 00:41:25 +00002366 template <typename Range>
2367 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2368 const Expr *ArgumentExpr,
2369 PartialDiagnostic PDiag,
2370 SourceLocation StringLoc,
2371 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002372 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002373
Ted Kremenek02087932010-07-16 02:11:22 +00002374protected:
Ted Kremenekce815422010-07-19 21:25:57 +00002375 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2376 const char *startSpec,
2377 unsigned specifierLen,
2378 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002379
2380 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2381 const char *startSpec,
2382 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00002383
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002384 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00002385 CharSourceRange getSpecifierRange(const char *startSpecifier,
2386 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00002387 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002388
Ted Kremenek5739de72010-01-29 01:06:55 +00002389 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002390
2391 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2392 const analyze_format_string::ConversionSpecifier &CS,
2393 const char *startSpecifier, unsigned specifierLen,
2394 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002395
2396 template <typename Range>
2397 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2398 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002399 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002400
2401 void CheckPositionalAndNonpositionalArgs(
2402 const analyze_format_string::FormatSpecifier *FS);
Ted Kremenekab278de2010-01-28 23:39:18 +00002403};
2404}
2405
Ted Kremenek02087932010-07-16 02:11:22 +00002406SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00002407 return OrigFormatExpr->getSourceRange();
2408}
2409
Ted Kremenek02087932010-07-16 02:11:22 +00002410CharSourceRange CheckFormatHandler::
2411getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00002412 SourceLocation Start = getLocationOfByte(startSpecifier);
2413 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2414
2415 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002416 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00002417
2418 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002419}
2420
Ted Kremenek02087932010-07-16 02:11:22 +00002421SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002422 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00002423}
2424
Ted Kremenek02087932010-07-16 02:11:22 +00002425void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2426 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00002427 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2428 getLocationOfByte(startSpecifier),
2429 /*IsStringLocation*/true,
2430 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00002431}
2432
Jordan Rose92303592012-09-08 04:00:03 +00002433void CheckFormatHandler::HandleInvalidLengthModifier(
2434 const analyze_format_string::FormatSpecifier &FS,
2435 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00002436 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00002437 using namespace analyze_format_string;
2438
2439 const LengthModifier &LM = FS.getLengthModifier();
2440 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2441
2442 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002443 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00002444 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002445 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002446 getLocationOfByte(LM.getStart()),
2447 /*IsStringLocation*/true,
2448 getSpecifierRange(startSpecifier, specifierLen));
2449
2450 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2451 << FixedLM->toString()
2452 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2453
2454 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002455 FixItHint Hint;
2456 if (DiagID == diag::warn_format_nonsensical_length)
2457 Hint = FixItHint::CreateRemoval(LMRange);
2458
2459 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002460 getLocationOfByte(LM.getStart()),
2461 /*IsStringLocation*/true,
2462 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00002463 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00002464 }
2465}
2466
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002467void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00002468 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002469 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002470 using namespace analyze_format_string;
2471
2472 const LengthModifier &LM = FS.getLengthModifier();
2473 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2474
2475 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002476 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00002477 if (FixedLM) {
2478 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2479 << LM.toString() << 0,
2480 getLocationOfByte(LM.getStart()),
2481 /*IsStringLocation*/true,
2482 getSpecifierRange(startSpecifier, specifierLen));
2483
2484 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2485 << FixedLM->toString()
2486 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2487
2488 } else {
2489 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2490 << LM.toString() << 0,
2491 getLocationOfByte(LM.getStart()),
2492 /*IsStringLocation*/true,
2493 getSpecifierRange(startSpecifier, specifierLen));
2494 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002495}
2496
2497void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2498 const analyze_format_string::ConversionSpecifier &CS,
2499 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00002500 using namespace analyze_format_string;
2501
2502 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00002503 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00002504 if (FixedCS) {
2505 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2506 << CS.toString() << /*conversion specifier*/1,
2507 getLocationOfByte(CS.getStart()),
2508 /*IsStringLocation*/true,
2509 getSpecifierRange(startSpecifier, specifierLen));
2510
2511 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2512 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2513 << FixedCS->toString()
2514 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2515 } else {
2516 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2517 << CS.toString() << /*conversion specifier*/1,
2518 getLocationOfByte(CS.getStart()),
2519 /*IsStringLocation*/true,
2520 getSpecifierRange(startSpecifier, specifierLen));
2521 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002522}
2523
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002524void CheckFormatHandler::HandlePosition(const char *startPos,
2525 unsigned posLen) {
2526 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2527 getLocationOfByte(startPos),
2528 /*IsStringLocation*/true,
2529 getSpecifierRange(startPos, posLen));
2530}
2531
Ted Kremenekd1668192010-02-27 01:41:03 +00002532void
Ted Kremenek02087932010-07-16 02:11:22 +00002533CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2534 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002535 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2536 << (unsigned) p,
2537 getLocationOfByte(startPos), /*IsStringLocation*/true,
2538 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00002539}
2540
Ted Kremenek02087932010-07-16 02:11:22 +00002541void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00002542 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002543 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2544 getLocationOfByte(startPos),
2545 /*IsStringLocation*/true,
2546 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00002547}
2548
Ted Kremenek02087932010-07-16 02:11:22 +00002549void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002550 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00002551 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002552 EmitFormatDiagnostic(
2553 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2554 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2555 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00002556 }
Ted Kremenek02087932010-07-16 02:11:22 +00002557}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002558
Jordan Rose58bbe422012-07-19 18:10:08 +00002559// Note that this may return NULL if there was an error parsing or building
2560// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00002561const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002562 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00002563}
2564
2565void CheckFormatHandler::DoneProcessing() {
2566 // Does the number of data arguments exceed the number of
2567 // format conversions in the format string?
2568 if (!HasVAListArg) {
2569 // Find any arguments that weren't covered.
2570 CoveredArgs.flip();
2571 signed notCoveredArg = CoveredArgs.find_first();
2572 if (notCoveredArg >= 0) {
2573 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose58bbe422012-07-19 18:10:08 +00002574 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2575 SourceLocation Loc = E->getLocStart();
2576 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2577 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2578 Loc, /*IsStringLocation*/false,
2579 getFormatStringRange());
2580 }
Bob Wilson23cd4342012-05-03 19:47:19 +00002581 }
Ted Kremenek02087932010-07-16 02:11:22 +00002582 }
2583 }
2584}
2585
Ted Kremenekce815422010-07-19 21:25:57 +00002586bool
2587CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2588 SourceLocation Loc,
2589 const char *startSpec,
2590 unsigned specifierLen,
2591 const char *csStart,
2592 unsigned csLen) {
2593
2594 bool keepGoing = true;
2595 if (argIndex < NumDataArgs) {
2596 // Consider the argument coverered, even though the specifier doesn't
2597 // make sense.
2598 CoveredArgs.set(argIndex);
2599 }
2600 else {
2601 // If argIndex exceeds the number of data arguments we
2602 // don't issue a warning because that is just a cascade of warnings (and
2603 // they may have intended '%%' anyway). We don't want to continue processing
2604 // the format string after this point, however, as we will like just get
2605 // gibberish when trying to match arguments.
2606 keepGoing = false;
2607 }
2608
Richard Trieu03cf7b72011-10-28 00:41:25 +00002609 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2610 << StringRef(csStart, csLen),
2611 Loc, /*IsStringLocation*/true,
2612 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekce815422010-07-19 21:25:57 +00002613
2614 return keepGoing;
2615}
2616
Richard Trieu03cf7b72011-10-28 00:41:25 +00002617void
2618CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2619 const char *startSpec,
2620 unsigned specifierLen) {
2621 EmitFormatDiagnostic(
2622 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2623 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2624}
2625
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002626bool
2627CheckFormatHandler::CheckNumArgs(
2628 const analyze_format_string::FormatSpecifier &FS,
2629 const analyze_format_string::ConversionSpecifier &CS,
2630 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2631
2632 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002633 PartialDiagnostic PDiag = FS.usesPositionalArg()
2634 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2635 << (argIndex+1) << NumDataArgs)
2636 : S.PDiag(diag::warn_printf_insufficient_data_args);
2637 EmitFormatDiagnostic(
2638 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2639 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002640 return false;
2641 }
2642 return true;
2643}
2644
Richard Trieu03cf7b72011-10-28 00:41:25 +00002645template<typename Range>
2646void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2647 SourceLocation Loc,
2648 bool IsStringLocation,
2649 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00002650 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002651 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00002652 Loc, IsStringLocation, StringRange, FixIt);
2653}
2654
2655/// \brief If the format string is not within the funcion call, emit a note
2656/// so that the function call and string are in diagnostic messages.
2657///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002658/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00002659/// call and only one diagnostic message will be produced. Otherwise, an
2660/// extra note will be emitted pointing to location of the format string.
2661///
2662/// \param ArgumentExpr the expression that is passed as the format string
2663/// argument in the function call. Used for getting locations when two
2664/// diagnostics are emitted.
2665///
2666/// \param PDiag the callee should already have provided any strings for the
2667/// diagnostic message. This function only adds locations and fixits
2668/// to diagnostics.
2669///
2670/// \param Loc primary location for diagnostic. If two diagnostics are
2671/// required, one will be at Loc and a new SourceLocation will be created for
2672/// the other one.
2673///
2674/// \param IsStringLocation if true, Loc points to the format string should be
2675/// used for the note. Otherwise, Loc points to the argument list and will
2676/// be used with PDiag.
2677///
2678/// \param StringRange some or all of the string to highlight. This is
2679/// templated so it can accept either a CharSourceRange or a SourceRange.
2680///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002681/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002682template<typename Range>
2683void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2684 const Expr *ArgumentExpr,
2685 PartialDiagnostic PDiag,
2686 SourceLocation Loc,
2687 bool IsStringLocation,
2688 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00002689 ArrayRef<FixItHint> FixIt) {
2690 if (InFunctionCall) {
2691 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2692 D << StringRange;
2693 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2694 I != E; ++I) {
2695 D << *I;
2696 }
2697 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002698 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2699 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00002700
2701 const Sema::SemaDiagnosticBuilder &Note =
2702 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2703 diag::note_format_string_defined);
2704
2705 Note << StringRange;
2706 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2707 I != E; ++I) {
2708 Note << *I;
2709 }
Richard Trieu03cf7b72011-10-28 00:41:25 +00002710 }
2711}
2712
Ted Kremenek02087932010-07-16 02:11:22 +00002713//===--- CHECK: Printf format string checking ------------------------------===//
2714
2715namespace {
2716class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002717 bool ObjCContext;
Ted Kremenek02087932010-07-16 02:11:22 +00002718public:
2719 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2720 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002721 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00002722 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002723 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002724 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002725 Sema::VariadicCallType CallType,
2726 llvm::SmallBitVector &CheckedVarArgs)
2727 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2728 numDataArgs, beg, hasVAListArg, Args,
2729 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
2730 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00002731 {}
2732
Ted Kremenek02087932010-07-16 02:11:22 +00002733
2734 bool HandleInvalidPrintfConversionSpecifier(
2735 const analyze_printf::PrintfSpecifier &FS,
2736 const char *startSpecifier,
2737 unsigned specifierLen);
2738
2739 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2740 const char *startSpecifier,
2741 unsigned specifierLen);
Richard Smith55ce3522012-06-25 20:30:08 +00002742 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2743 const char *StartSpecifier,
2744 unsigned SpecifierLen,
2745 const Expr *E);
2746
Ted Kremenek02087932010-07-16 02:11:22 +00002747 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2748 const char *startSpecifier, unsigned specifierLen);
2749 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2750 const analyze_printf::OptionalAmount &Amt,
2751 unsigned type,
2752 const char *startSpecifier, unsigned specifierLen);
2753 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2754 const analyze_printf::OptionalFlag &flag,
2755 const char *startSpecifier, unsigned specifierLen);
2756 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2757 const analyze_printf::OptionalFlag &ignoredFlag,
2758 const analyze_printf::OptionalFlag &flag,
2759 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002760 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith55ce3522012-06-25 20:30:08 +00002761 const Expr *E, const CharSourceRange &CSR);
2762
Ted Kremenek02087932010-07-16 02:11:22 +00002763};
2764}
2765
2766bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2767 const analyze_printf::PrintfSpecifier &FS,
2768 const char *startSpecifier,
2769 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002770 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00002771 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00002772
Ted Kremenekce815422010-07-19 21:25:57 +00002773 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2774 getLocationOfByte(CS.getStart()),
2775 startSpecifier, specifierLen,
2776 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00002777}
2778
Ted Kremenek02087932010-07-16 02:11:22 +00002779bool CheckPrintfHandler::HandleAmount(
2780 const analyze_format_string::OptionalAmount &Amt,
2781 unsigned k, const char *startSpecifier,
2782 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00002783
2784 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00002785 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00002786 unsigned argIndex = Amt.getArgIndex();
2787 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002788 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2789 << k,
2790 getLocationOfByte(Amt.getStart()),
2791 /*IsStringLocation*/true,
2792 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00002793 // Don't do any more checking. We will just emit
2794 // spurious errors.
2795 return false;
2796 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002797
Ted Kremenek5739de72010-01-29 01:06:55 +00002798 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00002799 // Although not in conformance with C99, we also allow the argument to be
2800 // an 'unsigned int' as that is a reasonably safe case. GCC also
2801 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00002802 CoveredArgs.set(argIndex);
2803 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00002804 if (!Arg)
2805 return false;
2806
Ted Kremenek5739de72010-01-29 01:06:55 +00002807 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002808
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002809 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
2810 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002811
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002812 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002813 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002814 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00002815 << T << Arg->getSourceRange(),
2816 getLocationOfByte(Amt.getStart()),
2817 /*IsStringLocation*/true,
2818 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00002819 // Don't do any more checking. We will just emit
2820 // spurious errors.
2821 return false;
2822 }
2823 }
2824 }
2825 return true;
2826}
Ted Kremenek5739de72010-01-29 01:06:55 +00002827
Tom Careb49ec692010-06-17 19:00:27 +00002828void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00002829 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002830 const analyze_printf::OptionalAmount &Amt,
2831 unsigned type,
2832 const char *startSpecifier,
2833 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002834 const analyze_printf::PrintfConversionSpecifier &CS =
2835 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00002836
Richard Trieu03cf7b72011-10-28 00:41:25 +00002837 FixItHint fixit =
2838 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2839 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2840 Amt.getConstantLength()))
2841 : FixItHint();
2842
2843 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2844 << type << CS.toString(),
2845 getLocationOfByte(Amt.getStart()),
2846 /*IsStringLocation*/true,
2847 getSpecifierRange(startSpecifier, specifierLen),
2848 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00002849}
2850
Ted Kremenek02087932010-07-16 02:11:22 +00002851void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002852 const analyze_printf::OptionalFlag &flag,
2853 const char *startSpecifier,
2854 unsigned specifierLen) {
2855 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002856 const analyze_printf::PrintfConversionSpecifier &CS =
2857 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00002858 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2859 << flag.toString() << CS.toString(),
2860 getLocationOfByte(flag.getPosition()),
2861 /*IsStringLocation*/true,
2862 getSpecifierRange(startSpecifier, specifierLen),
2863 FixItHint::CreateRemoval(
2864 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00002865}
2866
2867void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00002868 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002869 const analyze_printf::OptionalFlag &ignoredFlag,
2870 const analyze_printf::OptionalFlag &flag,
2871 const char *startSpecifier,
2872 unsigned specifierLen) {
2873 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002874 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2875 << ignoredFlag.toString() << flag.toString(),
2876 getLocationOfByte(ignoredFlag.getPosition()),
2877 /*IsStringLocation*/true,
2878 getSpecifierRange(startSpecifier, specifierLen),
2879 FixItHint::CreateRemoval(
2880 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00002881}
2882
Richard Smith55ce3522012-06-25 20:30:08 +00002883// Determines if the specified is a C++ class or struct containing
2884// a member with the specified name and kind (e.g. a CXXMethodDecl named
2885// "c_str()").
2886template<typename MemberKind>
2887static llvm::SmallPtrSet<MemberKind*, 1>
2888CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2889 const RecordType *RT = Ty->getAs<RecordType>();
2890 llvm::SmallPtrSet<MemberKind*, 1> Results;
2891
2892 if (!RT)
2893 return Results;
2894 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
2895 if (!RD)
2896 return Results;
2897
2898 LookupResult R(S, &S.PP.getIdentifierTable().get(Name), SourceLocation(),
2899 Sema::LookupMemberName);
2900
2901 // We just need to include all members of the right kind turned up by the
2902 // filter, at this point.
2903 if (S.LookupQualifiedName(R, RT->getDecl()))
2904 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2905 NamedDecl *decl = (*I)->getUnderlyingDecl();
2906 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
2907 Results.insert(FK);
2908 }
2909 return Results;
2910}
2911
2912// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002913// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00002914// Returns true when a c_str() conversion method is found.
2915bool CheckPrintfHandler::checkForCStrMembers(
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002916 const analyze_printf::ArgType &AT, const Expr *E,
Richard Smith55ce3522012-06-25 20:30:08 +00002917 const CharSourceRange &CSR) {
2918 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2919
2920 MethodSet Results =
2921 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
2922
2923 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2924 MI != ME; ++MI) {
2925 const CXXMethodDecl *Method = *MI;
2926 if (Method->getNumParams() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00002927 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00002928 // FIXME: Suggest parens if the expression needs them.
2929 SourceLocation EndLoc =
2930 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd());
2931 S.Diag(E->getLocStart(), diag::note_printf_c_str)
2932 << "c_str()"
2933 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
2934 return true;
2935 }
2936 }
2937
2938 return false;
2939}
2940
Ted Kremenekab278de2010-01-28 23:39:18 +00002941bool
Ted Kremenek02087932010-07-16 02:11:22 +00002942CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00002943 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00002944 const char *startSpecifier,
2945 unsigned specifierLen) {
2946
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002947 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00002948 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002949 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00002950
Ted Kremenek6cd69422010-07-19 22:01:06 +00002951 if (FS.consumesDataArgument()) {
2952 if (atFirstArg) {
2953 atFirstArg = false;
2954 usesPositionalArgs = FS.usesPositionalArg();
2955 }
2956 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002957 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2958 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00002959 return false;
2960 }
Ted Kremenek5739de72010-01-29 01:06:55 +00002961 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002962
Ted Kremenekd1668192010-02-27 01:41:03 +00002963 // First check if the field width, precision, and conversion specifier
2964 // have matching data arguments.
2965 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2966 startSpecifier, specifierLen)) {
2967 return false;
2968 }
2969
2970 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2971 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00002972 return false;
2973 }
2974
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002975 if (!CS.consumesDataArgument()) {
2976 // FIXME: Technically specifying a precision or field width here
2977 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00002978 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002979 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002980
Ted Kremenek4a49d982010-02-26 19:18:41 +00002981 // Consume the argument.
2982 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00002983 if (argIndex < NumDataArgs) {
2984 // The check to see if the argIndex is valid will come later.
2985 // We set the bit here because we may exit early from this
2986 // function if we encounter some other error.
2987 CoveredArgs.set(argIndex);
2988 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00002989
2990 // Check for using an Objective-C specific conversion specifier
2991 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002992 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00002993 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2994 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00002995 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002996
Tom Careb49ec692010-06-17 19:00:27 +00002997 // Check for invalid use of field width
2998 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00002999 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00003000 startSpecifier, specifierLen);
3001 }
3002
3003 // Check for invalid use of precision
3004 if (!FS.hasValidPrecision()) {
3005 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
3006 startSpecifier, specifierLen);
3007 }
3008
3009 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00003010 if (!FS.hasValidThousandsGroupingPrefix())
3011 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003012 if (!FS.hasValidLeadingZeros())
3013 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
3014 if (!FS.hasValidPlusPrefix())
3015 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00003016 if (!FS.hasValidSpacePrefix())
3017 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003018 if (!FS.hasValidAlternativeForm())
3019 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3020 if (!FS.hasValidLeftJustified())
3021 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3022
3023 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00003024 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3025 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3026 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003027 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3028 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3029 startSpecifier, specifierLen);
3030
3031 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003032 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003033 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3034 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003035 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003036 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003037 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003038 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3039 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00003040
Jordan Rose92303592012-09-08 04:00:03 +00003041 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3042 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3043
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003044 // The remaining checks depend on the data arguments.
3045 if (HasVAListArg)
3046 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003047
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003048 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003049 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003050
Jordan Rose58bbe422012-07-19 18:10:08 +00003051 const Expr *Arg = getDataArg(argIndex);
3052 if (!Arg)
3053 return true;
3054
3055 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00003056}
3057
Jordan Roseaee34382012-09-05 22:56:26 +00003058static bool requiresParensToAddCast(const Expr *E) {
3059 // FIXME: We should have a general way to reason about operator
3060 // precedence and whether parens are actually needed here.
3061 // Take care of a few common cases where they aren't.
3062 const Expr *Inside = E->IgnoreImpCasts();
3063 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3064 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3065
3066 switch (Inside->getStmtClass()) {
3067 case Stmt::ArraySubscriptExprClass:
3068 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003069 case Stmt::CharacterLiteralClass:
3070 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003071 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003072 case Stmt::FloatingLiteralClass:
3073 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003074 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003075 case Stmt::ObjCArrayLiteralClass:
3076 case Stmt::ObjCBoolLiteralExprClass:
3077 case Stmt::ObjCBoxedExprClass:
3078 case Stmt::ObjCDictionaryLiteralClass:
3079 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003080 case Stmt::ObjCIvarRefExprClass:
3081 case Stmt::ObjCMessageExprClass:
3082 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003083 case Stmt::ObjCStringLiteralClass:
3084 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003085 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003086 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003087 case Stmt::UnaryOperatorClass:
3088 return false;
3089 default:
3090 return true;
3091 }
3092}
3093
Richard Smith55ce3522012-06-25 20:30:08 +00003094bool
3095CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3096 const char *StartSpecifier,
3097 unsigned SpecifierLen,
3098 const Expr *E) {
3099 using namespace analyze_format_string;
3100 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003101 // Now type check the data expression that matches the
3102 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003103 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3104 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00003105 if (!AT.isValid())
3106 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00003107
Jordan Rose598ec092012-12-05 18:44:40 +00003108 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00003109 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3110 ExprTy = TET->getUnderlyingExpr()->getType();
3111 }
3112
Jordan Rose598ec092012-12-05 18:44:40 +00003113 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003114 return true;
Jordan Rose98709982012-06-04 22:48:57 +00003115
Jordan Rose22b74712012-09-05 22:56:19 +00003116 // Look through argument promotions for our error message's reported type.
3117 // This includes the integral and floating promotions, but excludes array
3118 // and function pointer decay; seeing that an argument intended to be a
3119 // string has type 'char [6]' is probably more confusing than 'char *'.
3120 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3121 if (ICE->getCastKind() == CK_IntegralCast ||
3122 ICE->getCastKind() == CK_FloatingCast) {
3123 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00003124 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00003125
3126 // Check if we didn't match because of an implicit cast from a 'char'
3127 // or 'short' to an 'int'. This is done because printf is a varargs
3128 // function.
3129 if (ICE->getType() == S.Context.IntTy ||
3130 ICE->getType() == S.Context.UnsignedIntTy) {
3131 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00003132 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003133 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00003134 }
Jordan Rose98709982012-06-04 22:48:57 +00003135 }
Jordan Rose598ec092012-12-05 18:44:40 +00003136 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3137 // Special case for 'a', which has type 'int' in C.
3138 // Note, however, that we do /not/ want to treat multibyte constants like
3139 // 'MooV' as characters! This form is deprecated but still exists.
3140 if (ExprTy == S.Context.IntTy)
3141 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3142 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00003143 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003144
Jordan Rose0e5badd2012-12-05 18:44:49 +00003145 // %C in an Objective-C context prints a unichar, not a wchar_t.
3146 // If the argument is an integer of some kind, believe the %C and suggest
3147 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00003148 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003149 if (ObjCContext &&
3150 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3151 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3152 !ExprTy->isCharType()) {
3153 // 'unichar' is defined as a typedef of unsigned short, but we should
3154 // prefer using the typedef if it is visible.
3155 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00003156
3157 // While we are here, check if the value is an IntegerLiteral that happens
3158 // to be within the valid range.
3159 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3160 const llvm::APInt &V = IL->getValue();
3161 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3162 return true;
3163 }
3164
Jordan Rose0e5badd2012-12-05 18:44:49 +00003165 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3166 Sema::LookupOrdinaryName);
3167 if (S.LookupName(Result, S.getCurScope())) {
3168 NamedDecl *ND = Result.getFoundDecl();
3169 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3170 if (TD->getUnderlyingType() == IntendedTy)
3171 IntendedTy = S.Context.getTypedefType(TD);
3172 }
3173 }
3174 }
3175
3176 // Special-case some of Darwin's platform-independence types by suggesting
3177 // casts to primitive types that are known to be large enough.
3178 bool ShouldNotPrintDirectly = false;
Jordan Roseaee34382012-09-05 22:56:26 +00003179 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003180 // Use a 'while' to peel off layers of typedefs.
3181 QualType TyTy = IntendedTy;
3182 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
Jordan Roseaee34382012-09-05 22:56:26 +00003183 StringRef Name = UserTy->getDecl()->getName();
Jordan Rose0e5badd2012-12-05 18:44:49 +00003184 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Jordan Roseaee34382012-09-05 22:56:26 +00003185 .Case("NSInteger", S.Context.LongTy)
3186 .Case("NSUInteger", S.Context.UnsignedLongTy)
3187 .Case("SInt32", S.Context.IntTy)
3188 .Case("UInt32", S.Context.UnsignedIntTy)
Jordan Rose0e5badd2012-12-05 18:44:49 +00003189 .Default(QualType());
3190
3191 if (!CastTy.isNull()) {
3192 ShouldNotPrintDirectly = true;
3193 IntendedTy = CastTy;
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003194 break;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003195 }
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003196 TyTy = UserTy->desugar();
Jordan Roseaee34382012-09-05 22:56:26 +00003197 }
3198 }
3199
Jordan Rose22b74712012-09-05 22:56:19 +00003200 // We may be able to offer a FixItHint if it is a supported type.
3201 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00003202 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00003203 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003204
Jordan Rose22b74712012-09-05 22:56:19 +00003205 if (success) {
3206 // Get the fix string from the fixed format specifier
3207 SmallString<16> buf;
3208 llvm::raw_svector_ostream os(buf);
3209 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003210
Jordan Roseaee34382012-09-05 22:56:26 +00003211 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3212
Jordan Rose0e5badd2012-12-05 18:44:49 +00003213 if (IntendedTy == ExprTy) {
3214 // In this case, the specifier is wrong and should be changed to match
3215 // the argument.
3216 EmitFormatDiagnostic(
3217 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3218 << AT.getRepresentativeTypeName(S.Context) << IntendedTy
3219 << E->getSourceRange(),
3220 E->getLocStart(),
3221 /*IsStringLocation*/false,
3222 SpecRange,
3223 FixItHint::CreateReplacement(SpecRange, os.str()));
3224
3225 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00003226 // The canonical type for formatting this value is different from the
3227 // actual type of the expression. (This occurs, for example, with Darwin's
3228 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3229 // should be printed as 'long' for 64-bit compatibility.)
3230 // Rather than emitting a normal format/argument mismatch, we want to
3231 // add a cast to the recommended type (and correct the format string
3232 // if necessary).
3233 SmallString<16> CastBuf;
3234 llvm::raw_svector_ostream CastFix(CastBuf);
3235 CastFix << "(";
3236 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3237 CastFix << ")";
3238
3239 SmallVector<FixItHint,4> Hints;
3240 if (!AT.matchesType(S.Context, IntendedTy))
3241 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3242
3243 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3244 // If there's already a cast present, just replace it.
3245 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3246 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3247
3248 } else if (!requiresParensToAddCast(E)) {
3249 // If the expression has high enough precedence,
3250 // just write the C-style cast.
3251 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3252 CastFix.str()));
3253 } else {
3254 // Otherwise, add parens around the expression as well as the cast.
3255 CastFix << "(";
3256 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3257 CastFix.str()));
3258
3259 SourceLocation After = S.PP.getLocForEndOfToken(E->getLocEnd());
3260 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3261 }
3262
Jordan Rose0e5badd2012-12-05 18:44:49 +00003263 if (ShouldNotPrintDirectly) {
3264 // The expression has a type that should not be printed directly.
3265 // We extract the name from the typedef because we don't want to show
3266 // the underlying type in the diagnostic.
3267 StringRef Name = cast<TypedefType>(ExprTy)->getDecl()->getName();
Jordan Roseaee34382012-09-05 22:56:26 +00003268
Jordan Rose0e5badd2012-12-05 18:44:49 +00003269 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
3270 << Name << IntendedTy
3271 << E->getSourceRange(),
3272 E->getLocStart(), /*IsStringLocation=*/false,
3273 SpecRange, Hints);
3274 } else {
3275 // In this case, the expression could be printed using a different
3276 // specifier, but we've decided that the specifier is probably correct
3277 // and we should cast instead. Just use the normal warning message.
3278 EmitFormatDiagnostic(
3279 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3280 << AT.getRepresentativeTypeName(S.Context) << ExprTy
3281 << E->getSourceRange(),
3282 E->getLocStart(), /*IsStringLocation*/false,
3283 SpecRange, Hints);
3284 }
Jordan Roseaee34382012-09-05 22:56:26 +00003285 }
Jordan Rose22b74712012-09-05 22:56:19 +00003286 } else {
3287 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3288 SpecifierLen);
3289 // Since the warning for passing non-POD types to variadic functions
3290 // was deferred until now, we emit a warning for non-POD
3291 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00003292 switch (S.isValidVarArgType(ExprTy)) {
3293 case Sema::VAK_Valid:
3294 case Sema::VAK_ValidInCXX11:
Jordan Rose22b74712012-09-05 22:56:19 +00003295 EmitFormatDiagnostic(
Richard Smithd7293d72013-08-05 18:49:43 +00003296 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3297 << AT.getRepresentativeTypeName(S.Context) << ExprTy
3298 << CSR
3299 << E->getSourceRange(),
3300 E->getLocStart(), /*IsStringLocation*/false, CSR);
3301 break;
3302
3303 case Sema::VAK_Undefined:
3304 EmitFormatDiagnostic(
3305 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003306 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00003307 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00003308 << CallType
3309 << AT.getRepresentativeTypeName(S.Context)
3310 << CSR
3311 << E->getSourceRange(),
3312 E->getLocStart(), /*IsStringLocation*/false, CSR);
Jordan Rose22b74712012-09-05 22:56:19 +00003313 checkForCStrMembers(AT, E, CSR);
Richard Smithd7293d72013-08-05 18:49:43 +00003314 break;
3315
3316 case Sema::VAK_Invalid:
3317 if (ExprTy->isObjCObjectType())
3318 EmitFormatDiagnostic(
3319 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3320 << S.getLangOpts().CPlusPlus11
3321 << ExprTy
3322 << CallType
3323 << AT.getRepresentativeTypeName(S.Context)
3324 << CSR
3325 << E->getSourceRange(),
3326 E->getLocStart(), /*IsStringLocation*/false, CSR);
3327 else
3328 // FIXME: If this is an initializer list, suggest removing the braces
3329 // or inserting a cast to the target type.
3330 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3331 << isa<InitListExpr>(E) << ExprTy << CallType
3332 << AT.getRepresentativeTypeName(S.Context)
3333 << E->getSourceRange();
3334 break;
3335 }
3336
3337 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3338 "format string specifier index out of range");
3339 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003340 }
3341
Ted Kremenekab278de2010-01-28 23:39:18 +00003342 return true;
3343}
3344
Ted Kremenek02087932010-07-16 02:11:22 +00003345//===--- CHECK: Scanf format string checking ------------------------------===//
3346
3347namespace {
3348class CheckScanfHandler : public CheckFormatHandler {
3349public:
3350 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3351 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003352 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003353 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003354 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003355 Sema::VariadicCallType CallType,
3356 llvm::SmallBitVector &CheckedVarArgs)
3357 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3358 numDataArgs, beg, hasVAListArg,
3359 Args, formatIdx, inFunctionCall, CallType,
3360 CheckedVarArgs)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003361 {}
Ted Kremenek02087932010-07-16 02:11:22 +00003362
3363 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3364 const char *startSpecifier,
3365 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00003366
3367 bool HandleInvalidScanfConversionSpecifier(
3368 const analyze_scanf::ScanfSpecifier &FS,
3369 const char *startSpecifier,
3370 unsigned specifierLen);
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003371
3372 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek02087932010-07-16 02:11:22 +00003373};
Ted Kremenek019d2242010-01-29 01:50:07 +00003374}
Ted Kremenekab278de2010-01-28 23:39:18 +00003375
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003376void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3377 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003378 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3379 getLocationOfByte(end), /*IsStringLocation*/true,
3380 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003381}
3382
Ted Kremenekce815422010-07-19 21:25:57 +00003383bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3384 const analyze_scanf::ScanfSpecifier &FS,
3385 const char *startSpecifier,
3386 unsigned specifierLen) {
3387
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003388 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003389 FS.getConversionSpecifier();
3390
3391 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3392 getLocationOfByte(CS.getStart()),
3393 startSpecifier, specifierLen,
3394 CS.getStart(), CS.getLength());
3395}
3396
Ted Kremenek02087932010-07-16 02:11:22 +00003397bool CheckScanfHandler::HandleScanfSpecifier(
3398 const analyze_scanf::ScanfSpecifier &FS,
3399 const char *startSpecifier,
3400 unsigned specifierLen) {
3401
3402 using namespace analyze_scanf;
3403 using namespace analyze_format_string;
3404
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003405 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003406
Ted Kremenek6cd69422010-07-19 22:01:06 +00003407 // Handle case where '%' and '*' don't consume an argument. These shouldn't
3408 // be used to decide if we are using positional arguments consistently.
3409 if (FS.consumesDataArgument()) {
3410 if (atFirstArg) {
3411 atFirstArg = false;
3412 usesPositionalArgs = FS.usesPositionalArg();
3413 }
3414 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003415 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3416 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003417 return false;
3418 }
Ted Kremenek02087932010-07-16 02:11:22 +00003419 }
3420
3421 // Check if the field with is non-zero.
3422 const OptionalAmount &Amt = FS.getFieldWidth();
3423 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3424 if (Amt.getConstantAmount() == 0) {
3425 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3426 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00003427 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3428 getLocationOfByte(Amt.getStart()),
3429 /*IsStringLocation*/true, R,
3430 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00003431 }
3432 }
3433
3434 if (!FS.consumesDataArgument()) {
3435 // FIXME: Technically specifying a precision or field width here
3436 // makes no sense. Worth issuing a warning at some point.
3437 return true;
3438 }
3439
3440 // Consume the argument.
3441 unsigned argIndex = FS.getArgIndex();
3442 if (argIndex < NumDataArgs) {
3443 // The check to see if the argIndex is valid will come later.
3444 // We set the bit here because we may exit early from this
3445 // function if we encounter some other error.
3446 CoveredArgs.set(argIndex);
3447 }
3448
Ted Kremenek4407ea42010-07-20 20:04:47 +00003449 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003450 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003451 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3452 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003453 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003454 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003455 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003456 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3457 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003458
Jordan Rose92303592012-09-08 04:00:03 +00003459 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3460 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3461
Ted Kremenek02087932010-07-16 02:11:22 +00003462 // The remaining checks depend on the data arguments.
3463 if (HasVAListArg)
3464 return true;
3465
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003466 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00003467 return false;
Ted Kremenek02087932010-07-16 02:11:22 +00003468
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003469 // Check that the argument type matches the format specifier.
3470 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00003471 if (!Ex)
3472 return true;
3473
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00003474 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3475 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003476 ScanfSpecifier fixedFS = FS;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003477 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
Hans Wennborgd99d6882012-02-15 09:59:46 +00003478 S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003479
3480 if (success) {
3481 // Get the fix string from the fixed format specifier.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003482 SmallString<128> buf;
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003483 llvm::raw_svector_ostream os(buf);
3484 fixedFS.toString(os);
3485
3486 EmitFormatDiagnostic(
3487 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00003488 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003489 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00003490 Ex->getLocStart(),
3491 /*IsStringLocation*/false,
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003492 getSpecifierRange(startSpecifier, specifierLen),
3493 FixItHint::CreateReplacement(
3494 getSpecifierRange(startSpecifier, specifierLen),
3495 os.str()));
3496 } else {
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003497 EmitFormatDiagnostic(
3498 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00003499 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003500 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00003501 Ex->getLocStart(),
3502 /*IsStringLocation*/false,
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003503 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003504 }
3505 }
3506
Ted Kremenek02087932010-07-16 02:11:22 +00003507 return true;
3508}
3509
3510void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00003511 const Expr *OrigFormatExpr,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003512 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003513 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003514 unsigned firstDataArg, FormatStringType Type,
Richard Smithd7293d72013-08-05 18:49:43 +00003515 bool inFunctionCall, VariadicCallType CallType,
3516 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00003517
Ted Kremenekab278de2010-01-28 23:39:18 +00003518 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00003519 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003520 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003521 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00003522 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3523 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00003524 return;
3525 }
Ted Kremenek02087932010-07-16 02:11:22 +00003526
Ted Kremenekab278de2010-01-28 23:39:18 +00003527 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003528 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00003529 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00003530 // Account for cases where the string literal is truncated in a declaration.
3531 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
3532 assert(T && "String literal not of constant array type!");
3533 size_t TypeSize = T->getSize().getZExtValue();
3534 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003535 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00003536
3537 // Emit a warning if the string literal is truncated and does not contain an
3538 // embedded null character.
3539 if (TypeSize <= StrRef.size() &&
3540 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
3541 CheckFormatHandler::EmitFormatDiagnostic(
3542 *this, inFunctionCall, Args[format_idx],
3543 PDiag(diag::warn_printf_format_string_not_null_terminated),
3544 FExpr->getLocStart(),
3545 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
3546 return;
3547 }
3548
Ted Kremenekab278de2010-01-28 23:39:18 +00003549 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00003550 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003551 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003552 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00003553 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3554 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00003555 return;
3556 }
Ted Kremenek02087932010-07-16 02:11:22 +00003557
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003558 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek02087932010-07-16 02:11:22 +00003559 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003560 numDataArgs, (Type == FST_NSString),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003561 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00003562 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00003563
Hans Wennborg23926bd2011-12-15 10:25:47 +00003564 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00003565 getLangOpts(),
3566 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00003567 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003568 } else if (Type == FST_Scanf) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003569 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003570 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00003571 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00003572
Hans Wennborg23926bd2011-12-15 10:25:47 +00003573 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00003574 getLangOpts(),
3575 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00003576 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003577 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00003578}
3579
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003580//===--- CHECK: Standard memory functions ---------------------------------===//
3581
Nico Weber0e6daef2013-12-26 23:38:39 +00003582/// \brief Takes the expression passed to the size_t parameter of functions
3583/// such as memcmp, strncat, etc and warns if it's a comparison.
3584///
3585/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
3586static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
3587 IdentifierInfo *FnName,
3588 SourceLocation FnLoc,
3589 SourceLocation RParenLoc) {
3590 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
3591 if (!Size)
3592 return false;
3593
3594 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
3595 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
3596 return false;
3597
3598 Preprocessor &PP = S.getPreprocessor();
3599 SourceRange SizeRange = Size->getSourceRange();
3600 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
3601 << SizeRange << FnName;
3602 S.Diag(FnLoc, diag::warn_memsize_comparison_paren_note)
3603 << FnName
3604 << FixItHint::CreateInsertion(
3605 PP.getLocForEndOfToken(Size->getLHS()->getLocEnd()),
3606 ")")
3607 << FixItHint::CreateRemoval(RParenLoc);
3608 S.Diag(SizeRange.getBegin(), diag::warn_memsize_comparison_cast_note)
3609 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
3610 << FixItHint::CreateInsertion(
3611 PP.getLocForEndOfToken(SizeRange.getEnd()), ")");
3612
3613 return true;
3614}
3615
Douglas Gregora74926b2011-05-03 20:05:22 +00003616/// \brief Determine whether the given type is a dynamic class type (e.g.,
3617/// whether it has a vtable).
3618static bool isDynamicClassType(QualType T) {
3619 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3620 if (CXXRecordDecl *Definition = Record->getDefinition())
3621 if (Definition->isDynamicClass())
3622 return true;
3623
3624 return false;
3625}
3626
Chandler Carruth889ed862011-06-21 23:04:20 +00003627/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003628/// otherwise returns NULL.
3629static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Weberc5e73862011-06-14 16:14:58 +00003630 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003631 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3632 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
3633 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00003634
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003635 return 0;
3636}
3637
Chandler Carruth889ed862011-06-21 23:04:20 +00003638/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003639static QualType getSizeOfArgType(const Expr* E) {
3640 if (const UnaryExprOrTypeTraitExpr *SizeOf =
3641 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3642 if (SizeOf->getKind() == clang::UETT_SizeOf)
3643 return SizeOf->getTypeOfArgument();
3644
3645 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00003646}
3647
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003648/// \brief Check for dangerous or invalid arguments to memset().
3649///
Chandler Carruthac687262011-06-03 06:23:57 +00003650/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00003651/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
3652/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003653///
3654/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00003655void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00003656 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00003657 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00003658 assert(BId != 0);
3659
Ted Kremenekb5fabb22011-04-28 01:38:02 +00003660 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00003661 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00003662 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00003663 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00003664 return;
3665
Anna Zaks22122702012-01-17 00:37:07 +00003666 unsigned LastArg = (BId == Builtin::BImemset ||
3667 BId == Builtin::BIstrndup ? 1 : 2);
3668 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00003669 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003670
Nico Weber0e6daef2013-12-26 23:38:39 +00003671 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
3672 Call->getLocStart(), Call->getRParenLoc()))
3673 return;
3674
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003675 // We have special checking when the length is a sizeof expression.
3676 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
3677 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
3678 llvm::FoldingSetNodeID SizeOfArgID;
3679
Douglas Gregor3bb2a812011-05-03 20:37:33 +00003680 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
3681 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00003682 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003683
Douglas Gregor3bb2a812011-05-03 20:37:33 +00003684 QualType DestTy = Dest->getType();
3685 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
3686 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00003687
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003688 // Never warn about void type pointers. This can be used to suppress
3689 // false positives.
3690 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00003691 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003692
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003693 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
3694 // actually comparing the expressions for equality. Because computing the
3695 // expression IDs can be expensive, we only do this if the diagnostic is
3696 // enabled.
3697 if (SizeOfArg &&
3698 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
3699 SizeOfArg->getExprLoc())) {
3700 // We only compute IDs for expressions if the warning is enabled, and
3701 // cache the sizeof arg's ID.
3702 if (SizeOfArgID == llvm::FoldingSetNodeID())
3703 SizeOfArg->Profile(SizeOfArgID, Context, true);
3704 llvm::FoldingSetNodeID DestID;
3705 Dest->Profile(DestID, Context, true);
3706 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00003707 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
3708 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003709 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00003710 StringRef ReadableName = FnName->getName();
3711
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003712 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00003713 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003714 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00003715 if (!PointeeTy->isIncompleteType() &&
3716 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003717 ActionIdx = 2; // If the pointee's size is sizeof(char),
3718 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00003719
3720 // If the function is defined as a builtin macro, do not show macro
3721 // expansion.
3722 SourceLocation SL = SizeOfArg->getExprLoc();
3723 SourceRange DSR = Dest->getSourceRange();
3724 SourceRange SSR = SizeOfArg->getSourceRange();
3725 SourceManager &SM = PP.getSourceManager();
3726
3727 if (SM.isMacroArgExpansion(SL)) {
3728 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
3729 SL = SM.getSpellingLoc(SL);
3730 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
3731 SM.getSpellingLoc(DSR.getEnd()));
3732 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
3733 SM.getSpellingLoc(SSR.getEnd()));
3734 }
3735
Anna Zaksd08d9152012-05-30 23:14:52 +00003736 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003737 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00003738 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00003739 << PointeeTy
3740 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00003741 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00003742 << SSR);
3743 DiagRuntimeBehavior(SL, SizeOfArg,
3744 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
3745 << ActionIdx
3746 << SSR);
3747
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003748 break;
3749 }
3750 }
3751
3752 // Also check for cases where the sizeof argument is the exact same
3753 // type as the memory argument, and where it points to a user-defined
3754 // record type.
3755 if (SizeOfArgTy != QualType()) {
3756 if (PointeeTy->isRecordType() &&
3757 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
3758 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
3759 PDiag(diag::warn_sizeof_pointer_type_memaccess)
3760 << FnName << SizeOfArgTy << ArgIdx
3761 << PointeeTy << Dest->getSourceRange()
3762 << LenExpr->getSourceRange());
3763 break;
3764 }
Nico Weberc5e73862011-06-14 16:14:58 +00003765 }
3766
Douglas Gregor3bb2a812011-05-03 20:37:33 +00003767 // Always complain about dynamic classes.
Anna Zaks22122702012-01-17 00:37:07 +00003768 if (isDynamicClassType(PointeeTy)) {
3769
3770 unsigned OperationType = 0;
3771 // "overwritten" if we're warning about the destination for any call
3772 // but memcmp; otherwise a verb appropriate to the call.
3773 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
3774 if (BId == Builtin::BImemcpy)
3775 OperationType = 1;
3776 else if(BId == Builtin::BImemmove)
3777 OperationType = 2;
3778 else if (BId == Builtin::BImemcmp)
3779 OperationType = 3;
3780 }
3781
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00003782 DiagRuntimeBehavior(
3783 Dest->getExprLoc(), Dest,
3784 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks22122702012-01-17 00:37:07 +00003785 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Anna Zaks201d4892012-01-13 21:52:01 +00003786 << FnName << PointeeTy
Anna Zaks22122702012-01-17 00:37:07 +00003787 << OperationType
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00003788 << Call->getCallee()->getSourceRange());
Anna Zaks22122702012-01-17 00:37:07 +00003789 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
3790 BId != Builtin::BImemset)
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00003791 DiagRuntimeBehavior(
3792 Dest->getExprLoc(), Dest,
3793 PDiag(diag::warn_arc_object_memaccess)
3794 << ArgIdx << FnName << PointeeTy
3795 << Call->getCallee()->getSourceRange());
John McCall31168b02011-06-15 23:02:42 +00003796 else
Douglas Gregor3bb2a812011-05-03 20:37:33 +00003797 continue;
John McCall31168b02011-06-15 23:02:42 +00003798
3799 DiagRuntimeBehavior(
3800 Dest->getExprLoc(), Dest,
Chandler Carruthac687262011-06-03 06:23:57 +00003801 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor3bb2a812011-05-03 20:37:33 +00003802 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
3803 break;
3804 }
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003805 }
3806}
3807
Ted Kremenek6865f772011-08-18 20:55:45 +00003808// A little helper routine: ignore addition and subtraction of integer literals.
3809// This intentionally does not ignore all integer constant expressions because
3810// we don't want to remove sizeof().
3811static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
3812 Ex = Ex->IgnoreParenCasts();
3813
3814 for (;;) {
3815 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
3816 if (!BO || !BO->isAdditiveOp())
3817 break;
3818
3819 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
3820 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
3821
3822 if (isa<IntegerLiteral>(RHS))
3823 Ex = LHS;
3824 else if (isa<IntegerLiteral>(LHS))
3825 Ex = RHS;
3826 else
3827 break;
3828 }
3829
3830 return Ex;
3831}
3832
Anna Zaks13b08572012-08-08 21:42:23 +00003833static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
3834 ASTContext &Context) {
3835 // Only handle constant-sized or VLAs, but not flexible members.
3836 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
3837 // Only issue the FIXIT for arrays of size > 1.
3838 if (CAT->getSize().getSExtValue() <= 1)
3839 return false;
3840 } else if (!Ty->isVariableArrayType()) {
3841 return false;
3842 }
3843 return true;
3844}
3845
Ted Kremenek6865f772011-08-18 20:55:45 +00003846// Warn if the user has made the 'size' argument to strlcpy or strlcat
3847// be the size of the source, instead of the destination.
3848void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
3849 IdentifierInfo *FnName) {
3850
3851 // Don't crash if the user has the wrong number of arguments
3852 if (Call->getNumArgs() != 3)
3853 return;
3854
3855 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
3856 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
3857 const Expr *CompareWithSrc = NULL;
Nico Weber0e6daef2013-12-26 23:38:39 +00003858
3859 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
3860 Call->getLocStart(), Call->getRParenLoc()))
3861 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00003862
3863 // Look for 'strlcpy(dst, x, sizeof(x))'
3864 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
3865 CompareWithSrc = Ex;
3866 else {
3867 // Look for 'strlcpy(dst, x, strlen(x))'
3868 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00003869 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
3870 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00003871 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
3872 }
3873 }
3874
3875 if (!CompareWithSrc)
3876 return;
3877
3878 // Determine if the argument to sizeof/strlen is equal to the source
3879 // argument. In principle there's all kinds of things you could do
3880 // here, for instance creating an == expression and evaluating it with
3881 // EvaluateAsBooleanCondition, but this uses a more direct technique:
3882 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
3883 if (!SrcArgDRE)
3884 return;
3885
3886 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
3887 if (!CompareWithSrcDRE ||
3888 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
3889 return;
3890
3891 const Expr *OriginalSizeArg = Call->getArg(2);
3892 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
3893 << OriginalSizeArg->getSourceRange() << FnName;
3894
3895 // Output a FIXIT hint if the destination is an array (rather than a
3896 // pointer to an array). This could be enhanced to handle some
3897 // pointers if we know the actual size, like if DstArg is 'array+2'
3898 // we could say 'sizeof(array)-2'.
3899 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00003900 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00003901 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00003902
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003903 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00003904 llvm::raw_svector_ostream OS(sizeString);
3905 OS << "sizeof(";
Richard Smith235341b2012-08-16 03:56:14 +00003906 DstArg->printPretty(OS, 0, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00003907 OS << ")";
3908
3909 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
3910 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
3911 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00003912}
3913
Anna Zaks314cd092012-02-01 19:08:57 +00003914/// Check if two expressions refer to the same declaration.
3915static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
3916 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
3917 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
3918 return D1->getDecl() == D2->getDecl();
3919 return false;
3920}
3921
3922static const Expr *getStrlenExprArg(const Expr *E) {
3923 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
3924 const FunctionDecl *FD = CE->getDirectCallee();
3925 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
3926 return 0;
3927 return CE->getArg(0)->IgnoreParenCasts();
3928 }
3929 return 0;
3930}
3931
3932// Warn on anti-patterns as the 'size' argument to strncat.
3933// The correct size argument should look like following:
3934// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
3935void Sema::CheckStrncatArguments(const CallExpr *CE,
3936 IdentifierInfo *FnName) {
3937 // Don't crash if the user has the wrong number of arguments.
3938 if (CE->getNumArgs() < 3)
3939 return;
3940 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
3941 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
3942 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
3943
Nico Weber0e6daef2013-12-26 23:38:39 +00003944 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
3945 CE->getRParenLoc()))
3946 return;
3947
Anna Zaks314cd092012-02-01 19:08:57 +00003948 // Identify common expressions, which are wrongly used as the size argument
3949 // to strncat and may lead to buffer overflows.
3950 unsigned PatternType = 0;
3951 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
3952 // - sizeof(dst)
3953 if (referToTheSameDecl(SizeOfArg, DstArg))
3954 PatternType = 1;
3955 // - sizeof(src)
3956 else if (referToTheSameDecl(SizeOfArg, SrcArg))
3957 PatternType = 2;
3958 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
3959 if (BE->getOpcode() == BO_Sub) {
3960 const Expr *L = BE->getLHS()->IgnoreParenCasts();
3961 const Expr *R = BE->getRHS()->IgnoreParenCasts();
3962 // - sizeof(dst) - strlen(dst)
3963 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
3964 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
3965 PatternType = 1;
3966 // - sizeof(src) - (anything)
3967 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
3968 PatternType = 2;
3969 }
3970 }
3971
3972 if (PatternType == 0)
3973 return;
3974
Anna Zaks5069aa32012-02-03 01:27:37 +00003975 // Generate the diagnostic.
3976 SourceLocation SL = LenArg->getLocStart();
3977 SourceRange SR = LenArg->getSourceRange();
3978 SourceManager &SM = PP.getSourceManager();
3979
3980 // If the function is defined as a builtin macro, do not show macro expansion.
3981 if (SM.isMacroArgExpansion(SL)) {
3982 SL = SM.getSpellingLoc(SL);
3983 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
3984 SM.getSpellingLoc(SR.getEnd()));
3985 }
3986
Anna Zaks13b08572012-08-08 21:42:23 +00003987 // Check if the destination is an array (rather than a pointer to an array).
3988 QualType DstTy = DstArg->getType();
3989 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
3990 Context);
3991 if (!isKnownSizeArray) {
3992 if (PatternType == 1)
3993 Diag(SL, diag::warn_strncat_wrong_size) << SR;
3994 else
3995 Diag(SL, diag::warn_strncat_src_size) << SR;
3996 return;
3997 }
3998
Anna Zaks314cd092012-02-01 19:08:57 +00003999 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00004000 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004001 else
Anna Zaks5069aa32012-02-03 01:27:37 +00004002 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004003
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004004 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00004005 llvm::raw_svector_ostream OS(sizeString);
4006 OS << "sizeof(";
Richard Smith235341b2012-08-16 03:56:14 +00004007 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00004008 OS << ") - ";
4009 OS << "strlen(";
Richard Smith235341b2012-08-16 03:56:14 +00004010 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00004011 OS << ") - 1";
4012
Anna Zaks5069aa32012-02-03 01:27:37 +00004013 Diag(SL, diag::note_strncat_wrong_size)
4014 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00004015}
4016
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004017//===--- CHECK: Return Address of Stack Variable --------------------------===//
4018
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004019static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4020 Decl *ParentDecl);
4021static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
4022 Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004023
4024/// CheckReturnStackAddr - Check if a return statement returns the address
4025/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004026static void
4027CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
4028 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00004029
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004030 Expr *stackE = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004031 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004032
4033 // Perform checking for returned stack addresses, local blocks,
4034 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00004035 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004036 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004037 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0);
Mike Stump12b8ce12009-08-04 21:02:39 +00004038 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004039 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004040 }
4041
4042 if (stackE == 0)
4043 return; // Nothing suspicious was found.
4044
4045 SourceLocation diagLoc;
4046 SourceRange diagRange;
4047 if (refVars.empty()) {
4048 diagLoc = stackE->getLocStart();
4049 diagRange = stackE->getSourceRange();
4050 } else {
4051 // We followed through a reference variable. 'stackE' contains the
4052 // problematic expression but we will warn at the return statement pointing
4053 // at the reference variable. We will later display the "trail" of
4054 // reference variables using notes.
4055 diagLoc = refVars[0]->getLocStart();
4056 diagRange = refVars[0]->getSourceRange();
4057 }
4058
4059 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004060 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004061 : diag::warn_ret_stack_addr)
4062 << DR->getDecl()->getDeclName() << diagRange;
4063 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004064 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004065 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004066 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004067 } else { // local temporary.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004068 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
4069 : diag::warn_ret_local_temp_addr)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004070 << diagRange;
4071 }
4072
4073 // Display the "trail" of reference variables that we followed until we
4074 // found the problematic expression using notes.
4075 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
4076 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
4077 // If this var binds to another reference var, show the range of the next
4078 // var, otherwise the var binds to the problematic expression, in which case
4079 // show the range of the expression.
4080 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
4081 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004082 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
4083 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004084 }
4085}
4086
4087/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
4088/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004089/// to a location on the stack, a local block, an address of a label, or a
4090/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004091/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004092/// encounter a subexpression that (1) clearly does not lead to one of the
4093/// above problematic expressions (2) is something we cannot determine leads to
4094/// a problematic expression based on such local checking.
4095///
4096/// Both EvalAddr and EvalVal follow through reference variables to evaluate
4097/// the expression that they point to. Such variables are added to the
4098/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004099///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00004100/// EvalAddr processes expressions that are pointers that are used as
4101/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004102/// At the base case of the recursion is a check for the above problematic
4103/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004104///
4105/// This implementation handles:
4106///
4107/// * pointer-to-pointer casts
4108/// * implicit conversions from array references to pointers
4109/// * taking the address of fields
4110/// * arbitrary interplay between "&" and "*" operators
4111/// * pointer arithmetic from an address of a stack variable
4112/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004113static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4114 Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004115 if (E->isTypeDependent())
Craig Topper47005942013-08-02 05:10:31 +00004116 return NULL;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004117
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004118 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00004119 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004120 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004121 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00004122 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00004123
Peter Collingbourne91147592011-04-15 00:35:48 +00004124 E = E->IgnoreParens();
4125
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004126 // Our "symbolic interpreter" is just a dispatch off the currently
4127 // viewed AST node. We then recursively traverse the AST by calling
4128 // EvalAddr and EvalVal appropriately.
4129 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004130 case Stmt::DeclRefExprClass: {
4131 DeclRefExpr *DR = cast<DeclRefExpr>(E);
4132
Richard Smith40f08eb2014-01-30 22:05:38 +00004133 // If we leave the immediate function, the lifetime isn't about to end.
4134 if (DR->refersToEnclosingLocal())
4135 return 0;
4136
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004137 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
4138 // If this is a reference variable, follow through to the expression that
4139 // it points to.
4140 if (V->hasLocalStorage() &&
4141 V->getType()->isReferenceType() && V->hasInit()) {
4142 // Add the reference variable to the "trail".
4143 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004144 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004145 }
4146
4147 return NULL;
4148 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004149
Chris Lattner934edb22007-12-28 05:31:15 +00004150 case Stmt::UnaryOperatorClass: {
4151 // The only unary operator that make sense to handle here
4152 // is AddrOf. All others don't make sense as pointers.
4153 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004154
John McCalle3027922010-08-25 11:45:40 +00004155 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004156 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004157 else
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004158 return NULL;
4159 }
Mike Stump11289f42009-09-09 15:08:12 +00004160
Chris Lattner934edb22007-12-28 05:31:15 +00004161 case Stmt::BinaryOperatorClass: {
4162 // Handle pointer arithmetic. All other binary operators are not valid
4163 // in this context.
4164 BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00004165 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00004166
John McCalle3027922010-08-25 11:45:40 +00004167 if (op != BO_Add && op != BO_Sub)
Chris Lattner934edb22007-12-28 05:31:15 +00004168 return NULL;
Mike Stump11289f42009-09-09 15:08:12 +00004169
Chris Lattner934edb22007-12-28 05:31:15 +00004170 Expr *Base = B->getLHS();
4171
4172 // Determine which argument is the real pointer base. It could be
4173 // the RHS argument instead of the LHS.
4174 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00004175
Chris Lattner934edb22007-12-28 05:31:15 +00004176 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004177 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004178 }
Steve Naroff2752a172008-09-10 19:17:48 +00004179
Chris Lattner934edb22007-12-28 05:31:15 +00004180 // For conditional operators we need to see if either the LHS or RHS are
4181 // valid DeclRefExpr*s. If one of them is valid, we return it.
4182 case Stmt::ConditionalOperatorClass: {
4183 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004184
Chris Lattner934edb22007-12-28 05:31:15 +00004185 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004186 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
4187 if (Expr *LHSExpr = C->getLHS()) {
4188 // In C++, we can have a throw-expression, which has 'void' type.
4189 if (!LHSExpr->getType()->isVoidType())
4190 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004191 return LHS;
4192 }
Chris Lattner934edb22007-12-28 05:31:15 +00004193
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004194 // In C++, we can have a throw-expression, which has 'void' type.
4195 if (C->getRHS()->getType()->isVoidType())
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004196 return 0;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004197
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004198 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004199 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004200
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004201 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00004202 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004203 return E; // local block.
4204 return NULL;
4205
4206 case Stmt::AddrLabelExprClass:
4207 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00004208
John McCall28fc7092011-11-10 05:35:25 +00004209 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004210 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
4211 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00004212
Ted Kremenekc3b4c522008-08-07 00:49:01 +00004213 // For casts, we need to handle conversions from arrays to
4214 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00004215 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00004216 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00004217 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00004218 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00004219 case Stmt::CXXStaticCastExprClass:
4220 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00004221 case Stmt::CXXConstCastExprClass:
4222 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8195ad72012-02-23 23:04:32 +00004223 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
4224 switch (cast<CastExpr>(E)->getCastKind()) {
4225 case CK_BitCast:
4226 case CK_LValueToRValue:
4227 case CK_NoOp:
4228 case CK_BaseToDerived:
4229 case CK_DerivedToBase:
4230 case CK_UncheckedDerivedToBase:
4231 case CK_Dynamic:
4232 case CK_CPointerToObjCPointerCast:
4233 case CK_BlockPointerToObjCPointerCast:
4234 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004235 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00004236
4237 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004238 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00004239
4240 default:
4241 return 0;
4242 }
Chris Lattner934edb22007-12-28 05:31:15 +00004243 }
Mike Stump11289f42009-09-09 15:08:12 +00004244
Douglas Gregorfe314812011-06-21 17:03:29 +00004245 case Stmt::MaterializeTemporaryExprClass:
4246 if (Expr *Result = EvalAddr(
4247 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004248 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00004249 return Result;
4250
4251 return E;
4252
Chris Lattner934edb22007-12-28 05:31:15 +00004253 // Everything else: we simply don't reason about them.
4254 default:
4255 return NULL;
4256 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004257}
Mike Stump11289f42009-09-09 15:08:12 +00004258
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004259
4260/// EvalVal - This function is complements EvalAddr in the mutual recursion.
4261/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004262static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4263 Decl *ParentDecl) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004264do {
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00004265 // We should only be called for evaluating non-pointer expressions, or
4266 // expressions with a pointer type that are not used as references but instead
4267 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00004268
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004269 // Our "symbolic interpreter" is just a dispatch off the currently
4270 // viewed AST node. We then recursively traverse the AST by calling
4271 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00004272
4273 E = E->IgnoreParens();
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004274 switch (E->getStmtClass()) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004275 case Stmt::ImplicitCastExprClass: {
4276 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall2536c6d2010-08-25 10:28:54 +00004277 if (IE->getValueKind() == VK_LValue) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004278 E = IE->getSubExpr();
4279 continue;
4280 }
4281 return NULL;
4282 }
4283
John McCall28fc7092011-11-10 05:35:25 +00004284 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004285 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00004286
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004287 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004288 // When we hit a DeclRefExpr we are looking at code that refers to a
4289 // variable's name. If it's not a reference variable we check if it has
4290 // local storage within the function, and if so, return the expression.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004291 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004292
Richard Smith40f08eb2014-01-30 22:05:38 +00004293 // If we leave the immediate function, the lifetime isn't about to end.
4294 if (DR->refersToEnclosingLocal())
4295 return 0;
4296
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004297 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
4298 // Check if it refers to itself, e.g. "int& i = i;".
4299 if (V == ParentDecl)
4300 return DR;
4301
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004302 if (V->hasLocalStorage()) {
4303 if (!V->getType()->isReferenceType())
4304 return DR;
4305
4306 // Reference variable, follow through to the expression that
4307 // it points to.
4308 if (V->hasInit()) {
4309 // Add the reference variable to the "trail".
4310 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004311 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004312 }
4313 }
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004314 }
Mike Stump11289f42009-09-09 15:08:12 +00004315
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004316 return NULL;
4317 }
Mike Stump11289f42009-09-09 15:08:12 +00004318
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004319 case Stmt::UnaryOperatorClass: {
4320 // The only unary operator that make sense to handle here
4321 // is Deref. All others don't resolve to a "name." This includes
4322 // handling all sorts of rvalues passed to a unary operator.
4323 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004324
John McCalle3027922010-08-25 11:45:40 +00004325 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004326 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004327
4328 return NULL;
4329 }
Mike Stump11289f42009-09-09 15:08:12 +00004330
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004331 case Stmt::ArraySubscriptExprClass: {
4332 // Array subscripts are potential references to data on the stack. We
4333 // retrieve the DeclRefExpr* for the array variable if it indeed
4334 // has local storage.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004335 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004336 }
Mike Stump11289f42009-09-09 15:08:12 +00004337
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004338 case Stmt::ConditionalOperatorClass: {
4339 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004340 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004341 ConditionalOperator *C = cast<ConditionalOperator>(E);
4342
Anders Carlsson801c5c72007-11-30 19:04:31 +00004343 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004344 if (Expr *LHSExpr = C->getLHS()) {
4345 // In C++, we can have a throw-expression, which has 'void' type.
4346 if (!LHSExpr->getType()->isVoidType())
4347 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
4348 return LHS;
4349 }
4350
4351 // In C++, we can have a throw-expression, which has 'void' type.
4352 if (C->getRHS()->getType()->isVoidType())
4353 return 0;
Anders Carlsson801c5c72007-11-30 19:04:31 +00004354
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004355 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004356 }
Mike Stump11289f42009-09-09 15:08:12 +00004357
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004358 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00004359 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004360 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004361
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004362 // Check for indirect access. We only want direct field accesses.
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00004363 if (M->isArrow())
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004364 return NULL;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00004365
4366 // Check whether the member type is itself a reference, in which case
4367 // we're not going to refer to the member, but to what the member refers to.
4368 if (M->getMemberDecl()->getType()->isReferenceType())
4369 return NULL;
4370
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004371 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004372 }
Mike Stump11289f42009-09-09 15:08:12 +00004373
Douglas Gregorfe314812011-06-21 17:03:29 +00004374 case Stmt::MaterializeTemporaryExprClass:
4375 if (Expr *Result = EvalVal(
4376 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004377 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00004378 return Result;
4379
4380 return E;
4381
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004382 default:
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004383 // Check that we don't return or take the address of a reference to a
4384 // temporary. This is only useful in C++.
4385 if (!E->isTypeDependent() && E->isRValue())
4386 return E;
4387
4388 // Everything else: we simply don't reason about them.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004389 return NULL;
4390 }
Ted Kremenekb7861562010-08-04 20:01:07 +00004391} while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004392}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004393
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004394void
4395Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
4396 SourceLocation ReturnLoc,
4397 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00004398 const AttrVec *Attrs,
4399 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004400 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
4401
4402 // Check if the return value is null but should not be.
4403 if (Attrs)
4404 for (specific_attr_iterator<ReturnsNonNullAttr>
4405 I = specific_attr_iterator<ReturnsNonNullAttr>(Attrs->begin()),
4406 E = specific_attr_iterator<ReturnsNonNullAttr>(Attrs->end());
4407 I != E; ++I) {
4408 if (CheckNonNullExpr(*this, RetValExp))
4409 Diag(ReturnLoc, diag::warn_null_ret)
4410 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
4411 break;
4412 }
Artyom Skrobov9f213442014-01-24 11:10:39 +00004413
4414 // C++11 [basic.stc.dynamic.allocation]p4:
4415 // If an allocation function declared with a non-throwing
4416 // exception-specification fails to allocate storage, it shall return
4417 // a null pointer. Any other allocation function that fails to allocate
4418 // storage shall indicate failure only by throwing an exception [...]
4419 if (FD) {
4420 OverloadedOperatorKind Op = FD->getOverloadedOperator();
4421 if (Op == OO_New || Op == OO_Array_New) {
4422 const FunctionProtoType *Proto
4423 = FD->getType()->castAs<FunctionProtoType>();
4424 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
4425 CheckNonNullExpr(*this, RetValExp))
4426 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
4427 << FD << getLangOpts().CPlusPlus11;
4428 }
4429 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004430}
4431
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004432//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
4433
4434/// Check for comparisons of floating point operands using != and ==.
4435/// Issue a warning if these are no self-comparisons, as they are not likely
4436/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00004437void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00004438 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
4439 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004440
4441 // Special case: check for x == x (which is OK).
4442 // Do not emit warnings for such cases.
4443 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
4444 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
4445 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00004446 return;
Mike Stump11289f42009-09-09 15:08:12 +00004447
4448
Ted Kremenekeda40e22007-11-29 00:59:04 +00004449 // Special case: check for comparisons against literals that can be exactly
4450 // represented by APFloat. In such cases, do not emit a warning. This
4451 // is a heuristic: often comparison against such literals are used to
4452 // detect if a value in a variable has not changed. This clearly can
4453 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00004454 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
4455 if (FLL->isExact())
4456 return;
4457 } else
4458 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
4459 if (FLR->isExact())
4460 return;
Mike Stump11289f42009-09-09 15:08:12 +00004461
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004462 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00004463 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00004464 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00004465 return;
Mike Stump11289f42009-09-09 15:08:12 +00004466
David Blaikie1f4ff152012-07-16 20:47:22 +00004467 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00004468 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00004469 return;
Mike Stump11289f42009-09-09 15:08:12 +00004470
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004471 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00004472 Diag(Loc, diag::warn_floatingpoint_eq)
4473 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004474}
John McCallca01b222010-01-04 23:21:16 +00004475
John McCall70aa5392010-01-06 05:24:50 +00004476//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
4477//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00004478
John McCall70aa5392010-01-06 05:24:50 +00004479namespace {
John McCallca01b222010-01-04 23:21:16 +00004480
John McCall70aa5392010-01-06 05:24:50 +00004481/// Structure recording the 'active' range of an integer-valued
4482/// expression.
4483struct IntRange {
4484 /// The number of bits active in the int.
4485 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00004486
John McCall70aa5392010-01-06 05:24:50 +00004487 /// True if the int is known not to have negative values.
4488 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00004489
John McCall70aa5392010-01-06 05:24:50 +00004490 IntRange(unsigned Width, bool NonNegative)
4491 : Width(Width), NonNegative(NonNegative)
4492 {}
John McCallca01b222010-01-04 23:21:16 +00004493
John McCall817d4af2010-11-10 23:38:19 +00004494 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00004495 static IntRange forBoolType() {
4496 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00004497 }
4498
John McCall817d4af2010-11-10 23:38:19 +00004499 /// Returns the range of an opaque value of the given integral type.
4500 static IntRange forValueOfType(ASTContext &C, QualType T) {
4501 return forValueOfCanonicalType(C,
4502 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00004503 }
4504
John McCall817d4af2010-11-10 23:38:19 +00004505 /// Returns the range of an opaque value of a canonical integral type.
4506 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00004507 assert(T->isCanonicalUnqualified());
4508
4509 if (const VectorType *VT = dyn_cast<VectorType>(T))
4510 T = VT->getElementType().getTypePtr();
4511 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4512 T = CT->getElementType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00004513
David Majnemer6a426652013-06-07 22:07:20 +00004514 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00004515 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00004516 EnumDecl *Enum = ET->getDecl();
4517 if (!Enum->isCompleteDefinition())
4518 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00004519
David Majnemer6a426652013-06-07 22:07:20 +00004520 unsigned NumPositive = Enum->getNumPositiveBits();
4521 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00004522
David Majnemer6a426652013-06-07 22:07:20 +00004523 if (NumNegative == 0)
4524 return IntRange(NumPositive, true/*NonNegative*/);
4525 else
4526 return IntRange(std::max(NumPositive + 1, NumNegative),
4527 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00004528 }
John McCall70aa5392010-01-06 05:24:50 +00004529
4530 const BuiltinType *BT = cast<BuiltinType>(T);
4531 assert(BT->isInteger());
4532
4533 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4534 }
4535
John McCall817d4af2010-11-10 23:38:19 +00004536 /// Returns the "target" range of a canonical integral type, i.e.
4537 /// the range of values expressible in the type.
4538 ///
4539 /// This matches forValueOfCanonicalType except that enums have the
4540 /// full range of their type, not the range of their enumerators.
4541 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
4542 assert(T->isCanonicalUnqualified());
4543
4544 if (const VectorType *VT = dyn_cast<VectorType>(T))
4545 T = VT->getElementType().getTypePtr();
4546 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4547 T = CT->getElementType().getTypePtr();
4548 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00004549 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00004550
4551 const BuiltinType *BT = cast<BuiltinType>(T);
4552 assert(BT->isInteger());
4553
4554 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4555 }
4556
4557 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00004558 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00004559 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00004560 L.NonNegative && R.NonNegative);
4561 }
4562
John McCall817d4af2010-11-10 23:38:19 +00004563 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00004564 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00004565 return IntRange(std::min(L.Width, R.Width),
4566 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00004567 }
4568};
4569
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004570static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
4571 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00004572 if (value.isSigned() && value.isNegative())
4573 return IntRange(value.getMinSignedBits(), false);
4574
4575 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00004576 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00004577
4578 // isNonNegative() just checks the sign bit without considering
4579 // signedness.
4580 return IntRange(value.getActiveBits(), true);
4581}
4582
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004583static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
4584 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00004585 if (result.isInt())
4586 return GetValueRange(C, result.getInt(), MaxWidth);
4587
4588 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00004589 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
4590 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
4591 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
4592 R = IntRange::join(R, El);
4593 }
John McCall70aa5392010-01-06 05:24:50 +00004594 return R;
4595 }
4596
4597 if (result.isComplexInt()) {
4598 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
4599 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
4600 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00004601 }
4602
4603 // This can happen with lossless casts to intptr_t of "based" lvalues.
4604 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00004605 // FIXME: The only reason we need to pass the type in here is to get
4606 // the sign right on this one case. It would be nice if APValue
4607 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004608 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00004609 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00004610}
John McCall70aa5392010-01-06 05:24:50 +00004611
Eli Friedmane6d33952013-07-08 20:20:06 +00004612static QualType GetExprType(Expr *E) {
4613 QualType Ty = E->getType();
4614 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
4615 Ty = AtomicRHS->getValueType();
4616 return Ty;
4617}
4618
John McCall70aa5392010-01-06 05:24:50 +00004619/// Pseudo-evaluate the given integer expression, estimating the
4620/// range of values it might take.
4621///
4622/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004623static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00004624 E = E->IgnoreParens();
4625
4626 // Try a full evaluation first.
4627 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00004628 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00004629 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00004630
4631 // I think we only want to look through implicit casts here; if the
4632 // user has an explicit widening cast, we should treat the value as
4633 // being of the new, wider type.
4634 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00004635 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00004636 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
4637
Eli Friedmane6d33952013-07-08 20:20:06 +00004638 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00004639
John McCalle3027922010-08-25 11:45:40 +00004640 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall2ce81ad2010-01-06 22:07:33 +00004641
John McCall70aa5392010-01-06 05:24:50 +00004642 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00004643 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00004644 return OutputTypeRange;
4645
4646 IntRange SubRange
4647 = GetExprRange(C, CE->getSubExpr(),
4648 std::min(MaxWidth, OutputTypeRange.Width));
4649
4650 // Bail out if the subexpr's range is as wide as the cast type.
4651 if (SubRange.Width >= OutputTypeRange.Width)
4652 return OutputTypeRange;
4653
4654 // Otherwise, we take the smaller width, and we're non-negative if
4655 // either the output type or the subexpr is.
4656 return IntRange(SubRange.Width,
4657 SubRange.NonNegative || OutputTypeRange.NonNegative);
4658 }
4659
4660 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4661 // If we can fold the condition, just take that operand.
4662 bool CondResult;
4663 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
4664 return GetExprRange(C, CondResult ? CO->getTrueExpr()
4665 : CO->getFalseExpr(),
4666 MaxWidth);
4667
4668 // Otherwise, conservatively merge.
4669 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
4670 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
4671 return IntRange::join(L, R);
4672 }
4673
4674 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4675 switch (BO->getOpcode()) {
4676
4677 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00004678 case BO_LAnd:
4679 case BO_LOr:
4680 case BO_LT:
4681 case BO_GT:
4682 case BO_LE:
4683 case BO_GE:
4684 case BO_EQ:
4685 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00004686 return IntRange::forBoolType();
4687
John McCallc3688382011-07-13 06:35:24 +00004688 // The type of the assignments is the type of the LHS, so the RHS
4689 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00004690 case BO_MulAssign:
4691 case BO_DivAssign:
4692 case BO_RemAssign:
4693 case BO_AddAssign:
4694 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00004695 case BO_XorAssign:
4696 case BO_OrAssign:
4697 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00004698 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00004699
John McCallc3688382011-07-13 06:35:24 +00004700 // Simple assignments just pass through the RHS, which will have
4701 // been coerced to the LHS type.
4702 case BO_Assign:
4703 // TODO: bitfields?
4704 return GetExprRange(C, BO->getRHS(), MaxWidth);
4705
John McCall70aa5392010-01-06 05:24:50 +00004706 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00004707 case BO_PtrMemD:
4708 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00004709 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00004710
John McCall2ce81ad2010-01-06 22:07:33 +00004711 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00004712 case BO_And:
4713 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00004714 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
4715 GetExprRange(C, BO->getRHS(), MaxWidth));
4716
John McCall70aa5392010-01-06 05:24:50 +00004717 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00004718 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00004719 // ...except that we want to treat '1 << (blah)' as logically
4720 // positive. It's an important idiom.
4721 if (IntegerLiteral *I
4722 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
4723 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00004724 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00004725 return IntRange(R.Width, /*NonNegative*/ true);
4726 }
4727 }
4728 // fallthrough
4729
John McCalle3027922010-08-25 11:45:40 +00004730 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00004731 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00004732
John McCall2ce81ad2010-01-06 22:07:33 +00004733 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00004734 case BO_Shr:
4735 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00004736 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4737
4738 // If the shift amount is a positive constant, drop the width by
4739 // that much.
4740 llvm::APSInt shift;
4741 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
4742 shift.isNonNegative()) {
4743 unsigned zext = shift.getZExtValue();
4744 if (zext >= L.Width)
4745 L.Width = (L.NonNegative ? 0 : 1);
4746 else
4747 L.Width -= zext;
4748 }
4749
4750 return L;
4751 }
4752
4753 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00004754 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00004755 return GetExprRange(C, BO->getRHS(), MaxWidth);
4756
John McCall2ce81ad2010-01-06 22:07:33 +00004757 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00004758 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00004759 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00004760 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00004761 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004762
John McCall51431812011-07-14 22:39:48 +00004763 // The width of a division result is mostly determined by the size
4764 // of the LHS.
4765 case BO_Div: {
4766 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00004767 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00004768 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4769
4770 // If the divisor is constant, use that.
4771 llvm::APSInt divisor;
4772 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
4773 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
4774 if (log2 >= L.Width)
4775 L.Width = (L.NonNegative ? 0 : 1);
4776 else
4777 L.Width = std::min(L.Width - log2, MaxWidth);
4778 return L;
4779 }
4780
4781 // Otherwise, just use the LHS's width.
4782 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4783 return IntRange(L.Width, L.NonNegative && R.NonNegative);
4784 }
4785
4786 // The result of a remainder can't be larger than the result of
4787 // either side.
4788 case BO_Rem: {
4789 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00004790 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00004791 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4792 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4793
4794 IntRange meet = IntRange::meet(L, R);
4795 meet.Width = std::min(meet.Width, MaxWidth);
4796 return meet;
4797 }
4798
4799 // The default behavior is okay for these.
4800 case BO_Mul:
4801 case BO_Add:
4802 case BO_Xor:
4803 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00004804 break;
4805 }
4806
John McCall51431812011-07-14 22:39:48 +00004807 // The default case is to treat the operation as if it were closed
4808 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00004809 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4810 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
4811 return IntRange::join(L, R);
4812 }
4813
4814 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
4815 switch (UO->getOpcode()) {
4816 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00004817 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00004818 return IntRange::forBoolType();
4819
4820 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00004821 case UO_Deref:
4822 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00004823 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00004824
4825 default:
4826 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
4827 }
4828 }
4829
Ted Kremeneka553fbf2013-10-14 18:55:27 +00004830 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
4831 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
4832
John McCalld25db7e2013-05-06 21:39:12 +00004833 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00004834 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00004835 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00004836
Eli Friedmane6d33952013-07-08 20:20:06 +00004837 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00004838}
John McCall263a48b2010-01-04 23:31:57 +00004839
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004840static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00004841 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00004842}
4843
John McCall263a48b2010-01-04 23:31:57 +00004844/// Checks whether the given value, which currently has the given
4845/// source semantics, has the same value when coerced through the
4846/// target semantics.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004847static bool IsSameFloatAfterCast(const llvm::APFloat &value,
4848 const llvm::fltSemantics &Src,
4849 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00004850 llvm::APFloat truncated = value;
4851
4852 bool ignored;
4853 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
4854 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
4855
4856 return truncated.bitwiseIsEqual(value);
4857}
4858
4859/// Checks whether the given value, which currently has the given
4860/// source semantics, has the same value when coerced through the
4861/// target semantics.
4862///
4863/// The value might be a vector of floats (or a complex number).
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004864static bool IsSameFloatAfterCast(const APValue &value,
4865 const llvm::fltSemantics &Src,
4866 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00004867 if (value.isFloat())
4868 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
4869
4870 if (value.isVector()) {
4871 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
4872 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
4873 return false;
4874 return true;
4875 }
4876
4877 assert(value.isComplexFloat());
4878 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
4879 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
4880}
4881
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004882static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00004883
Ted Kremenek6274be42010-09-23 21:43:44 +00004884static bool IsZero(Sema &S, Expr *E) {
4885 // Suppress cases where we are comparing against an enum constant.
4886 if (const DeclRefExpr *DR =
4887 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
4888 if (isa<EnumConstantDecl>(DR->getDecl()))
4889 return false;
4890
4891 // Suppress cases where the '0' value is expanded from a macro.
4892 if (E->getLocStart().isMacroID())
4893 return false;
4894
John McCallcc7e5bf2010-05-06 08:58:33 +00004895 llvm::APSInt Value;
4896 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
4897}
4898
John McCall2551c1b2010-10-06 00:25:24 +00004899static bool HasEnumType(Expr *E) {
4900 // Strip off implicit integral promotions.
4901 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00004902 if (ICE->getCastKind() != CK_IntegralCast &&
4903 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00004904 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00004905 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00004906 }
4907
4908 return E->getType()->isEnumeralType();
4909}
4910
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004911static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00004912 // Disable warning in template instantiations.
4913 if (!S.ActiveTemplateInstantiations.empty())
4914 return;
4915
John McCalle3027922010-08-25 11:45:40 +00004916 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00004917 if (E->isValueDependent())
4918 return;
4919
John McCalle3027922010-08-25 11:45:40 +00004920 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00004921 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00004922 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00004923 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00004924 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00004925 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00004926 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00004927 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00004928 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00004929 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00004930 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00004931 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00004932 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00004933 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00004934 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00004935 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4936 }
4937}
4938
Fariborz Jahanianb1885422012-09-18 17:37:21 +00004939static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00004940 Expr *Constant, Expr *Other,
Fariborz Jahanianb1885422012-09-18 17:37:21 +00004941 llvm::APSInt Value,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00004942 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00004943 // Disable warning in template instantiations.
4944 if (!S.ActiveTemplateInstantiations.empty())
4945 return;
4946
Richard Trieu560910c2012-11-14 22:50:24 +00004947 // 0 values are handled later by CheckTrivialUnsignedComparison().
4948 if (Value == 0)
4949 return;
4950
Fariborz Jahanianb1885422012-09-18 17:37:21 +00004951 BinaryOperatorKind op = E->getOpcode();
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00004952 QualType OtherT = Other->getType();
4953 QualType ConstantT = Constant->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00004954 QualType CommonT = E->getLHS()->getType();
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00004955 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
Fariborz Jahanianb1885422012-09-18 17:37:21 +00004956 return;
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00004957 assert((OtherT->isIntegerType() && ConstantT->isIntegerType())
Fariborz Jahanianb1885422012-09-18 17:37:21 +00004958 && "comparison with non-integer type");
Richard Trieu560910c2012-11-14 22:50:24 +00004959
4960 bool ConstantSigned = ConstantT->isSignedIntegerType();
Richard Trieu560910c2012-11-14 22:50:24 +00004961 bool CommonSigned = CommonT->isSignedIntegerType();
4962
4963 bool EqualityOnly = false;
4964
4965 // TODO: Investigate using GetExprRange() to get tighter bounds on
4966 // on the bit ranges.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00004967 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
Richard Trieu560910c2012-11-14 22:50:24 +00004968 unsigned OtherWidth = OtherRange.Width;
4969
4970 if (CommonSigned) {
4971 // The common type is signed, therefore no signed to unsigned conversion.
Eli Friedman5ac98752012-11-30 23:09:29 +00004972 if (!OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00004973 // Check that the constant is representable in type OtherT.
4974 if (ConstantSigned) {
4975 if (OtherWidth >= Value.getMinSignedBits())
4976 return;
4977 } else { // !ConstantSigned
4978 if (OtherWidth >= Value.getActiveBits() + 1)
4979 return;
4980 }
4981 } else { // !OtherSigned
4982 // Check that the constant is representable in type OtherT.
4983 // Negative values are out of range.
4984 if (ConstantSigned) {
4985 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
4986 return;
4987 } else { // !ConstantSigned
4988 if (OtherWidth >= Value.getActiveBits())
4989 return;
4990 }
4991 }
4992 } else { // !CommonSigned
Eli Friedman5ac98752012-11-30 23:09:29 +00004993 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00004994 if (OtherWidth >= Value.getActiveBits())
4995 return;
Eli Friedman5ac98752012-11-30 23:09:29 +00004996 } else if (!OtherRange.NonNegative && !ConstantSigned) {
Richard Trieu560910c2012-11-14 22:50:24 +00004997 // Check to see if the constant is representable in OtherT.
4998 if (OtherWidth > Value.getActiveBits())
4999 return;
5000 // Check to see if the constant is equivalent to a negative value
5001 // cast to CommonT.
5002 if (S.Context.getIntWidth(ConstantT) == S.Context.getIntWidth(CommonT) &&
Richard Trieu03c3a2f2012-11-15 03:43:50 +00005003 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
Richard Trieu560910c2012-11-14 22:50:24 +00005004 return;
5005 // The constant value rests between values that OtherT can represent after
5006 // conversion. Relational comparison still works, but equality
5007 // comparisons will be tautological.
5008 EqualityOnly = true;
5009 } else { // OtherSigned && ConstantSigned
5010 assert(0 && "Two signed types converted to unsigned types.");
5011 }
5012 }
5013
5014 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
5015
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005016 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00005017 if (op == BO_EQ || op == BO_NE) {
5018 IsTrue = op == BO_NE;
5019 } else if (EqualityOnly) {
5020 return;
5021 } else if (RhsConstant) {
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005022 if (op == BO_GT || op == BO_GE)
Richard Trieu560910c2012-11-14 22:50:24 +00005023 IsTrue = !PositiveConstant;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005024 else // op == BO_LT || op == BO_LE
Richard Trieu560910c2012-11-14 22:50:24 +00005025 IsTrue = PositiveConstant;
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005026 } else {
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005027 if (op == BO_LT || op == BO_LE)
Richard Trieu560910c2012-11-14 22:50:24 +00005028 IsTrue = !PositiveConstant;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005029 else // op == BO_GT || op == BO_GE
Richard Trieu560910c2012-11-14 22:50:24 +00005030 IsTrue = PositiveConstant;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005031 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005032
5033 // If this is a comparison to an enum constant, include that
5034 // constant in the diagnostic.
5035 const EnumConstantDecl *ED = 0;
5036 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
5037 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
5038
5039 SmallString<64> PrettySourceValue;
5040 llvm::raw_svector_ostream OS(PrettySourceValue);
5041 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00005042 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005043 else
5044 OS << Value;
5045
Richard Trieuc38786b2014-01-10 04:38:09 +00005046 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
5047 S.PDiag(diag::warn_out_of_range_compare)
5048 << OS.str() << OtherT << IsTrue
5049 << E->getLHS()->getSourceRange()
5050 << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005051}
5052
John McCallcc7e5bf2010-05-06 08:58:33 +00005053/// Analyze the operands of the given comparison. Implements the
5054/// fallback case from AnalyzeComparison.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005055static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00005056 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5057 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00005058}
John McCall263a48b2010-01-04 23:31:57 +00005059
John McCallca01b222010-01-04 23:21:16 +00005060/// \brief Implements -Wsign-compare.
5061///
Richard Trieu82402a02011-09-15 21:56:47 +00005062/// \param E the binary operator to check for warnings
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005063static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005064 // The type the comparison is being performed in.
5065 QualType T = E->getLHS()->getType();
5066 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
5067 && "comparison with mismatched types");
Fariborz Jahanian282071e2012-09-18 17:46:26 +00005068 if (E->isValueDependent())
5069 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005070
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005071 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
5072 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005073
5074 bool IsComparisonConstant = false;
5075
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005076 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005077 // of 'true' or 'false'.
5078 if (T->isIntegralType(S.Context)) {
5079 llvm::APSInt RHSValue;
5080 bool IsRHSIntegralLiteral =
5081 RHS->isIntegerConstantExpr(RHSValue, S.Context);
5082 llvm::APSInt LHSValue;
5083 bool IsLHSIntegralLiteral =
5084 LHS->isIntegerConstantExpr(LHSValue, S.Context);
5085 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
5086 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
5087 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
5088 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
5089 else
5090 IsComparisonConstant =
5091 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005092 } else if (!T->hasUnsignedIntegerRepresentation())
5093 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005094
John McCallcc7e5bf2010-05-06 08:58:33 +00005095 // We don't do anything special if this isn't an unsigned integral
5096 // comparison: we're only interested in integral comparisons, and
5097 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00005098 //
5099 // We also don't care about value-dependent expressions or expressions
5100 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005101 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00005102 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005103
John McCallcc7e5bf2010-05-06 08:58:33 +00005104 // Check to see if one of the (unmodified) operands is of different
5105 // signedness.
5106 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00005107 if (LHS->getType()->hasSignedIntegerRepresentation()) {
5108 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00005109 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00005110 signedOperand = LHS;
5111 unsignedOperand = RHS;
5112 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
5113 signedOperand = RHS;
5114 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00005115 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00005116 CheckTrivialUnsignedComparison(S, E);
5117 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005118 }
5119
John McCallcc7e5bf2010-05-06 08:58:33 +00005120 // Otherwise, calculate the effective range of the signed operand.
5121 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00005122
John McCallcc7e5bf2010-05-06 08:58:33 +00005123 // Go ahead and analyze implicit conversions in the operands. Note
5124 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00005125 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
5126 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00005127
John McCallcc7e5bf2010-05-06 08:58:33 +00005128 // If the signed range is non-negative, -Wsign-compare won't fire,
5129 // but we should still check for comparisons which are always true
5130 // or false.
5131 if (signedRange.NonNegative)
5132 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005133
5134 // For (in)equality comparisons, if the unsigned operand is a
5135 // constant which cannot collide with a overflowed signed operand,
5136 // then reinterpreting the signed operand as unsigned will not
5137 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00005138 if (E->isEqualityOp()) {
5139 unsigned comparisonWidth = S.Context.getIntWidth(T);
5140 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00005141
John McCallcc7e5bf2010-05-06 08:58:33 +00005142 // We should never be unable to prove that the unsigned operand is
5143 // non-negative.
5144 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
5145
5146 if (unsignedRange.Width < comparisonWidth)
5147 return;
5148 }
5149
Douglas Gregorbfb4a212012-05-01 01:53:49 +00005150 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
5151 S.PDiag(diag::warn_mixed_sign_comparison)
5152 << LHS->getType() << RHS->getType()
5153 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00005154}
5155
John McCall1f425642010-11-11 03:21:53 +00005156/// Analyzes an attempt to assign the given value to a bitfield.
5157///
5158/// Returns true if there was something fishy about the attempt.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005159static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
5160 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00005161 assert(Bitfield->isBitField());
5162 if (Bitfield->isInvalidDecl())
5163 return false;
5164
John McCalldeebbcf2010-11-11 05:33:51 +00005165 // White-list bool bitfields.
5166 if (Bitfield->getType()->isBooleanType())
5167 return false;
5168
Douglas Gregor789adec2011-02-04 13:09:01 +00005169 // Ignore value- or type-dependent expressions.
5170 if (Bitfield->getBitWidth()->isValueDependent() ||
5171 Bitfield->getBitWidth()->isTypeDependent() ||
5172 Init->isValueDependent() ||
5173 Init->isTypeDependent())
5174 return false;
5175
John McCall1f425642010-11-11 03:21:53 +00005176 Expr *OriginalInit = Init->IgnoreParenImpCasts();
5177
Richard Smith5fab0c92011-12-28 19:48:30 +00005178 llvm::APSInt Value;
5179 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00005180 return false;
5181
John McCall1f425642010-11-11 03:21:53 +00005182 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00005183 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00005184
5185 if (OriginalWidth <= FieldWidth)
5186 return false;
5187
Eli Friedmanc267a322012-01-26 23:11:39 +00005188 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00005189 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00005190 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00005191
Eli Friedmanc267a322012-01-26 23:11:39 +00005192 // Check whether the stored value is equal to the original value.
5193 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00005194 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00005195 return false;
5196
Eli Friedmanc267a322012-01-26 23:11:39 +00005197 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00005198 // therefore don't strictly fit into a signed bitfield of width 1.
5199 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00005200 return false;
5201
John McCall1f425642010-11-11 03:21:53 +00005202 std::string PrettyValue = Value.toString(10);
5203 std::string PrettyTrunc = TruncatedValue.toString(10);
5204
5205 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
5206 << PrettyValue << PrettyTrunc << OriginalInit->getType()
5207 << Init->getSourceRange();
5208
5209 return true;
5210}
5211
John McCalld2a53122010-11-09 23:24:47 +00005212/// Analyze the given simple or compound assignment for warning-worthy
5213/// operations.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005214static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00005215 // Just recurse on the LHS.
5216 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5217
5218 // We want to recurse on the RHS as normal unless we're assigning to
5219 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00005220 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005221 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00005222 E->getOperatorLoc())) {
5223 // Recurse, ignoring any implicit conversions on the RHS.
5224 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
5225 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00005226 }
5227 }
5228
5229 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
5230}
5231
John McCall263a48b2010-01-04 23:31:57 +00005232/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005233static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00005234 SourceLocation CContext, unsigned diag,
5235 bool pruneControlFlow = false) {
5236 if (pruneControlFlow) {
5237 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5238 S.PDiag(diag)
5239 << SourceType << T << E->getSourceRange()
5240 << SourceRange(CContext));
5241 return;
5242 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00005243 S.Diag(E->getExprLoc(), diag)
5244 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
5245}
5246
Chandler Carruth7f3654f2011-04-05 06:47:57 +00005247/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005248static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00005249 SourceLocation CContext, unsigned diag,
5250 bool pruneControlFlow = false) {
5251 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00005252}
5253
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005254/// Diagnose an implicit cast from a literal expression. Does not warn when the
5255/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00005256void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
5257 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005258 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00005259 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005260 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00005261 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
5262 T->hasUnsignedIntegerRepresentation());
5263 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00005264 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005265 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00005266 return;
5267
Eli Friedman07185912013-08-29 23:44:43 +00005268 // FIXME: Force the precision of the source value down so we don't print
5269 // digits which are usually useless (we don't really care here if we
5270 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
5271 // would automatically print the shortest representation, but it's a bit
5272 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00005273 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00005274 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
5275 precision = (precision * 59 + 195) / 196;
5276 Value.toString(PrettySourceValue, precision);
5277
David Blaikie9b88cc02012-05-15 17:18:27 +00005278 SmallString<16> PrettyTargetValue;
David Blaikie7555b6a2012-05-15 16:56:36 +00005279 if (T->isSpecificBuiltinType(BuiltinType::Bool))
5280 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
5281 else
David Blaikie9b88cc02012-05-15 17:18:27 +00005282 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00005283
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005284 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikie7555b6a2012-05-15 16:56:36 +00005285 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
5286 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00005287}
5288
John McCall18a2c2c2010-11-09 22:22:12 +00005289std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
5290 if (!Range.Width) return "0";
5291
5292 llvm::APSInt ValueInRange = Value;
5293 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00005294 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00005295 return ValueInRange.toString(10);
5296}
5297
Hans Wennborgf4ad2322012-08-28 15:44:30 +00005298static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
5299 if (!isa<ImplicitCastExpr>(Ex))
5300 return false;
5301
5302 Expr *InnerE = Ex->IgnoreParenImpCasts();
5303 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
5304 const Type *Source =
5305 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5306 if (Target->isDependentType())
5307 return false;
5308
5309 const BuiltinType *FloatCandidateBT =
5310 dyn_cast<BuiltinType>(ToBool ? Source : Target);
5311 const Type *BoolCandidateType = ToBool ? Target : Source;
5312
5313 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
5314 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
5315}
5316
5317void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
5318 SourceLocation CC) {
5319 unsigned NumArgs = TheCall->getNumArgs();
5320 for (unsigned i = 0; i < NumArgs; ++i) {
5321 Expr *CurrA = TheCall->getArg(i);
5322 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
5323 continue;
5324
5325 bool IsSwapped = ((i > 0) &&
5326 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
5327 IsSwapped |= ((i < (NumArgs - 1)) &&
5328 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
5329 if (IsSwapped) {
5330 // Warn on this floating-point to bool conversion.
5331 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
5332 CurrA->getType(), CC,
5333 diag::warn_impcast_floating_point_to_bool);
5334 }
5335 }
5336}
5337
John McCallcc7e5bf2010-05-06 08:58:33 +00005338void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005339 SourceLocation CC, bool *ICContext = 0) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005340 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00005341
John McCallcc7e5bf2010-05-06 08:58:33 +00005342 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
5343 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
5344 if (Source == Target) return;
5345 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00005346
Chandler Carruthc22845a2011-07-26 05:40:03 +00005347 // If the conversion context location is invalid don't complain. We also
5348 // don't want to emit a warning if the issue occurs from the expansion of
5349 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
5350 // delay this check as long as possible. Once we detect we are in that
5351 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005352 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00005353 return;
5354
Richard Trieu021baa32011-09-23 20:10:00 +00005355 // Diagnose implicit casts to bool.
5356 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
5357 if (isa<StringLiteral>(E))
5358 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00005359 // and expressions, for instance, assert(0 && "error here"), are
5360 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00005361 return DiagnoseImpCast(S, E, T, CC,
5362 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00005363 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
5364 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
5365 // This covers the literal expressions that evaluate to Objective-C
5366 // objects.
5367 return DiagnoseImpCast(S, E, T, CC,
5368 diag::warn_impcast_objective_c_literal_to_bool);
5369 }
Lang Hamesdf5c1212011-12-05 20:49:50 +00005370 if (Source->isFunctionType()) {
5371 // Warn on function to bool. Checks free functions and static member
5372 // functions. Weakly imported functions are excluded from the check,
5373 // since it's common to test their value to check whether the linker
5374 // found a definition for them.
5375 ValueDecl *D = 0;
5376 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
5377 D = R->getDecl();
5378 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
5379 D = M->getMemberDecl();
5380 }
5381
5382 if (D && !D->isWeak()) {
Richard Trieu5f623222011-12-06 04:48:01 +00005383 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
5384 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
5385 << F << E->getSourceRange() << SourceRange(CC);
David Blaikie10eb4b62011-12-09 21:42:37 +00005386 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
5387 << FixItHint::CreateInsertion(E->getExprLoc(), "&");
5388 QualType ReturnType;
5389 UnresolvedSet<4> NonTemplateOverloads;
David Blaikiee5323aa2013-06-21 23:54:45 +00005390 S.tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
David Blaikie10eb4b62011-12-09 21:42:37 +00005391 if (!ReturnType.isNull()
5392 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
5393 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
5394 << FixItHint::CreateInsertion(
5395 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu5f623222011-12-06 04:48:01 +00005396 return;
5397 }
Lang Hamesdf5c1212011-12-05 20:49:50 +00005398 }
5399 }
Richard Trieu021baa32011-09-23 20:10:00 +00005400 }
John McCall263a48b2010-01-04 23:31:57 +00005401
5402 // Strip vector types.
5403 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005404 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005405 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005406 return;
John McCallacf0ee52010-10-08 02:01:28 +00005407 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005408 }
Chris Lattneree7286f2011-06-14 04:51:15 +00005409
5410 // If the vector cast is cast between two vectors of the same size, it is
5411 // a bitcast, not a conversion.
5412 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
5413 return;
John McCall263a48b2010-01-04 23:31:57 +00005414
5415 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
5416 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
5417 }
5418
5419 // Strip complex types.
5420 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005421 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005422 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005423 return;
5424
John McCallacf0ee52010-10-08 02:01:28 +00005425 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005426 }
John McCall263a48b2010-01-04 23:31:57 +00005427
5428 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
5429 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
5430 }
5431
5432 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
5433 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
5434
5435 // If the source is floating point...
5436 if (SourceBT && SourceBT->isFloatingPoint()) {
5437 // ...and the target is floating point...
5438 if (TargetBT && TargetBT->isFloatingPoint()) {
5439 // ...then warn if we're dropping FP rank.
5440
5441 // Builtin FP kinds are ordered by increasing FP rank.
5442 if (SourceBT->getKind() > TargetBT->getKind()) {
5443 // Don't warn about float constants that are precisely
5444 // representable in the target type.
5445 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00005446 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00005447 // Value might be a float, a float vector, or a float complex.
5448 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00005449 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
5450 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00005451 return;
5452 }
5453
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005454 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005455 return;
5456
John McCallacf0ee52010-10-08 02:01:28 +00005457 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall263a48b2010-01-04 23:31:57 +00005458 }
5459 return;
5460 }
5461
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005462 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00005463 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005464 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005465 return;
5466
Chandler Carruth22c7a792011-02-17 11:05:49 +00005467 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00005468 // We also want to warn on, e.g., "int i = -1.234"
5469 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
5470 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
5471 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
5472
Chandler Carruth016ef402011-04-10 08:36:24 +00005473 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
5474 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00005475 } else {
5476 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
5477 }
5478 }
John McCall263a48b2010-01-04 23:31:57 +00005479
Hans Wennborgf4ad2322012-08-28 15:44:30 +00005480 // If the target is bool, warn if expr is a function or method call.
5481 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
5482 isa<CallExpr>(E)) {
5483 // Check last argument of function call to see if it is an
5484 // implicit cast from a type matching the type the result
5485 // is being cast to.
5486 CallExpr *CEx = cast<CallExpr>(E);
5487 unsigned NumArgs = CEx->getNumArgs();
5488 if (NumArgs > 0) {
5489 Expr *LastA = CEx->getArg(NumArgs - 1);
5490 Expr *InnerE = LastA->IgnoreParenImpCasts();
5491 const Type *InnerType =
5492 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5493 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
5494 // Warn on this floating-point to bool conversion
5495 DiagnoseImpCast(S, E, T, CC,
5496 diag::warn_impcast_floating_point_to_bool);
5497 }
5498 }
5499 }
John McCall263a48b2010-01-04 23:31:57 +00005500 return;
5501 }
5502
Richard Trieubeaf3452011-05-29 19:59:02 +00005503 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
David Blaikie9366d2b2012-06-19 21:19:06 +00005504 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
David Blaikiea1edff02012-11-08 00:41:20 +00005505 && !Target->isBlockPointerType() && !Target->isMemberPointerType()
David Blaikiebcd4b552013-02-16 00:56:22 +00005506 && Target->isScalarType() && !Target->isNullPtrType()) {
David Blaikieae12b182012-03-16 20:30:12 +00005507 SourceLocation Loc = E->getSourceRange().getBegin();
5508 if (Loc.isMacroID())
5509 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
David Blaikie18e9ac72012-05-15 21:57:38 +00005510 if (!Loc.isMacroID() || CC.isMacroID())
5511 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
5512 << T << clang::SourceRange(CC)
Richard Smithf7ec86a2013-09-20 00:27:40 +00005513 << FixItHint::CreateReplacement(Loc,
5514 S.getFixItZeroLiteralForType(T, Loc));
Richard Trieubeaf3452011-05-29 19:59:02 +00005515 }
5516
David Blaikie9366d2b2012-06-19 21:19:06 +00005517 if (!Source->isIntegerType() || !Target->isIntegerType())
5518 return;
5519
David Blaikie7555b6a2012-05-15 16:56:36 +00005520 // TODO: remove this early return once the false positives for constant->bool
5521 // in templates, macros, etc, are reduced or removed.
5522 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
5523 return;
5524
John McCallcc7e5bf2010-05-06 08:58:33 +00005525 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00005526 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00005527
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005528 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00005529 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005530 // TODO: this should happen for bitfield stores, too.
5531 llvm::APSInt Value(32);
5532 if (E->isIntegerConstantExpr(Value, S.Context)) {
5533 if (S.SourceMgr.isInSystemMacro(CC))
5534 return;
5535
John McCall18a2c2c2010-11-09 22:22:12 +00005536 std::string PrettySourceValue = Value.toString(10);
5537 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005538
Ted Kremenek33ba9952011-10-22 02:37:33 +00005539 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5540 S.PDiag(diag::warn_impcast_integer_precision_constant)
5541 << PrettySourceValue << PrettyTargetValue
5542 << E->getType() << T << E->getSourceRange()
5543 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00005544 return;
5545 }
5546
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005547 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
5548 if (S.SourceMgr.isInSystemMacro(CC))
5549 return;
5550
David Blaikie9455da02012-04-12 22:40:54 +00005551 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00005552 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
5553 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00005554 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00005555 }
5556
5557 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
5558 (!TargetRange.NonNegative && SourceRange.NonNegative &&
5559 SourceRange.Width == TargetRange.Width)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005560
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005561 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005562 return;
5563
John McCallcc7e5bf2010-05-06 08:58:33 +00005564 unsigned DiagID = diag::warn_impcast_integer_sign;
5565
5566 // Traditionally, gcc has warned about this under -Wsign-compare.
5567 // We also want to warn about it in -Wconversion.
5568 // So if -Wconversion is off, use a completely identical diagnostic
5569 // in the sign-compare group.
5570 // The conditional-checking code will
5571 if (ICContext) {
5572 DiagID = diag::warn_impcast_integer_sign_conditional;
5573 *ICContext = true;
5574 }
5575
John McCallacf0ee52010-10-08 02:01:28 +00005576 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00005577 }
5578
Douglas Gregora78f1932011-02-22 02:45:07 +00005579 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00005580 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
5581 // type, to give us better diagnostics.
5582 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005583 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00005584 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5585 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
5586 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
5587 SourceType = S.Context.getTypeDeclType(Enum);
5588 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
5589 }
5590 }
5591
Douglas Gregora78f1932011-02-22 02:45:07 +00005592 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
5593 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00005594 if (SourceEnum->getDecl()->hasNameForLinkage() &&
5595 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005596 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005597 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005598 return;
5599
Douglas Gregor364f7db2011-03-12 00:14:31 +00005600 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00005601 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005602 }
Douglas Gregora78f1932011-02-22 02:45:07 +00005603
John McCall263a48b2010-01-04 23:31:57 +00005604 return;
5605}
5606
David Blaikie18e9ac72012-05-15 21:57:38 +00005607void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5608 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00005609
5610void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00005611 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005612 E = E->IgnoreParenImpCasts();
5613
5614 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00005615 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00005616
John McCallacf0ee52010-10-08 02:01:28 +00005617 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005618 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00005619 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00005620 return;
5621}
5622
David Blaikie18e9ac72012-05-15 21:57:38 +00005623void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5624 SourceLocation CC, QualType T) {
John McCallacf0ee52010-10-08 02:01:28 +00005625 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005626
5627 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00005628 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
5629 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00005630
5631 // If -Wconversion would have warned about either of the candidates
5632 // for a signedness conversion to the context type...
5633 if (!Suspicious) return;
5634
5635 // ...but it's currently ignored...
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00005636 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
5637 CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00005638 return;
5639
John McCallcc7e5bf2010-05-06 08:58:33 +00005640 // ...then check whether it would have warned about either of the
5641 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00005642 if (E->getType() == T) return;
5643
5644 Suspicious = false;
5645 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
5646 E->getType(), CC, &Suspicious);
5647 if (!Suspicious)
5648 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00005649 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00005650}
5651
5652/// AnalyzeImplicitConversions - Find and report any interesting
5653/// implicit conversions in the given expression. There are a couple
5654/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00005655void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005656 QualType T = OrigE->getType();
5657 Expr *E = OrigE->IgnoreParenImpCasts();
5658
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00005659 if (E->isTypeDependent() || E->isValueDependent())
5660 return;
5661
John McCallcc7e5bf2010-05-06 08:58:33 +00005662 // For conditional operators, we analyze the arguments as if they
5663 // were being fed directly into the output.
5664 if (isa<ConditionalOperator>(E)) {
5665 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00005666 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00005667 return;
5668 }
5669
Hans Wennborgf4ad2322012-08-28 15:44:30 +00005670 // Check implicit argument conversions for function calls.
5671 if (CallExpr *Call = dyn_cast<CallExpr>(E))
5672 CheckImplicitArgumentConversions(S, Call, CC);
5673
John McCallcc7e5bf2010-05-06 08:58:33 +00005674 // Go ahead and check any implicit conversions we might have skipped.
5675 // The non-canonical typecheck is just an optimization;
5676 // CheckImplicitConversion will filter out dead implicit conversions.
5677 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00005678 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005679
5680 // Now continue drilling into this expression.
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00005681
5682 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00005683 if (POE->getResultExpr())
5684 E = POE->getResultExpr();
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00005685 }
5686
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00005687 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5688 return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
5689
John McCallcc7e5bf2010-05-06 08:58:33 +00005690 // Skip past explicit casts.
5691 if (isa<ExplicitCastExpr>(E)) {
5692 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00005693 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005694 }
5695
John McCalld2a53122010-11-09 23:24:47 +00005696 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5697 // Do a somewhat different check with comparison operators.
5698 if (BO->isComparisonOp())
5699 return AnalyzeComparison(S, BO);
5700
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005701 // And with simple assignments.
5702 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00005703 return AnalyzeAssignment(S, BO);
5704 }
John McCallcc7e5bf2010-05-06 08:58:33 +00005705
5706 // These break the otherwise-useful invariant below. Fortunately,
5707 // we don't really need to recurse into them, because any internal
5708 // expressions should have been analyzed already when they were
5709 // built into statements.
5710 if (isa<StmtExpr>(E)) return;
5711
5712 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00005713 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00005714
5715 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00005716 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00005717 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00005718 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Richard Trieu021baa32011-09-23 20:10:00 +00005719 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor73456262012-02-09 10:18:50 +00005720 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00005721 if (!ChildExpr)
5722 continue;
5723
Richard Trieu955231d2014-01-25 01:10:35 +00005724 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00005725 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00005726 // Ignore checking string literals that are in logical and operators.
5727 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00005728 continue;
5729 AnalyzeImplicitConversions(S, ChildExpr, CC);
5730 }
John McCallcc7e5bf2010-05-06 08:58:33 +00005731}
5732
5733} // end anonymous namespace
5734
5735/// Diagnoses "dangerous" implicit conversions within the given
5736/// expression (which is a full expression). Implements -Wconversion
5737/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00005738///
5739/// \param CC the "context" location of the implicit conversion, i.e.
5740/// the most location of the syntactic entity requiring the implicit
5741/// conversion
5742void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005743 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00005744 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00005745 return;
5746
5747 // Don't diagnose for value- or type-dependent expressions.
5748 if (E->isTypeDependent() || E->isValueDependent())
5749 return;
5750
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00005751 // Check for array bounds violations in cases where the check isn't triggered
5752 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
5753 // ArraySubscriptExpr is on the RHS of a variable initialization.
5754 CheckArrayAccess(E);
5755
John McCallacf0ee52010-10-08 02:01:28 +00005756 // This is not the right CC for (e.g.) a variable initialization.
5757 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005758}
5759
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00005760/// Diagnose when expression is an integer constant expression and its evaluation
5761/// results in integer overflow
5762void Sema::CheckForIntOverflow (Expr *E) {
Richard Smithe9ff7702013-11-05 22:23:30 +00005763 if (isa<BinaryOperator>(E->IgnoreParens()))
5764 E->EvaluateForOverflow(Context);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00005765}
5766
Richard Smithc406cb72013-01-17 01:17:56 +00005767namespace {
5768/// \brief Visitor for expressions which looks for unsequenced operations on the
5769/// same object.
5770class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00005771 typedef EvaluatedExprVisitor<SequenceChecker> Base;
5772
Richard Smithc406cb72013-01-17 01:17:56 +00005773 /// \brief A tree of sequenced regions within an expression. Two regions are
5774 /// unsequenced if one is an ancestor or a descendent of the other. When we
5775 /// finish processing an expression with sequencing, such as a comma
5776 /// expression, we fold its tree nodes into its parent, since they are
5777 /// unsequenced with respect to nodes we will visit later.
5778 class SequenceTree {
5779 struct Value {
5780 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
5781 unsigned Parent : 31;
5782 bool Merged : 1;
5783 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00005784 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00005785
5786 public:
5787 /// \brief A region within an expression which may be sequenced with respect
5788 /// to some other region.
5789 class Seq {
5790 explicit Seq(unsigned N) : Index(N) {}
5791 unsigned Index;
5792 friend class SequenceTree;
5793 public:
5794 Seq() : Index(0) {}
5795 };
5796
5797 SequenceTree() { Values.push_back(Value(0)); }
5798 Seq root() const { return Seq(0); }
5799
5800 /// \brief Create a new sequence of operations, which is an unsequenced
5801 /// subset of \p Parent. This sequence of operations is sequenced with
5802 /// respect to other children of \p Parent.
5803 Seq allocate(Seq Parent) {
5804 Values.push_back(Value(Parent.Index));
5805 return Seq(Values.size() - 1);
5806 }
5807
5808 /// \brief Merge a sequence of operations into its parent.
5809 void merge(Seq S) {
5810 Values[S.Index].Merged = true;
5811 }
5812
5813 /// \brief Determine whether two operations are unsequenced. This operation
5814 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
5815 /// should have been merged into its parent as appropriate.
5816 bool isUnsequenced(Seq Cur, Seq Old) {
5817 unsigned C = representative(Cur.Index);
5818 unsigned Target = representative(Old.Index);
5819 while (C >= Target) {
5820 if (C == Target)
5821 return true;
5822 C = Values[C].Parent;
5823 }
5824 return false;
5825 }
5826
5827 private:
5828 /// \brief Pick a representative for a sequence.
5829 unsigned representative(unsigned K) {
5830 if (Values[K].Merged)
5831 // Perform path compression as we go.
5832 return Values[K].Parent = representative(Values[K].Parent);
5833 return K;
5834 }
5835 };
5836
5837 /// An object for which we can track unsequenced uses.
5838 typedef NamedDecl *Object;
5839
5840 /// Different flavors of object usage which we track. We only track the
5841 /// least-sequenced usage of each kind.
5842 enum UsageKind {
5843 /// A read of an object. Multiple unsequenced reads are OK.
5844 UK_Use,
5845 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00005846 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00005847 UK_ModAsValue,
5848 /// A modification of an object which is not sequenced before the value
5849 /// computation of the expression, such as n++.
5850 UK_ModAsSideEffect,
5851
5852 UK_Count = UK_ModAsSideEffect + 1
5853 };
5854
5855 struct Usage {
5856 Usage() : Use(0), Seq() {}
5857 Expr *Use;
5858 SequenceTree::Seq Seq;
5859 };
5860
5861 struct UsageInfo {
5862 UsageInfo() : Diagnosed(false) {}
5863 Usage Uses[UK_Count];
5864 /// Have we issued a diagnostic for this variable already?
5865 bool Diagnosed;
5866 };
5867 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
5868
5869 Sema &SemaRef;
5870 /// Sequenced regions within the expression.
5871 SequenceTree Tree;
5872 /// Declaration modifications and references which we have seen.
5873 UsageInfoMap UsageMap;
5874 /// The region we are currently within.
5875 SequenceTree::Seq Region;
5876 /// Filled in with declarations which were modified as a side-effect
5877 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00005878 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00005879 /// Expressions to check later. We defer checking these to reduce
5880 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00005881 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00005882
5883 /// RAII object wrapping the visitation of a sequenced subexpression of an
5884 /// expression. At the end of this process, the side-effects of the evaluation
5885 /// become sequenced with respect to the value computation of the result, so
5886 /// we downgrade any UK_ModAsSideEffect within the evaluation to
5887 /// UK_ModAsValue.
5888 struct SequencedSubexpression {
5889 SequencedSubexpression(SequenceChecker &Self)
5890 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
5891 Self.ModAsSideEffect = &ModAsSideEffect;
5892 }
5893 ~SequencedSubexpression() {
5894 for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) {
5895 UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first];
5896 U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second;
5897 Self.addUsage(U, ModAsSideEffect[I].first,
5898 ModAsSideEffect[I].second.Use, UK_ModAsValue);
5899 }
5900 Self.ModAsSideEffect = OldModAsSideEffect;
5901 }
5902
5903 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00005904 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
5905 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00005906 };
5907
Richard Smith40238f02013-06-20 22:21:56 +00005908 /// RAII object wrapping the visitation of a subexpression which we might
5909 /// choose to evaluate as a constant. If any subexpression is evaluated and
5910 /// found to be non-constant, this allows us to suppress the evaluation of
5911 /// the outer expression.
5912 class EvaluationTracker {
5913 public:
5914 EvaluationTracker(SequenceChecker &Self)
5915 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
5916 Self.EvalTracker = this;
5917 }
5918 ~EvaluationTracker() {
5919 Self.EvalTracker = Prev;
5920 if (Prev)
5921 Prev->EvalOK &= EvalOK;
5922 }
5923
5924 bool evaluate(const Expr *E, bool &Result) {
5925 if (!EvalOK || E->isValueDependent())
5926 return false;
5927 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
5928 return EvalOK;
5929 }
5930
5931 private:
5932 SequenceChecker &Self;
5933 EvaluationTracker *Prev;
5934 bool EvalOK;
5935 } *EvalTracker;
5936
Richard Smithc406cb72013-01-17 01:17:56 +00005937 /// \brief Find the object which is produced by the specified expression,
5938 /// if any.
5939 Object getObject(Expr *E, bool Mod) const {
5940 E = E->IgnoreParenCasts();
5941 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5942 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
5943 return getObject(UO->getSubExpr(), Mod);
5944 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5945 if (BO->getOpcode() == BO_Comma)
5946 return getObject(BO->getRHS(), Mod);
5947 if (Mod && BO->isAssignmentOp())
5948 return getObject(BO->getLHS(), Mod);
5949 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
5950 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
5951 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
5952 return ME->getMemberDecl();
5953 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5954 // FIXME: If this is a reference, map through to its value.
5955 return DRE->getDecl();
5956 return 0;
5957 }
5958
5959 /// \brief Note that an object was modified or used by an expression.
5960 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
5961 Usage &U = UI.Uses[UK];
5962 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
5963 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
5964 ModAsSideEffect->push_back(std::make_pair(O, U));
5965 U.Use = Ref;
5966 U.Seq = Region;
5967 }
5968 }
5969 /// \brief Check whether a modification or use conflicts with a prior usage.
5970 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
5971 bool IsModMod) {
5972 if (UI.Diagnosed)
5973 return;
5974
5975 const Usage &U = UI.Uses[OtherKind];
5976 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
5977 return;
5978
5979 Expr *Mod = U.Use;
5980 Expr *ModOrUse = Ref;
5981 if (OtherKind == UK_Use)
5982 std::swap(Mod, ModOrUse);
5983
5984 SemaRef.Diag(Mod->getExprLoc(),
5985 IsModMod ? diag::warn_unsequenced_mod_mod
5986 : diag::warn_unsequenced_mod_use)
5987 << O << SourceRange(ModOrUse->getExprLoc());
5988 UI.Diagnosed = true;
5989 }
5990
5991 void notePreUse(Object O, Expr *Use) {
5992 UsageInfo &U = UsageMap[O];
5993 // Uses conflict with other modifications.
5994 checkUsage(O, U, Use, UK_ModAsValue, false);
5995 }
5996 void notePostUse(Object O, Expr *Use) {
5997 UsageInfo &U = UsageMap[O];
5998 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
5999 addUsage(U, O, Use, UK_Use);
6000 }
6001
6002 void notePreMod(Object O, Expr *Mod) {
6003 UsageInfo &U = UsageMap[O];
6004 // Modifications conflict with other modifications and with uses.
6005 checkUsage(O, U, Mod, UK_ModAsValue, true);
6006 checkUsage(O, U, Mod, UK_Use, false);
6007 }
6008 void notePostMod(Object O, Expr *Use, UsageKind UK) {
6009 UsageInfo &U = UsageMap[O];
6010 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
6011 addUsage(U, O, Use, UK);
6012 }
6013
6014public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006015 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
6016 : Base(S.Context), SemaRef(S), Region(Tree.root()), ModAsSideEffect(0),
6017 WorkList(WorkList), EvalTracker(0) {
Richard Smithc406cb72013-01-17 01:17:56 +00006018 Visit(E);
6019 }
6020
6021 void VisitStmt(Stmt *S) {
6022 // Skip all statements which aren't expressions for now.
6023 }
6024
6025 void VisitExpr(Expr *E) {
6026 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00006027 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00006028 }
6029
6030 void VisitCastExpr(CastExpr *E) {
6031 Object O = Object();
6032 if (E->getCastKind() == CK_LValueToRValue)
6033 O = getObject(E->getSubExpr(), false);
6034
6035 if (O)
6036 notePreUse(O, E);
6037 VisitExpr(E);
6038 if (O)
6039 notePostUse(O, E);
6040 }
6041
6042 void VisitBinComma(BinaryOperator *BO) {
6043 // C++11 [expr.comma]p1:
6044 // Every value computation and side effect associated with the left
6045 // expression is sequenced before every value computation and side
6046 // effect associated with the right expression.
6047 SequenceTree::Seq LHS = Tree.allocate(Region);
6048 SequenceTree::Seq RHS = Tree.allocate(Region);
6049 SequenceTree::Seq OldRegion = Region;
6050
6051 {
6052 SequencedSubexpression SeqLHS(*this);
6053 Region = LHS;
6054 Visit(BO->getLHS());
6055 }
6056
6057 Region = RHS;
6058 Visit(BO->getRHS());
6059
6060 Region = OldRegion;
6061
6062 // Forget that LHS and RHS are sequenced. They are both unsequenced
6063 // with respect to other stuff.
6064 Tree.merge(LHS);
6065 Tree.merge(RHS);
6066 }
6067
6068 void VisitBinAssign(BinaryOperator *BO) {
6069 // The modification is sequenced after the value computation of the LHS
6070 // and RHS, so check it before inspecting the operands and update the
6071 // map afterwards.
6072 Object O = getObject(BO->getLHS(), true);
6073 if (!O)
6074 return VisitExpr(BO);
6075
6076 notePreMod(O, BO);
6077
6078 // C++11 [expr.ass]p7:
6079 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
6080 // only once.
6081 //
6082 // Therefore, for a compound assignment operator, O is considered used
6083 // everywhere except within the evaluation of E1 itself.
6084 if (isa<CompoundAssignOperator>(BO))
6085 notePreUse(O, BO);
6086
6087 Visit(BO->getLHS());
6088
6089 if (isa<CompoundAssignOperator>(BO))
6090 notePostUse(O, BO);
6091
6092 Visit(BO->getRHS());
6093
Richard Smith83e37bee2013-06-26 23:16:51 +00006094 // C++11 [expr.ass]p1:
6095 // the assignment is sequenced [...] before the value computation of the
6096 // assignment expression.
6097 // C11 6.5.16/3 has no such rule.
6098 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6099 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00006100 }
6101 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
6102 VisitBinAssign(CAO);
6103 }
6104
6105 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
6106 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
6107 void VisitUnaryPreIncDec(UnaryOperator *UO) {
6108 Object O = getObject(UO->getSubExpr(), true);
6109 if (!O)
6110 return VisitExpr(UO);
6111
6112 notePreMod(O, UO);
6113 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00006114 // C++11 [expr.pre.incr]p1:
6115 // the expression ++x is equivalent to x+=1
6116 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6117 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00006118 }
6119
6120 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
6121 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
6122 void VisitUnaryPostIncDec(UnaryOperator *UO) {
6123 Object O = getObject(UO->getSubExpr(), true);
6124 if (!O)
6125 return VisitExpr(UO);
6126
6127 notePreMod(O, UO);
6128 Visit(UO->getSubExpr());
6129 notePostMod(O, UO, UK_ModAsSideEffect);
6130 }
6131
6132 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
6133 void VisitBinLOr(BinaryOperator *BO) {
6134 // The side-effects of the LHS of an '&&' are sequenced before the
6135 // value computation of the RHS, and hence before the value computation
6136 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
6137 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00006138 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00006139 {
6140 SequencedSubexpression Sequenced(*this);
6141 Visit(BO->getLHS());
6142 }
6143
6144 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006145 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00006146 if (!Result)
6147 Visit(BO->getRHS());
6148 } else {
6149 // Check for unsequenced operations in the RHS, treating it as an
6150 // entirely separate evaluation.
6151 //
6152 // FIXME: If there are operations in the RHS which are unsequenced
6153 // with respect to operations outside the RHS, and those operations
6154 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00006155 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00006156 }
Richard Smithc406cb72013-01-17 01:17:56 +00006157 }
6158 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00006159 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00006160 {
6161 SequencedSubexpression Sequenced(*this);
6162 Visit(BO->getLHS());
6163 }
6164
6165 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006166 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00006167 if (Result)
6168 Visit(BO->getRHS());
6169 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00006170 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00006171 }
Richard Smithc406cb72013-01-17 01:17:56 +00006172 }
6173
6174 // Only visit the condition, unless we can be sure which subexpression will
6175 // be chosen.
6176 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00006177 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00006178 {
6179 SequencedSubexpression Sequenced(*this);
6180 Visit(CO->getCond());
6181 }
Richard Smithc406cb72013-01-17 01:17:56 +00006182
6183 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006184 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00006185 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00006186 else {
Richard Smithd33f5202013-01-17 23:18:09 +00006187 WorkList.push_back(CO->getTrueExpr());
6188 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00006189 }
Richard Smithc406cb72013-01-17 01:17:56 +00006190 }
6191
Richard Smithe3dbfe02013-06-30 10:40:20 +00006192 void VisitCallExpr(CallExpr *CE) {
6193 // C++11 [intro.execution]p15:
6194 // When calling a function [...], every value computation and side effect
6195 // associated with any argument expression, or with the postfix expression
6196 // designating the called function, is sequenced before execution of every
6197 // expression or statement in the body of the function [and thus before
6198 // the value computation of its result].
6199 SequencedSubexpression Sequenced(*this);
6200 Base::VisitCallExpr(CE);
6201
6202 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
6203 }
6204
Richard Smithc406cb72013-01-17 01:17:56 +00006205 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00006206 // This is a call, so all subexpressions are sequenced before the result.
6207 SequencedSubexpression Sequenced(*this);
6208
Richard Smithc406cb72013-01-17 01:17:56 +00006209 if (!CCE->isListInitialization())
6210 return VisitExpr(CCE);
6211
6212 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006213 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00006214 SequenceTree::Seq Parent = Region;
6215 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
6216 E = CCE->arg_end();
6217 I != E; ++I) {
6218 Region = Tree.allocate(Parent);
6219 Elts.push_back(Region);
6220 Visit(*I);
6221 }
6222
6223 // Forget that the initializers are sequenced.
6224 Region = Parent;
6225 for (unsigned I = 0; I < Elts.size(); ++I)
6226 Tree.merge(Elts[I]);
6227 }
6228
6229 void VisitInitListExpr(InitListExpr *ILE) {
6230 if (!SemaRef.getLangOpts().CPlusPlus11)
6231 return VisitExpr(ILE);
6232
6233 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006234 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00006235 SequenceTree::Seq Parent = Region;
6236 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
6237 Expr *E = ILE->getInit(I);
6238 if (!E) continue;
6239 Region = Tree.allocate(Parent);
6240 Elts.push_back(Region);
6241 Visit(E);
6242 }
6243
6244 // Forget that the initializers are sequenced.
6245 Region = Parent;
6246 for (unsigned I = 0; I < Elts.size(); ++I)
6247 Tree.merge(Elts[I]);
6248 }
6249};
6250}
6251
6252void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006253 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00006254 WorkList.push_back(E);
6255 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00006256 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00006257 SequenceChecker(*this, Item, WorkList);
6258 }
Richard Smithc406cb72013-01-17 01:17:56 +00006259}
6260
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006261void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
6262 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00006263 CheckImplicitConversions(E, CheckLoc);
6264 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006265 if (!IsConstexpr && !E->isValueDependent())
6266 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00006267}
6268
John McCall1f425642010-11-11 03:21:53 +00006269void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
6270 FieldDecl *BitField,
6271 Expr *Init) {
6272 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
6273}
6274
Mike Stump0c2ec772010-01-21 03:59:47 +00006275/// CheckParmsForFunctionDef - Check that the parameters of the given
6276/// function are appropriate for the definition of a function. This
6277/// takes care of any checks that cannot be performed on the
6278/// declaration itself, e.g., that the types of each of the function
6279/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00006280bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
6281 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00006282 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00006283 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00006284 for (; P != PEnd; ++P) {
6285 ParmVarDecl *Param = *P;
6286
Mike Stump0c2ec772010-01-21 03:59:47 +00006287 // C99 6.7.5.3p4: the parameters in a parameter type list in a
6288 // function declarator that is part of a function definition of
6289 // that function shall not have incomplete type.
6290 //
6291 // This is also C++ [dcl.fct]p6.
6292 if (!Param->isInvalidDecl() &&
6293 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00006294 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00006295 Param->setInvalidDecl();
6296 HasInvalidParm = true;
6297 }
6298
6299 // C99 6.9.1p5: If the declarator includes a parameter type list, the
6300 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00006301 if (CheckParameterNames &&
6302 Param->getIdentifier() == 0 &&
Mike Stump0c2ec772010-01-21 03:59:47 +00006303 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00006304 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00006305 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00006306
6307 // C99 6.7.5.3p12:
6308 // If the function declarator is not part of a definition of that
6309 // function, parameters may have incomplete type and may use the [*]
6310 // notation in their sequences of declarator specifiers to specify
6311 // variable length array types.
6312 QualType PType = Param->getOriginalType();
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00006313 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigdeb55d52010-02-01 05:02:49 +00006314 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitb3318502013-03-01 21:41:22 +00006315 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigdeb55d52010-02-01 05:02:49 +00006316 // information is added for it.
6317 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00006318 break;
Sam Weinigdeb55d52010-02-01 05:02:49 +00006319 }
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00006320 PType= AT->getElementType();
Sam Weinigdeb55d52010-02-01 05:02:49 +00006321 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00006322
6323 // MSVC destroys objects passed by value in the callee. Therefore a
6324 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00006325 // object's destructor. However, we don't perform any direct access check
6326 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00006327 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
6328 .getCXXABI()
6329 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00006330 if (!Param->isInvalidDecl()) {
6331 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
6332 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
6333 if (!ClassDecl->isInvalidDecl() &&
6334 !ClassDecl->hasIrrelevantDestructor() &&
6335 !ClassDecl->isDependentContext()) {
6336 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
6337 MarkFunctionReferenced(Param->getLocation(), Destructor);
6338 DiagnoseUseOfDecl(Destructor, Param->getLocation());
6339 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00006340 }
6341 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00006342 }
Mike Stump0c2ec772010-01-21 03:59:47 +00006343 }
6344
6345 return HasInvalidParm;
6346}
John McCall2b5c1b22010-08-12 21:44:57 +00006347
6348/// CheckCastAlign - Implements -Wcast-align, which warns when a
6349/// pointer cast increases the alignment requirements.
6350void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
6351 // This is actually a lot of work to potentially be doing on every
6352 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00006353 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
6354 TRange.getBegin())
David Blaikie9c902b52011-09-25 23:23:43 +00006355 == DiagnosticsEngine::Ignored)
John McCall2b5c1b22010-08-12 21:44:57 +00006356 return;
6357
6358 // Ignore dependent types.
6359 if (T->isDependentType() || Op->getType()->isDependentType())
6360 return;
6361
6362 // Require that the destination be a pointer type.
6363 const PointerType *DestPtr = T->getAs<PointerType>();
6364 if (!DestPtr) return;
6365
6366 // If the destination has alignment 1, we're done.
6367 QualType DestPointee = DestPtr->getPointeeType();
6368 if (DestPointee->isIncompleteType()) return;
6369 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
6370 if (DestAlign.isOne()) return;
6371
6372 // Require that the source be a pointer type.
6373 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
6374 if (!SrcPtr) return;
6375 QualType SrcPointee = SrcPtr->getPointeeType();
6376
6377 // Whitelist casts from cv void*. We already implicitly
6378 // whitelisted casts to cv void*, since they have alignment 1.
6379 // Also whitelist casts involving incomplete types, which implicitly
6380 // includes 'void'.
6381 if (SrcPointee->isIncompleteType()) return;
6382
6383 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
6384 if (SrcAlign >= DestAlign) return;
6385
6386 Diag(TRange.getBegin(), diag::warn_cast_align)
6387 << Op->getType() << T
6388 << static_cast<unsigned>(SrcAlign.getQuantity())
6389 << static_cast<unsigned>(DestAlign.getQuantity())
6390 << TRange << Op->getSourceRange();
6391}
6392
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006393static const Type* getElementType(const Expr *BaseExpr) {
6394 const Type* EltType = BaseExpr->getType().getTypePtr();
6395 if (EltType->isAnyPointerType())
6396 return EltType->getPointeeType().getTypePtr();
6397 else if (EltType->isArrayType())
6398 return EltType->getBaseElementTypeUnsafe();
6399 return EltType;
6400}
6401
Chandler Carruth28389f02011-08-05 09:10:50 +00006402/// \brief Check whether this array fits the idiom of a size-one tail padded
6403/// array member of a struct.
6404///
6405/// We avoid emitting out-of-bounds access warnings for such arrays as they are
6406/// commonly used to emulate flexible arrays in C89 code.
6407static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
6408 const NamedDecl *ND) {
6409 if (Size != 1 || !ND) return false;
6410
6411 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
6412 if (!FD) return false;
6413
6414 // Don't consider sizes resulting from macro expansions or template argument
6415 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00006416
6417 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00006418 while (TInfo) {
6419 TypeLoc TL = TInfo->getTypeLoc();
6420 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00006421 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
6422 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00006423 TInfo = TDL->getTypeSourceInfo();
6424 continue;
6425 }
David Blaikie6adc78e2013-02-18 22:06:02 +00006426 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
6427 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00006428 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
6429 return false;
6430 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00006431 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00006432 }
Chandler Carruth28389f02011-08-05 09:10:50 +00006433
6434 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00006435 if (!RD) return false;
6436 if (RD->isUnion()) return false;
6437 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
6438 if (!CRD->isStandardLayout()) return false;
6439 }
Chandler Carruth28389f02011-08-05 09:10:50 +00006440
Benjamin Kramer8c543672011-08-06 03:04:42 +00006441 // See if this is the last field decl in the record.
6442 const Decl *D = FD;
6443 while ((D = D->getNextDeclInContext()))
6444 if (isa<FieldDecl>(D))
6445 return false;
6446 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00006447}
6448
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006449void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006450 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00006451 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00006452 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006453 if (IndexExpr->isValueDependent())
6454 return;
6455
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00006456 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006457 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006458 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006459 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006460 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00006461 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00006462
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006463 llvm::APSInt index;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006464 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremenek64699be2011-02-16 01:57:07 +00006465 return;
Richard Smith13f67182011-12-16 19:31:14 +00006466 if (IndexNegated)
6467 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00006468
Chandler Carruth126b1552011-08-05 08:07:29 +00006469 const NamedDecl *ND = NULL;
Chandler Carruth126b1552011-08-05 08:07:29 +00006470 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
6471 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00006472 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00006473 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00006474
Ted Kremeneke4b316c2011-02-23 23:06:04 +00006475 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00006476 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00006477 if (!size.isStrictlyPositive())
6478 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006479
6480 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00006481 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006482 // Make sure we're comparing apples to apples when comparing index to size
6483 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
6484 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00006485 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00006486 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006487 if (ptrarith_typesize != array_typesize) {
6488 // There's a cast to a different size type involved
6489 uint64_t ratio = array_typesize / ptrarith_typesize;
6490 // TODO: Be smarter about handling cases where array_typesize is not a
6491 // multiple of ptrarith_typesize
6492 if (ptrarith_typesize * ratio == array_typesize)
6493 size *= llvm::APInt(size.getBitWidth(), ratio);
6494 }
6495 }
6496
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006497 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00006498 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00006499 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00006500 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00006501
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006502 // For array subscripting the index must be less than size, but for pointer
6503 // arithmetic also allow the index (offset) to be equal to size since
6504 // computing the next address after the end of the array is legal and
6505 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00006506 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00006507 return;
6508
6509 // Also don't warn for arrays of size 1 which are members of some
6510 // structure. These are often used to approximate flexible arrays in C89
6511 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006512 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00006513 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006514
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006515 // Suppress the warning if the subscript expression (as identified by the
6516 // ']' location) and the index expression are both from macro expansions
6517 // within a system header.
6518 if (ASE) {
6519 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
6520 ASE->getRBracketLoc());
6521 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
6522 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
6523 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00006524 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006525 return;
6526 }
6527 }
6528
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006529 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006530 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006531 DiagID = diag::warn_array_index_exceeds_bounds;
6532
6533 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6534 PDiag(DiagID) << index.toString(10, true)
6535 << size.toString(10, true)
6536 << (unsigned)size.getLimitedValue(~0U)
6537 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006538 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006539 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006540 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006541 DiagID = diag::warn_ptr_arith_precedes_bounds;
6542 if (index.isNegative()) index = -index;
6543 }
6544
6545 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6546 PDiag(DiagID) << index.toString(10, true)
6547 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00006548 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00006549
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00006550 if (!ND) {
6551 // Try harder to find a NamedDecl to point at in the note.
6552 while (const ArraySubscriptExpr *ASE =
6553 dyn_cast<ArraySubscriptExpr>(BaseExpr))
6554 BaseExpr = ASE->getBase()->IgnoreParenCasts();
6555 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
6556 ND = dyn_cast<NamedDecl>(DRE->getDecl());
6557 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
6558 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
6559 }
6560
Chandler Carruth1af88f12011-02-17 21:10:52 +00006561 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006562 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
6563 PDiag(diag::note_array_index_out_of_bounds)
6564 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00006565}
6566
Ted Kremenekdf26df72011-03-01 18:41:00 +00006567void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006568 int AllowOnePastEnd = 0;
6569 while (expr) {
6570 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00006571 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006572 case Stmt::ArraySubscriptExprClass: {
6573 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006574 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006575 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00006576 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006577 }
6578 case Stmt::UnaryOperatorClass: {
6579 // Only unwrap the * and & unary operators
6580 const UnaryOperator *UO = cast<UnaryOperator>(expr);
6581 expr = UO->getSubExpr();
6582 switch (UO->getOpcode()) {
6583 case UO_AddrOf:
6584 AllowOnePastEnd++;
6585 break;
6586 case UO_Deref:
6587 AllowOnePastEnd--;
6588 break;
6589 default:
6590 return;
6591 }
6592 break;
6593 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00006594 case Stmt::ConditionalOperatorClass: {
6595 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
6596 if (const Expr *lhs = cond->getLHS())
6597 CheckArrayAccess(lhs);
6598 if (const Expr *rhs = cond->getRHS())
6599 CheckArrayAccess(rhs);
6600 return;
6601 }
6602 default:
6603 return;
6604 }
Peter Collingbourne91147592011-04-15 00:35:48 +00006605 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00006606}
John McCall31168b02011-06-15 23:02:42 +00006607
6608//===--- CHECK: Objective-C retain cycles ----------------------------------//
6609
6610namespace {
6611 struct RetainCycleOwner {
6612 RetainCycleOwner() : Variable(0), Indirect(false) {}
6613 VarDecl *Variable;
6614 SourceRange Range;
6615 SourceLocation Loc;
6616 bool Indirect;
6617
6618 void setLocsFrom(Expr *e) {
6619 Loc = e->getExprLoc();
6620 Range = e->getSourceRange();
6621 }
6622 };
6623}
6624
6625/// Consider whether capturing the given variable can possibly lead to
6626/// a retain cycle.
6627static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00006628 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00006629 // lifetime. In MRR, it's captured strongly if the variable is
6630 // __block and has an appropriate type.
6631 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
6632 return false;
6633
6634 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00006635 if (ref)
6636 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00006637 return true;
6638}
6639
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00006640static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00006641 while (true) {
6642 e = e->IgnoreParens();
6643 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
6644 switch (cast->getCastKind()) {
6645 case CK_BitCast:
6646 case CK_LValueBitCast:
6647 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00006648 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00006649 e = cast->getSubExpr();
6650 continue;
6651
John McCall31168b02011-06-15 23:02:42 +00006652 default:
6653 return false;
6654 }
6655 }
6656
6657 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
6658 ObjCIvarDecl *ivar = ref->getDecl();
6659 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
6660 return false;
6661
6662 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00006663 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00006664 return false;
6665
6666 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
6667 owner.Indirect = true;
6668 return true;
6669 }
6670
6671 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
6672 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
6673 if (!var) return false;
6674 return considerVariable(var, ref, owner);
6675 }
6676
John McCall31168b02011-06-15 23:02:42 +00006677 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
6678 if (member->isArrow()) return false;
6679
6680 // Don't count this as an indirect ownership.
6681 e = member->getBase();
6682 continue;
6683 }
6684
John McCallfe96e0b2011-11-06 09:01:30 +00006685 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
6686 // Only pay attention to pseudo-objects on property references.
6687 ObjCPropertyRefExpr *pre
6688 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
6689 ->IgnoreParens());
6690 if (!pre) return false;
6691 if (pre->isImplicitProperty()) return false;
6692 ObjCPropertyDecl *property = pre->getExplicitProperty();
6693 if (!property->isRetaining() &&
6694 !(property->getPropertyIvarDecl() &&
6695 property->getPropertyIvarDecl()->getType()
6696 .getObjCLifetime() == Qualifiers::OCL_Strong))
6697 return false;
6698
6699 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00006700 if (pre->isSuperReceiver()) {
6701 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
6702 if (!owner.Variable)
6703 return false;
6704 owner.Loc = pre->getLocation();
6705 owner.Range = pre->getSourceRange();
6706 return true;
6707 }
John McCallfe96e0b2011-11-06 09:01:30 +00006708 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
6709 ->getSourceExpr());
6710 continue;
6711 }
6712
John McCall31168b02011-06-15 23:02:42 +00006713 // Array ivars?
6714
6715 return false;
6716 }
6717}
6718
6719namespace {
6720 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
6721 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
6722 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
6723 Variable(variable), Capturer(0) {}
6724
6725 VarDecl *Variable;
6726 Expr *Capturer;
6727
6728 void VisitDeclRefExpr(DeclRefExpr *ref) {
6729 if (ref->getDecl() == Variable && !Capturer)
6730 Capturer = ref;
6731 }
6732
John McCall31168b02011-06-15 23:02:42 +00006733 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
6734 if (Capturer) return;
6735 Visit(ref->getBase());
6736 if (Capturer && ref->isFreeIvar())
6737 Capturer = ref;
6738 }
6739
6740 void VisitBlockExpr(BlockExpr *block) {
6741 // Look inside nested blocks
6742 if (block->getBlockDecl()->capturesVariable(Variable))
6743 Visit(block->getBlockDecl()->getBody());
6744 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00006745
6746 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
6747 if (Capturer) return;
6748 if (OVE->getSourceExpr())
6749 Visit(OVE->getSourceExpr());
6750 }
John McCall31168b02011-06-15 23:02:42 +00006751 };
6752}
6753
6754/// Check whether the given argument is a block which captures a
6755/// variable.
6756static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
6757 assert(owner.Variable && owner.Loc.isValid());
6758
6759 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00006760
6761 // Look through [^{...} copy] and Block_copy(^{...}).
6762 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
6763 Selector Cmd = ME->getSelector();
6764 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
6765 e = ME->getInstanceReceiver();
6766 if (!e)
6767 return 0;
6768 e = e->IgnoreParenCasts();
6769 }
6770 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
6771 if (CE->getNumArgs() == 1) {
6772 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00006773 if (Fn) {
6774 const IdentifierInfo *FnI = Fn->getIdentifier();
6775 if (FnI && FnI->isStr("_Block_copy")) {
6776 e = CE->getArg(0)->IgnoreParenCasts();
6777 }
6778 }
Jordan Rose67e887c2012-09-17 17:54:30 +00006779 }
6780 }
6781
John McCall31168b02011-06-15 23:02:42 +00006782 BlockExpr *block = dyn_cast<BlockExpr>(e);
6783 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
6784 return 0;
6785
6786 FindCaptureVisitor visitor(S.Context, owner.Variable);
6787 visitor.Visit(block->getBlockDecl()->getBody());
6788 return visitor.Capturer;
6789}
6790
6791static void diagnoseRetainCycle(Sema &S, Expr *capturer,
6792 RetainCycleOwner &owner) {
6793 assert(capturer);
6794 assert(owner.Variable && owner.Loc.isValid());
6795
6796 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
6797 << owner.Variable << capturer->getSourceRange();
6798 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
6799 << owner.Indirect << owner.Range;
6800}
6801
6802/// Check for a keyword selector that starts with the word 'add' or
6803/// 'set'.
6804static bool isSetterLikeSelector(Selector sel) {
6805 if (sel.isUnarySelector()) return false;
6806
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006807 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00006808 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00006809 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00006810 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00006811 else if (str.startswith("add")) {
6812 // Specially whitelist 'addOperationWithBlock:'.
6813 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
6814 return false;
6815 str = str.substr(3);
6816 }
John McCall31168b02011-06-15 23:02:42 +00006817 else
6818 return false;
6819
6820 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00006821 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00006822}
6823
6824/// Check a message send to see if it's likely to cause a retain cycle.
6825void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
6826 // Only check instance methods whose selector looks like a setter.
6827 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
6828 return;
6829
6830 // Try to find a variable that the receiver is strongly owned by.
6831 RetainCycleOwner owner;
6832 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00006833 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00006834 return;
6835 } else {
6836 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
6837 owner.Variable = getCurMethodDecl()->getSelfDecl();
6838 owner.Loc = msg->getSuperLoc();
6839 owner.Range = msg->getSuperLoc();
6840 }
6841
6842 // Check whether the receiver is captured by any of the arguments.
6843 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
6844 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
6845 return diagnoseRetainCycle(*this, capturer, owner);
6846}
6847
6848/// Check a property assign to see if it's likely to cause a retain cycle.
6849void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
6850 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00006851 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00006852 return;
6853
6854 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
6855 diagnoseRetainCycle(*this, capturer, owner);
6856}
6857
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00006858void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
6859 RetainCycleOwner Owner;
6860 if (!considerVariable(Var, /*DeclRefExpr=*/0, Owner))
6861 return;
6862
6863 // Because we don't have an expression for the variable, we have to set the
6864 // location explicitly here.
6865 Owner.Loc = Var->getLocation();
6866 Owner.Range = Var->getSourceRange();
6867
6868 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
6869 diagnoseRetainCycle(*this, Capturer, Owner);
6870}
6871
Ted Kremenek9304da92012-12-21 08:04:28 +00006872static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
6873 Expr *RHS, bool isProperty) {
6874 // Check if RHS is an Objective-C object literal, which also can get
6875 // immediately zapped in a weak reference. Note that we explicitly
6876 // allow ObjCStringLiterals, since those are designed to never really die.
6877 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00006878
Ted Kremenek64873352012-12-21 22:46:35 +00006879 // This enum needs to match with the 'select' in
6880 // warn_objc_arc_literal_assign (off-by-1).
6881 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
6882 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
6883 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00006884
6885 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00006886 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00006887 << (isProperty ? 0 : 1)
6888 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00006889
6890 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00006891}
6892
Ted Kremenekc1f014a2012-12-21 19:45:30 +00006893static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
6894 Qualifiers::ObjCLifetime LT,
6895 Expr *RHS, bool isProperty) {
6896 // Strip off any implicit cast added to get to the one ARC-specific.
6897 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
6898 if (cast->getCastKind() == CK_ARCConsumeObject) {
6899 S.Diag(Loc, diag::warn_arc_retained_assign)
6900 << (LT == Qualifiers::OCL_ExplicitNone)
6901 << (isProperty ? 0 : 1)
6902 << RHS->getSourceRange();
6903 return true;
6904 }
6905 RHS = cast->getSubExpr();
6906 }
6907
6908 if (LT == Qualifiers::OCL_Weak &&
6909 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
6910 return true;
6911
6912 return false;
6913}
6914
Ted Kremenekb36234d2012-12-21 08:04:20 +00006915bool Sema::checkUnsafeAssigns(SourceLocation Loc,
6916 QualType LHS, Expr *RHS) {
6917 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
6918
6919 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
6920 return false;
6921
6922 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
6923 return true;
6924
6925 return false;
6926}
6927
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00006928void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
6929 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00006930 QualType LHSType;
6931 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00006932 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00006933 ObjCPropertyRefExpr *PRE
6934 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
6935 if (PRE && !PRE->isImplicitProperty()) {
6936 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
6937 if (PD)
6938 LHSType = PD->getType();
6939 }
6940
6941 if (LHSType.isNull())
6942 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00006943
6944 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
6945
6946 if (LT == Qualifiers::OCL_Weak) {
6947 DiagnosticsEngine::Level Level =
6948 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
6949 if (Level != DiagnosticsEngine::Ignored)
6950 getCurFunction()->markSafeWeakUse(LHS);
6951 }
6952
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00006953 if (checkUnsafeAssigns(Loc, LHSType, RHS))
6954 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00006955
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00006956 // FIXME. Check for other life times.
6957 if (LT != Qualifiers::OCL_None)
6958 return;
6959
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00006960 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00006961 if (PRE->isImplicitProperty())
6962 return;
6963 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
6964 if (!PD)
6965 return;
6966
Bill Wendling44426052012-12-20 19:22:21 +00006967 unsigned Attributes = PD->getPropertyAttributes();
6968 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00006969 // when 'assign' attribute was not explicitly specified
6970 // by user, ignore it and rely on property type itself
6971 // for lifetime info.
6972 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
6973 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
6974 LHSType->isObjCRetainableType())
6975 return;
6976
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00006977 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00006978 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00006979 Diag(Loc, diag::warn_arc_retained_property_assign)
6980 << RHS->getSourceRange();
6981 return;
6982 }
6983 RHS = cast->getSubExpr();
6984 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00006985 }
Bill Wendling44426052012-12-20 19:22:21 +00006986 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00006987 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
6988 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00006989 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00006990 }
6991}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00006992
6993//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
6994
6995namespace {
6996bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
6997 SourceLocation StmtLoc,
6998 const NullStmt *Body) {
6999 // Do not warn if the body is a macro that expands to nothing, e.g:
7000 //
7001 // #define CALL(x)
7002 // if (condition)
7003 // CALL(0);
7004 //
7005 if (Body->hasLeadingEmptyMacro())
7006 return false;
7007
7008 // Get line numbers of statement and body.
7009 bool StmtLineInvalid;
7010 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
7011 &StmtLineInvalid);
7012 if (StmtLineInvalid)
7013 return false;
7014
7015 bool BodyLineInvalid;
7016 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
7017 &BodyLineInvalid);
7018 if (BodyLineInvalid)
7019 return false;
7020
7021 // Warn if null statement and body are on the same line.
7022 if (StmtLine != BodyLine)
7023 return false;
7024
7025 return true;
7026}
7027} // Unnamed namespace
7028
7029void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
7030 const Stmt *Body,
7031 unsigned DiagID) {
7032 // Since this is a syntactic check, don't emit diagnostic for template
7033 // instantiations, this just adds noise.
7034 if (CurrentInstantiationScope)
7035 return;
7036
7037 // The body should be a null statement.
7038 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
7039 if (!NBody)
7040 return;
7041
7042 // Do the usual checks.
7043 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
7044 return;
7045
7046 Diag(NBody->getSemiLoc(), DiagID);
7047 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
7048}
7049
7050void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
7051 const Stmt *PossibleBody) {
7052 assert(!CurrentInstantiationScope); // Ensured by caller
7053
7054 SourceLocation StmtLoc;
7055 const Stmt *Body;
7056 unsigned DiagID;
7057 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
7058 StmtLoc = FS->getRParenLoc();
7059 Body = FS->getBody();
7060 DiagID = diag::warn_empty_for_body;
7061 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
7062 StmtLoc = WS->getCond()->getSourceRange().getEnd();
7063 Body = WS->getBody();
7064 DiagID = diag::warn_empty_while_body;
7065 } else
7066 return; // Neither `for' nor `while'.
7067
7068 // The body should be a null statement.
7069 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
7070 if (!NBody)
7071 return;
7072
7073 // Skip expensive checks if diagnostic is disabled.
7074 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
7075 DiagnosticsEngine::Ignored)
7076 return;
7077
7078 // Do the usual checks.
7079 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
7080 return;
7081
7082 // `for(...);' and `while(...);' are popular idioms, so in order to keep
7083 // noise level low, emit diagnostics only if for/while is followed by a
7084 // CompoundStmt, e.g.:
7085 // for (int i = 0; i < n; i++);
7086 // {
7087 // a(i);
7088 // }
7089 // or if for/while is followed by a statement with more indentation
7090 // than for/while itself:
7091 // for (int i = 0; i < n; i++);
7092 // a(i);
7093 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
7094 if (!ProbableTypo) {
7095 bool BodyColInvalid;
7096 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
7097 PossibleBody->getLocStart(),
7098 &BodyColInvalid);
7099 if (BodyColInvalid)
7100 return;
7101
7102 bool StmtColInvalid;
7103 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
7104 S->getLocStart(),
7105 &StmtColInvalid);
7106 if (StmtColInvalid)
7107 return;
7108
7109 if (BodyCol > StmtCol)
7110 ProbableTypo = true;
7111 }
7112
7113 if (ProbableTypo) {
7114 Diag(NBody->getSemiLoc(), DiagID);
7115 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
7116 }
7117}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007118
7119//===--- Layout compatibility ----------------------------------------------//
7120
7121namespace {
7122
7123bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
7124
7125/// \brief Check if two enumeration types are layout-compatible.
7126bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
7127 // C++11 [dcl.enum] p8:
7128 // Two enumeration types are layout-compatible if they have the same
7129 // underlying type.
7130 return ED1->isComplete() && ED2->isComplete() &&
7131 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
7132}
7133
7134/// \brief Check if two fields are layout-compatible.
7135bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
7136 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
7137 return false;
7138
7139 if (Field1->isBitField() != Field2->isBitField())
7140 return false;
7141
7142 if (Field1->isBitField()) {
7143 // Make sure that the bit-fields are the same length.
7144 unsigned Bits1 = Field1->getBitWidthValue(C);
7145 unsigned Bits2 = Field2->getBitWidthValue(C);
7146
7147 if (Bits1 != Bits2)
7148 return false;
7149 }
7150
7151 return true;
7152}
7153
7154/// \brief Check if two standard-layout structs are layout-compatible.
7155/// (C++11 [class.mem] p17)
7156bool isLayoutCompatibleStruct(ASTContext &C,
7157 RecordDecl *RD1,
7158 RecordDecl *RD2) {
7159 // If both records are C++ classes, check that base classes match.
7160 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
7161 // If one of records is a CXXRecordDecl we are in C++ mode,
7162 // thus the other one is a CXXRecordDecl, too.
7163 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
7164 // Check number of base classes.
7165 if (D1CXX->getNumBases() != D2CXX->getNumBases())
7166 return false;
7167
7168 // Check the base classes.
7169 for (CXXRecordDecl::base_class_const_iterator
7170 Base1 = D1CXX->bases_begin(),
7171 BaseEnd1 = D1CXX->bases_end(),
7172 Base2 = D2CXX->bases_begin();
7173 Base1 != BaseEnd1;
7174 ++Base1, ++Base2) {
7175 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
7176 return false;
7177 }
7178 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
7179 // If only RD2 is a C++ class, it should have zero base classes.
7180 if (D2CXX->getNumBases() > 0)
7181 return false;
7182 }
7183
7184 // Check the fields.
7185 RecordDecl::field_iterator Field2 = RD2->field_begin(),
7186 Field2End = RD2->field_end(),
7187 Field1 = RD1->field_begin(),
7188 Field1End = RD1->field_end();
7189 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
7190 if (!isLayoutCompatible(C, *Field1, *Field2))
7191 return false;
7192 }
7193 if (Field1 != Field1End || Field2 != Field2End)
7194 return false;
7195
7196 return true;
7197}
7198
7199/// \brief Check if two standard-layout unions are layout-compatible.
7200/// (C++11 [class.mem] p18)
7201bool isLayoutCompatibleUnion(ASTContext &C,
7202 RecordDecl *RD1,
7203 RecordDecl *RD2) {
7204 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
7205 for (RecordDecl::field_iterator Field2 = RD2->field_begin(),
7206 Field2End = RD2->field_end();
7207 Field2 != Field2End; ++Field2) {
7208 UnmatchedFields.insert(*Field2);
7209 }
7210
7211 for (RecordDecl::field_iterator Field1 = RD1->field_begin(),
7212 Field1End = RD1->field_end();
7213 Field1 != Field1End; ++Field1) {
7214 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
7215 I = UnmatchedFields.begin(),
7216 E = UnmatchedFields.end();
7217
7218 for ( ; I != E; ++I) {
7219 if (isLayoutCompatible(C, *Field1, *I)) {
7220 bool Result = UnmatchedFields.erase(*I);
7221 (void) Result;
7222 assert(Result);
7223 break;
7224 }
7225 }
7226 if (I == E)
7227 return false;
7228 }
7229
7230 return UnmatchedFields.empty();
7231}
7232
7233bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
7234 if (RD1->isUnion() != RD2->isUnion())
7235 return false;
7236
7237 if (RD1->isUnion())
7238 return isLayoutCompatibleUnion(C, RD1, RD2);
7239 else
7240 return isLayoutCompatibleStruct(C, RD1, RD2);
7241}
7242
7243/// \brief Check if two types are layout-compatible in C++11 sense.
7244bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
7245 if (T1.isNull() || T2.isNull())
7246 return false;
7247
7248 // C++11 [basic.types] p11:
7249 // If two types T1 and T2 are the same type, then T1 and T2 are
7250 // layout-compatible types.
7251 if (C.hasSameType(T1, T2))
7252 return true;
7253
7254 T1 = T1.getCanonicalType().getUnqualifiedType();
7255 T2 = T2.getCanonicalType().getUnqualifiedType();
7256
7257 const Type::TypeClass TC1 = T1->getTypeClass();
7258 const Type::TypeClass TC2 = T2->getTypeClass();
7259
7260 if (TC1 != TC2)
7261 return false;
7262
7263 if (TC1 == Type::Enum) {
7264 return isLayoutCompatible(C,
7265 cast<EnumType>(T1)->getDecl(),
7266 cast<EnumType>(T2)->getDecl());
7267 } else if (TC1 == Type::Record) {
7268 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
7269 return false;
7270
7271 return isLayoutCompatible(C,
7272 cast<RecordType>(T1)->getDecl(),
7273 cast<RecordType>(T2)->getDecl());
7274 }
7275
7276 return false;
7277}
7278}
7279
7280//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
7281
7282namespace {
7283/// \brief Given a type tag expression find the type tag itself.
7284///
7285/// \param TypeExpr Type tag expression, as it appears in user's code.
7286///
7287/// \param VD Declaration of an identifier that appears in a type tag.
7288///
7289/// \param MagicValue Type tag magic value.
7290bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
7291 const ValueDecl **VD, uint64_t *MagicValue) {
7292 while(true) {
7293 if (!TypeExpr)
7294 return false;
7295
7296 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
7297
7298 switch (TypeExpr->getStmtClass()) {
7299 case Stmt::UnaryOperatorClass: {
7300 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
7301 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
7302 TypeExpr = UO->getSubExpr();
7303 continue;
7304 }
7305 return false;
7306 }
7307
7308 case Stmt::DeclRefExprClass: {
7309 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
7310 *VD = DRE->getDecl();
7311 return true;
7312 }
7313
7314 case Stmt::IntegerLiteralClass: {
7315 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
7316 llvm::APInt MagicValueAPInt = IL->getValue();
7317 if (MagicValueAPInt.getActiveBits() <= 64) {
7318 *MagicValue = MagicValueAPInt.getZExtValue();
7319 return true;
7320 } else
7321 return false;
7322 }
7323
7324 case Stmt::BinaryConditionalOperatorClass:
7325 case Stmt::ConditionalOperatorClass: {
7326 const AbstractConditionalOperator *ACO =
7327 cast<AbstractConditionalOperator>(TypeExpr);
7328 bool Result;
7329 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
7330 if (Result)
7331 TypeExpr = ACO->getTrueExpr();
7332 else
7333 TypeExpr = ACO->getFalseExpr();
7334 continue;
7335 }
7336 return false;
7337 }
7338
7339 case Stmt::BinaryOperatorClass: {
7340 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
7341 if (BO->getOpcode() == BO_Comma) {
7342 TypeExpr = BO->getRHS();
7343 continue;
7344 }
7345 return false;
7346 }
7347
7348 default:
7349 return false;
7350 }
7351 }
7352}
7353
7354/// \brief Retrieve the C type corresponding to type tag TypeExpr.
7355///
7356/// \param TypeExpr Expression that specifies a type tag.
7357///
7358/// \param MagicValues Registered magic values.
7359///
7360/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
7361/// kind.
7362///
7363/// \param TypeInfo Information about the corresponding C type.
7364///
7365/// \returns true if the corresponding C type was found.
7366bool GetMatchingCType(
7367 const IdentifierInfo *ArgumentKind,
7368 const Expr *TypeExpr, const ASTContext &Ctx,
7369 const llvm::DenseMap<Sema::TypeTagMagicValue,
7370 Sema::TypeTagData> *MagicValues,
7371 bool &FoundWrongKind,
7372 Sema::TypeTagData &TypeInfo) {
7373 FoundWrongKind = false;
7374
7375 // Variable declaration that has type_tag_for_datatype attribute.
7376 const ValueDecl *VD = NULL;
7377
7378 uint64_t MagicValue;
7379
7380 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
7381 return false;
7382
7383 if (VD) {
7384 for (specific_attr_iterator<TypeTagForDatatypeAttr>
7385 I = VD->specific_attr_begin<TypeTagForDatatypeAttr>(),
7386 E = VD->specific_attr_end<TypeTagForDatatypeAttr>();
7387 I != E; ++I) {
7388 if (I->getArgumentKind() != ArgumentKind) {
7389 FoundWrongKind = true;
7390 return false;
7391 }
7392 TypeInfo.Type = I->getMatchingCType();
7393 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
7394 TypeInfo.MustBeNull = I->getMustBeNull();
7395 return true;
7396 }
7397 return false;
7398 }
7399
7400 if (!MagicValues)
7401 return false;
7402
7403 llvm::DenseMap<Sema::TypeTagMagicValue,
7404 Sema::TypeTagData>::const_iterator I =
7405 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
7406 if (I == MagicValues->end())
7407 return false;
7408
7409 TypeInfo = I->second;
7410 return true;
7411}
7412} // unnamed namespace
7413
7414void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
7415 uint64_t MagicValue, QualType Type,
7416 bool LayoutCompatible,
7417 bool MustBeNull) {
7418 if (!TypeTagForDatatypeMagicValues)
7419 TypeTagForDatatypeMagicValues.reset(
7420 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
7421
7422 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
7423 (*TypeTagForDatatypeMagicValues)[Magic] =
7424 TypeTagData(Type, LayoutCompatible, MustBeNull);
7425}
7426
7427namespace {
7428bool IsSameCharType(QualType T1, QualType T2) {
7429 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
7430 if (!BT1)
7431 return false;
7432
7433 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
7434 if (!BT2)
7435 return false;
7436
7437 BuiltinType::Kind T1Kind = BT1->getKind();
7438 BuiltinType::Kind T2Kind = BT2->getKind();
7439
7440 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
7441 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
7442 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
7443 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
7444}
7445} // unnamed namespace
7446
7447void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
7448 const Expr * const *ExprArgs) {
7449 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
7450 bool IsPointerAttr = Attr->getIsPointer();
7451
7452 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
7453 bool FoundWrongKind;
7454 TypeTagData TypeInfo;
7455 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
7456 TypeTagForDatatypeMagicValues.get(),
7457 FoundWrongKind, TypeInfo)) {
7458 if (FoundWrongKind)
7459 Diag(TypeTagExpr->getExprLoc(),
7460 diag::warn_type_tag_for_datatype_wrong_kind)
7461 << TypeTagExpr->getSourceRange();
7462 return;
7463 }
7464
7465 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
7466 if (IsPointerAttr) {
7467 // Skip implicit cast of pointer to `void *' (as a function argument).
7468 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +00007469 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +00007470 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007471 ArgumentExpr = ICE->getSubExpr();
7472 }
7473 QualType ArgumentType = ArgumentExpr->getType();
7474
7475 // Passing a `void*' pointer shouldn't trigger a warning.
7476 if (IsPointerAttr && ArgumentType->isVoidPointerType())
7477 return;
7478
7479 if (TypeInfo.MustBeNull) {
7480 // Type tag with matching void type requires a null pointer.
7481 if (!ArgumentExpr->isNullPointerConstant(Context,
7482 Expr::NPC_ValueDependentIsNotNull)) {
7483 Diag(ArgumentExpr->getExprLoc(),
7484 diag::warn_type_safety_null_pointer_required)
7485 << ArgumentKind->getName()
7486 << ArgumentExpr->getSourceRange()
7487 << TypeTagExpr->getSourceRange();
7488 }
7489 return;
7490 }
7491
7492 QualType RequiredType = TypeInfo.Type;
7493 if (IsPointerAttr)
7494 RequiredType = Context.getPointerType(RequiredType);
7495
7496 bool mismatch = false;
7497 if (!TypeInfo.LayoutCompatible) {
7498 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
7499
7500 // C++11 [basic.fundamental] p1:
7501 // Plain char, signed char, and unsigned char are three distinct types.
7502 //
7503 // But we treat plain `char' as equivalent to `signed char' or `unsigned
7504 // char' depending on the current char signedness mode.
7505 if (mismatch)
7506 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
7507 RequiredType->getPointeeType())) ||
7508 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
7509 mismatch = false;
7510 } else
7511 if (IsPointerAttr)
7512 mismatch = !isLayoutCompatible(Context,
7513 ArgumentType->getPointeeType(),
7514 RequiredType->getPointeeType());
7515 else
7516 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
7517
7518 if (mismatch)
7519 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +00007520 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007521 << TypeInfo.LayoutCompatible << RequiredType
7522 << ArgumentExpr->getSourceRange()
7523 << TypeTagExpr->getSourceRange();
7524}