blob: 87042d1c07c17283f1f5e040fa0df277bae4d2f3 [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"
Alp Tokerb6cc5922014-05-03 03:45:55 +000030#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
Chandler Carruth3a022472012-12-04 09:13:33 +000031#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 {
Alp Tokerb6cc5922014-05-03 03:45:55 +000046 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
47 Context.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
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000104 ExprResult Arg(TheCall->getArg(0));
Richard Smith6cbd65d2013-07-11 02:27:57 +0000105 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
106 if (ResultType.isNull())
107 return true;
108
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000109 TheCall->setArg(0, Arg.get());
Richard Smith6cbd65d2013-07-11 02:27:57 +0000110 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) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000116 ExprResult TheCallResult(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;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000148 case Builtin::BI__va_start: {
149 switch (Context.getTargetInfo().getTriple().getArch()) {
150 case llvm::Triple::arm:
151 case llvm::Triple::thumb:
152 if (SemaBuiltinVAStartARM(TheCall))
153 return ExprError();
154 break;
155 default:
156 if (SemaBuiltinVAStart(TheCall))
157 return ExprError();
158 break;
159 }
160 break;
161 }
Chris Lattner2da14fb2007-12-20 00:26:33 +0000162 case Builtin::BI__builtin_isgreater:
163 case Builtin::BI__builtin_isgreaterequal:
164 case Builtin::BI__builtin_isless:
165 case Builtin::BI__builtin_islessequal:
166 case Builtin::BI__builtin_islessgreater:
167 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000168 if (SemaBuiltinUnorderedCompare(TheCall))
169 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000170 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000171 case Builtin::BI__builtin_fpclassify:
172 if (SemaBuiltinFPClassification(TheCall, 6))
173 return ExprError();
174 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000175 case Builtin::BI__builtin_isfinite:
176 case Builtin::BI__builtin_isinf:
177 case Builtin::BI__builtin_isinf_sign:
178 case Builtin::BI__builtin_isnan:
179 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000180 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000181 return ExprError();
182 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000183 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000184 return SemaBuiltinShuffleVector(TheCall);
185 // TheCall will be freed by the smart pointer here, but that's fine, since
186 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000187 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000188 if (SemaBuiltinPrefetch(TheCall))
189 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000190 break;
Hal Finkelf0417332014-07-17 14:25:55 +0000191 case Builtin::BI__assume:
192 if (SemaBuiltinAssume(TheCall))
193 return ExprError();
194 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000195 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000196 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000197 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000198 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000199 case Builtin::BI__builtin_longjmp:
200 if (SemaBuiltinLongjmp(TheCall))
201 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000202 break;
John McCallbebede42011-02-26 05:39:39 +0000203
204 case Builtin::BI__builtin_classify_type:
205 if (checkArgCount(*this, TheCall, 1)) return true;
206 TheCall->setType(Context.IntTy);
207 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000208 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000209 if (checkArgCount(*this, TheCall, 1)) return true;
210 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000211 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000212 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000213 case Builtin::BI__sync_fetch_and_add_1:
214 case Builtin::BI__sync_fetch_and_add_2:
215 case Builtin::BI__sync_fetch_and_add_4:
216 case Builtin::BI__sync_fetch_and_add_8:
217 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000218 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000219 case Builtin::BI__sync_fetch_and_sub_1:
220 case Builtin::BI__sync_fetch_and_sub_2:
221 case Builtin::BI__sync_fetch_and_sub_4:
222 case Builtin::BI__sync_fetch_and_sub_8:
223 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000224 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000225 case Builtin::BI__sync_fetch_and_or_1:
226 case Builtin::BI__sync_fetch_and_or_2:
227 case Builtin::BI__sync_fetch_and_or_4:
228 case Builtin::BI__sync_fetch_and_or_8:
229 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000230 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000231 case Builtin::BI__sync_fetch_and_and_1:
232 case Builtin::BI__sync_fetch_and_and_2:
233 case Builtin::BI__sync_fetch_and_and_4:
234 case Builtin::BI__sync_fetch_and_and_8:
235 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000236 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000237 case Builtin::BI__sync_fetch_and_xor_1:
238 case Builtin::BI__sync_fetch_and_xor_2:
239 case Builtin::BI__sync_fetch_and_xor_4:
240 case Builtin::BI__sync_fetch_and_xor_8:
241 case Builtin::BI__sync_fetch_and_xor_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000242 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000243 case Builtin::BI__sync_add_and_fetch_1:
244 case Builtin::BI__sync_add_and_fetch_2:
245 case Builtin::BI__sync_add_and_fetch_4:
246 case Builtin::BI__sync_add_and_fetch_8:
247 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000248 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000249 case Builtin::BI__sync_sub_and_fetch_1:
250 case Builtin::BI__sync_sub_and_fetch_2:
251 case Builtin::BI__sync_sub_and_fetch_4:
252 case Builtin::BI__sync_sub_and_fetch_8:
253 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000254 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000255 case Builtin::BI__sync_and_and_fetch_1:
256 case Builtin::BI__sync_and_and_fetch_2:
257 case Builtin::BI__sync_and_and_fetch_4:
258 case Builtin::BI__sync_and_and_fetch_8:
259 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000260 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000261 case Builtin::BI__sync_or_and_fetch_1:
262 case Builtin::BI__sync_or_and_fetch_2:
263 case Builtin::BI__sync_or_and_fetch_4:
264 case Builtin::BI__sync_or_and_fetch_8:
265 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000266 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000267 case Builtin::BI__sync_xor_and_fetch_1:
268 case Builtin::BI__sync_xor_and_fetch_2:
269 case Builtin::BI__sync_xor_and_fetch_4:
270 case Builtin::BI__sync_xor_and_fetch_8:
271 case Builtin::BI__sync_xor_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000272 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000273 case Builtin::BI__sync_val_compare_and_swap_1:
274 case Builtin::BI__sync_val_compare_and_swap_2:
275 case Builtin::BI__sync_val_compare_and_swap_4:
276 case Builtin::BI__sync_val_compare_and_swap_8:
277 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000278 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000279 case Builtin::BI__sync_bool_compare_and_swap_1:
280 case Builtin::BI__sync_bool_compare_and_swap_2:
281 case Builtin::BI__sync_bool_compare_and_swap_4:
282 case Builtin::BI__sync_bool_compare_and_swap_8:
283 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000284 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000285 case Builtin::BI__sync_lock_test_and_set_1:
286 case Builtin::BI__sync_lock_test_and_set_2:
287 case Builtin::BI__sync_lock_test_and_set_4:
288 case Builtin::BI__sync_lock_test_and_set_8:
289 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000290 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000291 case Builtin::BI__sync_lock_release_1:
292 case Builtin::BI__sync_lock_release_2:
293 case Builtin::BI__sync_lock_release_4:
294 case Builtin::BI__sync_lock_release_8:
295 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000296 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000297 case Builtin::BI__sync_swap_1:
298 case Builtin::BI__sync_swap_2:
299 case Builtin::BI__sync_swap_4:
300 case Builtin::BI__sync_swap_8:
301 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000302 return SemaBuiltinAtomicOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +0000303#define BUILTIN(ID, TYPE, ATTRS)
304#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
305 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000306 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +0000307#include "clang/Basic/Builtins.def"
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000308 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000309 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000310 return ExprError();
311 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +0000312 case Builtin::BI__builtin_addressof:
313 if (SemaBuiltinAddressof(*this, TheCall))
314 return ExprError();
315 break;
Richard Smith760520b2014-06-03 23:27:44 +0000316 case Builtin::BI__builtin_operator_new:
317 case Builtin::BI__builtin_operator_delete:
318 if (!getLangOpts().CPlusPlus) {
319 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
320 << (BuiltinID == Builtin::BI__builtin_operator_new
321 ? "__builtin_operator_new"
322 : "__builtin_operator_delete")
323 << "C++";
324 return ExprError();
325 }
326 // CodeGen assumes it can find the global new and delete to call,
327 // so ensure that they are declared.
328 DeclareGlobalNewDelete();
329 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000330 }
Richard Smith760520b2014-06-03 23:27:44 +0000331
Nate Begeman4904e322010-06-08 02:47:44 +0000332 // Since the target specific builtins for each arch overlap, only check those
333 // of the arch we are compiling for.
334 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000335 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +0000336 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000337 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000338 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000339 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000340 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
341 return ExprError();
342 break;
Tim Northover25e8a672014-05-24 12:51:25 +0000343 case llvm::Triple::aarch64:
344 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +0000345 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +0000346 return ExprError();
347 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000348 case llvm::Triple::mips:
349 case llvm::Triple::mipsel:
350 case llvm::Triple::mips64:
351 case llvm::Triple::mips64el:
352 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
353 return ExprError();
354 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000355 case llvm::Triple::x86:
356 case llvm::Triple::x86_64:
357 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
358 return ExprError();
359 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000360 default:
361 break;
362 }
363 }
364
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000365 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +0000366}
367
Nate Begeman91e1fea2010-06-14 05:21:25 +0000368// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +0000369static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +0000370 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +0000371 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +0000372 switch (Type.getEltType()) {
373 case NeonTypeFlags::Int8:
374 case NeonTypeFlags::Poly8:
375 return shift ? 7 : (8 << IsQuad) - 1;
376 case NeonTypeFlags::Int16:
377 case NeonTypeFlags::Poly16:
378 return shift ? 15 : (4 << IsQuad) - 1;
379 case NeonTypeFlags::Int32:
380 return shift ? 31 : (2 << IsQuad) - 1;
381 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +0000382 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +0000383 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000384 case NeonTypeFlags::Poly128:
385 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +0000386 case NeonTypeFlags::Float16:
387 assert(!shift && "cannot shift float types!");
388 return (4 << IsQuad) - 1;
389 case NeonTypeFlags::Float32:
390 assert(!shift && "cannot shift float types!");
391 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000392 case NeonTypeFlags::Float64:
393 assert(!shift && "cannot shift float types!");
394 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000395 }
David Blaikie8a40f702012-01-17 06:56:22 +0000396 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +0000397}
398
Bob Wilsone4d77232011-11-08 05:04:11 +0000399/// getNeonEltType - Return the QualType corresponding to the elements of
400/// the vector type specified by the NeonTypeFlags. This is used to check
401/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +0000402static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +0000403 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +0000404 switch (Flags.getEltType()) {
405 case NeonTypeFlags::Int8:
406 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
407 case NeonTypeFlags::Int16:
408 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
409 case NeonTypeFlags::Int32:
410 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
411 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +0000412 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +0000413 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
414 else
415 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
416 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000417 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +0000418 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000419 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +0000420 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +0000421 case NeonTypeFlags::Poly64:
Kevin Qinad64f6d2014-02-24 02:45:03 +0000422 return Context.UnsignedLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000423 case NeonTypeFlags::Poly128:
424 break;
Bob Wilsone4d77232011-11-08 05:04:11 +0000425 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +0000426 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000427 case NeonTypeFlags::Float32:
428 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +0000429 case NeonTypeFlags::Float64:
430 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000431 }
David Blaikie8a40f702012-01-17 06:56:22 +0000432 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +0000433}
434
Tim Northover12670412014-02-19 10:37:05 +0000435bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +0000436 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +0000437 uint64_t mask = 0;
438 unsigned TV = 0;
439 int PtrArgNum = -1;
440 bool HasConstPtr = false;
441 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +0000442#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000443#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000444#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000445 }
446
447 // For NEON intrinsics which are overloaded on vector element type, validate
448 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +0000449 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000450 if (mask) {
451 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
452 return true;
453
454 TV = Result.getLimitedValue(64);
455 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
456 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +0000457 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +0000458 }
459
460 if (PtrArgNum >= 0) {
461 // Check that pointer arguments have the specified type.
462 Expr *Arg = TheCall->getArg(PtrArgNum);
463 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
464 Arg = ICE->getSubExpr();
465 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
466 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +0000467
Tim Northovera2ee4332014-03-29 15:09:45 +0000468 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Tim Northover40956e62014-07-23 12:32:58 +0000469 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
Tim Northovera2ee4332014-03-29 15:09:45 +0000470 bool IsInt64Long =
471 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
472 QualType EltTy =
473 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +0000474 if (HasConstPtr)
475 EltTy = EltTy.withConst();
476 QualType LHSTy = Context.getPointerType(EltTy);
477 AssignConvertType ConvTy;
478 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
479 if (RHS.isInvalid())
480 return true;
481 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
482 RHS.get(), AA_Assigning))
483 return true;
484 }
485
486 // For NEON intrinsics which take an immediate value as part of the
487 // instruction, range check them here.
488 unsigned i = 0, l = 0, u = 0;
489 switch (BuiltinID) {
490 default:
491 return false;
Tim Northover12670412014-02-19 10:37:05 +0000492#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000493#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000494#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000495 }
Tim Northover2fe823a2013-08-01 09:23:19 +0000496
Richard Sandiford28940af2014-04-16 08:47:51 +0000497 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +0000498}
499
Tim Northovera2ee4332014-03-29 15:09:45 +0000500bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
501 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +0000502 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000503 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +0000504 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000505 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +0000506 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000507 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
508 BuiltinID == AArch64::BI__builtin_arm_strex ||
509 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +0000510 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +0000511 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000512 BuiltinID == ARM::BI__builtin_arm_ldaex ||
513 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
514 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +0000515
516 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
517
518 // Ensure that we have the proper number of arguments.
519 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
520 return true;
521
522 // Inspect the pointer argument of the atomic builtin. This should always be
523 // a pointer type, whose element is an integral scalar or pointer type.
524 // Because it is a pointer type, we don't have to worry about any implicit
525 // casts here.
526 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
527 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
528 if (PointerArgRes.isInvalid())
529 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000530 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000531
532 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
533 if (!pointerType) {
534 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
535 << PointerArg->getType() << PointerArg->getSourceRange();
536 return true;
537 }
538
539 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
540 // task is to insert the appropriate casts into the AST. First work out just
541 // what the appropriate type is.
542 QualType ValType = pointerType->getPointeeType();
543 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
544 if (IsLdrex)
545 AddrType.addConst();
546
547 // Issue a warning if the cast is dodgy.
548 CastKind CastNeeded = CK_NoOp;
549 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
550 CastNeeded = CK_BitCast;
551 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
552 << PointerArg->getType()
553 << Context.getPointerType(AddrType)
554 << AA_Passing << PointerArg->getSourceRange();
555 }
556
557 // Finally, do the cast and replace the argument with the corrected version.
558 AddrType = Context.getPointerType(AddrType);
559 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
560 if (PointerArgRes.isInvalid())
561 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000562 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000563
564 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
565
566 // In general, we allow ints, floats and pointers to be loaded and stored.
567 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
568 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
569 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
570 << PointerArg->getType() << PointerArg->getSourceRange();
571 return true;
572 }
573
574 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +0000575 if (Context.getTypeSize(ValType) > MaxWidth) {
576 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +0000577 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
578 << PointerArg->getType() << PointerArg->getSourceRange();
579 return true;
580 }
581
582 switch (ValType.getObjCLifetime()) {
583 case Qualifiers::OCL_None:
584 case Qualifiers::OCL_ExplicitNone:
585 // okay
586 break;
587
588 case Qualifiers::OCL_Weak:
589 case Qualifiers::OCL_Strong:
590 case Qualifiers::OCL_Autoreleasing:
591 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
592 << ValType << PointerArg->getSourceRange();
593 return true;
594 }
595
596
597 if (IsLdrex) {
598 TheCall->setType(ValType);
599 return false;
600 }
601
602 // Initialize the argument to be stored.
603 ExprResult ValArg = TheCall->getArg(0);
604 InitializedEntity Entity = InitializedEntity::InitializeParameter(
605 Context, ValType, /*consume*/ false);
606 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
607 if (ValArg.isInvalid())
608 return true;
Tim Northover6aacd492013-07-16 09:47:53 +0000609 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +0000610
611 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
612 // but the custom checker bypasses all default analysis.
613 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +0000614 return false;
615}
616
Nate Begeman4904e322010-06-08 02:47:44 +0000617bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +0000618 llvm::APSInt Result;
619
Tim Northover6aacd492013-07-16 09:47:53 +0000620 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000621 BuiltinID == ARM::BI__builtin_arm_ldaex ||
622 BuiltinID == ARM::BI__builtin_arm_strex ||
623 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000624 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +0000625 }
626
Yi Kong26d104a2014-08-13 19:18:14 +0000627 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
628 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
629 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
630 }
631
Tim Northover12670412014-02-19 10:37:05 +0000632 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
633 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +0000634
Yi Kong4efadfb2014-07-03 16:01:25 +0000635 // For intrinsics which take an immediate value as part of the instruction,
636 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +0000637 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +0000638 switch (BuiltinID) {
639 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +0000640 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
641 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +0000642 case ARM::BI__builtin_arm_vcvtr_f:
643 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +0000644 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +0000645 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +0000646 case ARM::BI__builtin_arm_isb:
647 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +0000648 }
Nate Begemand773fe62010-06-13 04:47:52 +0000649
Nate Begemanf568b072010-08-03 21:32:34 +0000650 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +0000651 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000652}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000653
Tim Northover573cbee2014-05-24 12:52:07 +0000654bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +0000655 CallExpr *TheCall) {
656 llvm::APSInt Result;
657
Tim Northover573cbee2014-05-24 12:52:07 +0000658 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000659 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
660 BuiltinID == AArch64::BI__builtin_arm_strex ||
661 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000662 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
663 }
664
Yi Konga5548432014-08-13 19:18:20 +0000665 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
666 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
667 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
668 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
669 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
670 }
671
Tim Northovera2ee4332014-03-29 15:09:45 +0000672 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
673 return true;
674
Yi Kong19a29ac2014-07-17 10:52:06 +0000675 // For intrinsics which take an immediate value as part of the instruction,
676 // range check them here.
677 unsigned i = 0, l = 0, u = 0;
678 switch (BuiltinID) {
679 default: return false;
680 case AArch64::BI__builtin_arm_dmb:
681 case AArch64::BI__builtin_arm_dsb:
682 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
683 }
684
Yi Kong19a29ac2014-07-17 10:52:06 +0000685 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +0000686}
687
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000688bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
689 unsigned i = 0, l = 0, u = 0;
690 switch (BuiltinID) {
691 default: return false;
692 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
693 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +0000694 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
695 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
696 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
697 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
698 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Richard Sandiford28940af2014-04-16 08:47:51 +0000699 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000700
Richard Sandiford28940af2014-04-16 08:47:51 +0000701 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000702}
703
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000704bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
705 switch (BuiltinID) {
706 case X86::BI_mm_prefetch:
Richard Sandiford28940af2014-04-16 08:47:51 +0000707 // This is declared to take (const char*, int)
708 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000709 }
710 return false;
711}
712
Richard Smith55ce3522012-06-25 20:30:08 +0000713/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
714/// parameter with the FormatAttr's correct format_idx and firstDataArg.
715/// Returns true when the format fits the function and the FormatStringInfo has
716/// been populated.
717bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
718 FormatStringInfo *FSI) {
719 FSI->HasVAListArg = Format->getFirstArg() == 0;
720 FSI->FormatIdx = Format->getFormatIdx() - 1;
721 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000722
Richard Smith55ce3522012-06-25 20:30:08 +0000723 // The way the format attribute works in GCC, the implicit this argument
724 // of member functions is counted. However, it doesn't appear in our own
725 // lists, so decrement format_idx in that case.
726 if (IsCXXMember) {
727 if(FSI->FormatIdx == 0)
728 return false;
729 --FSI->FormatIdx;
730 if (FSI->FirstDataArg != 0)
731 --FSI->FirstDataArg;
732 }
733 return true;
734}
Mike Stump11289f42009-09-09 15:08:12 +0000735
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000736/// Checks if a the given expression evaluates to null.
737///
738/// \brief Returns true if the value evaluates to null.
739static bool CheckNonNullExpr(Sema &S,
740 const Expr *Expr) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000741 // As a special case, transparent unions initialized with zero are
742 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000743 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000744 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
745 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000746 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000747 if (const InitListExpr *ILE =
748 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000749 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +0000750 }
751
752 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +0000753 return (!Expr->isValueDependent() &&
754 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
755 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000756}
757
758static void CheckNonNullArgument(Sema &S,
759 const Expr *ArgExpr,
760 SourceLocation CallSiteLoc) {
761 if (CheckNonNullExpr(S, ArgExpr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000762 S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
763}
764
Ted Kremenek2bc73332014-01-17 06:24:43 +0000765static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +0000766 const NamedDecl *FDecl,
Richard Smith588bd9b2014-08-27 04:59:42 +0000767 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +0000768 SourceLocation CallSiteLoc) {
Ted Kremenek9aedc152014-01-17 06:24:56 +0000769 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +0000770 llvm::SmallBitVector NonNullArgs;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000771 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
Richard Smith588bd9b2014-08-27 04:59:42 +0000772 if (!NonNull->args_size()) {
773 // Easy case: all pointer arguments are nonnull.
774 for (const auto *Arg : Args)
775 if (S.isValidNonNullAttrType(Arg->getType()))
776 CheckNonNullArgument(S, Arg, CallSiteLoc);
777 return;
778 }
779
780 for (unsigned Val : NonNull->args()) {
781 if (Val >= Args.size())
782 continue;
783 if (NonNullArgs.empty())
784 NonNullArgs.resize(Args.size());
785 NonNullArgs.set(Val);
786 }
Ted Kremenek2bc73332014-01-17 06:24:43 +0000787 }
Ted Kremenek9aedc152014-01-17 06:24:56 +0000788
789 // Check the attributes on the parameters.
790 ArrayRef<ParmVarDecl*> parms;
791 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
792 parms = FD->parameters();
793 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(FDecl))
794 parms = MD->parameters();
795
Richard Smith588bd9b2014-08-27 04:59:42 +0000796 unsigned ArgIndex = 0;
Ted Kremenek9aedc152014-01-17 06:24:56 +0000797 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
Richard Smith588bd9b2014-08-27 04:59:42 +0000798 I != E; ++I, ++ArgIndex) {
Ted Kremenek9aedc152014-01-17 06:24:56 +0000799 const ParmVarDecl *PVD = *I;
Richard Smith588bd9b2014-08-27 04:59:42 +0000800 if (PVD->hasAttr<NonNullAttr>() ||
801 (ArgIndex < NonNullArgs.size() && NonNullArgs[ArgIndex]))
802 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Ted Kremenek9aedc152014-01-17 06:24:56 +0000803 }
Richard Smith588bd9b2014-08-27 04:59:42 +0000804
805 // In case this is a variadic call, check any remaining arguments.
806 for (/**/; ArgIndex < NonNullArgs.size(); ++ArgIndex)
807 if (NonNullArgs[ArgIndex])
808 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Ted Kremenek2bc73332014-01-17 06:24:43 +0000809}
810
Richard Smith55ce3522012-06-25 20:30:08 +0000811/// Handles the checks for format strings, non-POD arguments to vararg
812/// functions, and NULL arguments passed to non-NULL parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +0000813void Sema::checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
814 unsigned NumParams, bool IsMemberFunction,
815 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +0000816 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +0000817 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +0000818 if (CurContext->isDependentContext())
819 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000820
Ted Kremenekb8176da2010-09-09 04:33:05 +0000821 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +0000822 llvm::SmallBitVector CheckedVarArgs;
823 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000824 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +0000825 // Only create vector if there are format attributes.
826 CheckedVarArgs.resize(Args.size());
827
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000828 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +0000829 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +0000830 }
Richard Smithd7293d72013-08-05 18:49:43 +0000831 }
Richard Smith55ce3522012-06-25 20:30:08 +0000832
833 // Refuse POD arguments that weren't caught by the format string
834 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +0000835 if (CallType != VariadicDoesNotApply) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000836 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +0000837 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +0000838 if (const Expr *Arg = Args[ArgIdx]) {
839 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
840 checkVariadicArgument(Arg, CallType);
841 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +0000842 }
Richard Smithd7293d72013-08-05 18:49:43 +0000843 }
Mike Stump11289f42009-09-09 15:08:12 +0000844
Richard Trieu41bc0992013-06-22 00:20:41 +0000845 if (FDecl) {
Richard Smith588bd9b2014-08-27 04:59:42 +0000846 CheckNonNullArguments(*this, FDecl, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000847
Richard Trieu41bc0992013-06-22 00:20:41 +0000848 // Type safety checking.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000849 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
850 CheckArgumentWithTypeTag(I, Args.data());
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000851 }
Richard Smith55ce3522012-06-25 20:30:08 +0000852}
853
854/// CheckConstructorCall - Check a constructor call for correctness and safety
855/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +0000856void Sema::CheckConstructorCall(FunctionDecl *FDecl,
857 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +0000858 const FunctionProtoType *Proto,
859 SourceLocation Loc) {
860 VariadicCallType CallType =
861 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Alp Toker9cacbab2014-01-20 20:26:09 +0000862 checkCall(FDecl, Args, Proto->getNumParams(),
Richard Smith55ce3522012-06-25 20:30:08 +0000863 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
864}
865
866/// CheckFunctionCall - Check a direct function call for various correctness
867/// and safety properties not strictly enforced by the C type system.
868bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
869 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +0000870 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
871 isa<CXXMethodDecl>(FDecl);
872 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
873 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +0000874 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
875 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +0000876 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Eli Friedman726d11c2012-10-11 00:30:58 +0000877 Expr** Args = TheCall->getArgs();
878 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +0000879 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +0000880 // If this is a call to a member operator, hide the first argument
881 // from checkCall.
882 // FIXME: Our choice of AST representation here is less than ideal.
883 ++Args;
884 --NumArgs;
885 }
Craig Topper8c2a2a02014-08-30 16:55:39 +0000886 checkCall(FDecl, llvm::makeArrayRef(Args, NumArgs), NumParams,
Richard Smith55ce3522012-06-25 20:30:08 +0000887 IsMemberFunction, TheCall->getRParenLoc(),
888 TheCall->getCallee()->getSourceRange(), CallType);
889
890 IdentifierInfo *FnInfo = FDecl->getIdentifier();
891 // None of the checks below are needed for functions that don't have
892 // simple names (e.g., C++ conversion functions).
893 if (!FnInfo)
894 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000895
Richard Trieu7eb0b2c2014-02-26 01:17:28 +0000896 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
897
Anna Zaks22122702012-01-17 00:37:07 +0000898 unsigned CMId = FDecl->getMemoryFunctionKind();
899 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +0000900 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +0000901
Anna Zaks201d4892012-01-13 21:52:01 +0000902 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +0000903 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +0000904 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +0000905 else if (CMId == Builtin::BIstrncat)
906 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +0000907 else
Anna Zaks22122702012-01-17 00:37:07 +0000908 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +0000909
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000910 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +0000911}
912
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000913bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +0000914 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +0000915 VariadicCallType CallType =
916 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000917
Dmitri Gribenko1debc462013-05-05 19:42:09 +0000918 checkCall(Method, Args, Method->param_size(),
Richard Smith55ce3522012-06-25 20:30:08 +0000919 /*IsMemberFunction=*/false,
920 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000921
922 return false;
923}
924
Richard Trieu664c4c62013-06-20 21:03:13 +0000925bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
926 const FunctionProtoType *Proto) {
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000927 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
928 if (!V)
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000929 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000930
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000931 QualType Ty = V->getType();
Richard Trieu664c4c62013-06-20 21:03:13 +0000932 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000933 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000934
Richard Trieu664c4c62013-06-20 21:03:13 +0000935 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +0000936 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +0000937 CallType = VariadicDoesNotApply;
938 } else if (Ty->isBlockPointerType()) {
939 CallType = VariadicBlock;
940 } else { // Ty->isFunctionPointerType()
941 CallType = VariadicFunction;
942 }
Alp Toker9cacbab2014-01-20 20:26:09 +0000943 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000944
Craig Topper8c2a2a02014-08-30 16:55:39 +0000945 checkCall(NDecl, llvm::makeArrayRef(TheCall->getArgs(),
946 TheCall->getNumArgs()),
Alp Toker9cacbab2014-01-20 20:26:09 +0000947 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +0000948 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +0000949
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000950 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000951}
952
Richard Trieu41bc0992013-06-22 00:20:41 +0000953/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
954/// such as function pointers returned from functions.
955bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000956 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +0000957 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +0000958 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Richard Trieu41bc0992013-06-22 00:20:41 +0000959
Craig Topperc3ec1492014-05-26 06:22:03 +0000960 checkCall(/*FDecl=*/nullptr,
Craig Topper8c2a2a02014-08-30 16:55:39 +0000961 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Alp Toker9cacbab2014-01-20 20:26:09 +0000962 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +0000963 TheCall->getCallee()->getSourceRange(), CallType);
964
965 return false;
966}
967
Tim Northovere94a34c2014-03-11 10:49:14 +0000968static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
969 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
970 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
971 return false;
972
973 switch (Op) {
974 case AtomicExpr::AO__c11_atomic_init:
975 llvm_unreachable("There is no ordering argument for an init");
976
977 case AtomicExpr::AO__c11_atomic_load:
978 case AtomicExpr::AO__atomic_load_n:
979 case AtomicExpr::AO__atomic_load:
980 return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
981 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
982
983 case AtomicExpr::AO__c11_atomic_store:
984 case AtomicExpr::AO__atomic_store:
985 case AtomicExpr::AO__atomic_store_n:
986 return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
987 Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
988 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
989
990 default:
991 return true;
992 }
993}
994
Richard Smithfeea8832012-04-12 05:08:17 +0000995ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
996 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000997 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
998 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000999
Richard Smithfeea8832012-04-12 05:08:17 +00001000 // All these operations take one of the following forms:
1001 enum {
1002 // C __c11_atomic_init(A *, C)
1003 Init,
1004 // C __c11_atomic_load(A *, int)
1005 Load,
1006 // void __atomic_load(A *, CP, int)
1007 Copy,
1008 // C __c11_atomic_add(A *, M, int)
1009 Arithmetic,
1010 // C __atomic_exchange_n(A *, CP, int)
1011 Xchg,
1012 // void __atomic_exchange(A *, C *, CP, int)
1013 GNUXchg,
1014 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
1015 C11CmpXchg,
1016 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
1017 GNUCmpXchg
1018 } Form = Init;
1019 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
1020 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
1021 // where:
1022 // C is an appropriate type,
1023 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
1024 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
1025 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
1026 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001027
Richard Smithfeea8832012-04-12 05:08:17 +00001028 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
1029 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
1030 && "need to update code for modified C11 atomics");
1031 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
1032 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
1033 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
1034 Op == AtomicExpr::AO__atomic_store_n ||
1035 Op == AtomicExpr::AO__atomic_exchange_n ||
1036 Op == AtomicExpr::AO__atomic_compare_exchange_n;
1037 bool IsAddSub = false;
1038
1039 switch (Op) {
1040 case AtomicExpr::AO__c11_atomic_init:
1041 Form = Init;
1042 break;
1043
1044 case AtomicExpr::AO__c11_atomic_load:
1045 case AtomicExpr::AO__atomic_load_n:
1046 Form = Load;
1047 break;
1048
1049 case AtomicExpr::AO__c11_atomic_store:
1050 case AtomicExpr::AO__atomic_load:
1051 case AtomicExpr::AO__atomic_store:
1052 case AtomicExpr::AO__atomic_store_n:
1053 Form = Copy;
1054 break;
1055
1056 case AtomicExpr::AO__c11_atomic_fetch_add:
1057 case AtomicExpr::AO__c11_atomic_fetch_sub:
1058 case AtomicExpr::AO__atomic_fetch_add:
1059 case AtomicExpr::AO__atomic_fetch_sub:
1060 case AtomicExpr::AO__atomic_add_fetch:
1061 case AtomicExpr::AO__atomic_sub_fetch:
1062 IsAddSub = true;
1063 // Fall through.
1064 case AtomicExpr::AO__c11_atomic_fetch_and:
1065 case AtomicExpr::AO__c11_atomic_fetch_or:
1066 case AtomicExpr::AO__c11_atomic_fetch_xor:
1067 case AtomicExpr::AO__atomic_fetch_and:
1068 case AtomicExpr::AO__atomic_fetch_or:
1069 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00001070 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00001071 case AtomicExpr::AO__atomic_and_fetch:
1072 case AtomicExpr::AO__atomic_or_fetch:
1073 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00001074 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00001075 Form = Arithmetic;
1076 break;
1077
1078 case AtomicExpr::AO__c11_atomic_exchange:
1079 case AtomicExpr::AO__atomic_exchange_n:
1080 Form = Xchg;
1081 break;
1082
1083 case AtomicExpr::AO__atomic_exchange:
1084 Form = GNUXchg;
1085 break;
1086
1087 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1088 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1089 Form = C11CmpXchg;
1090 break;
1091
1092 case AtomicExpr::AO__atomic_compare_exchange:
1093 case AtomicExpr::AO__atomic_compare_exchange_n:
1094 Form = GNUCmpXchg;
1095 break;
1096 }
1097
1098 // Check we have the right number of arguments.
1099 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001100 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001101 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001102 << TheCall->getCallee()->getSourceRange();
1103 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00001104 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1105 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001106 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001107 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001108 << TheCall->getCallee()->getSourceRange();
1109 return ExprError();
1110 }
1111
Richard Smithfeea8832012-04-12 05:08:17 +00001112 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001113 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001114 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1115 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1116 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00001117 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001118 << Ptr->getType() << Ptr->getSourceRange();
1119 return ExprError();
1120 }
1121
Richard Smithfeea8832012-04-12 05:08:17 +00001122 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1123 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1124 QualType ValType = AtomTy; // 'C'
1125 if (IsC11) {
1126 if (!AtomTy->isAtomicType()) {
1127 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1128 << Ptr->getType() << Ptr->getSourceRange();
1129 return ExprError();
1130 }
Richard Smithe00921a2012-09-15 06:09:58 +00001131 if (AtomTy.isConstQualified()) {
1132 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1133 << Ptr->getType() << Ptr->getSourceRange();
1134 return ExprError();
1135 }
Richard Smithfeea8832012-04-12 05:08:17 +00001136 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001137 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001138
Richard Smithfeea8832012-04-12 05:08:17 +00001139 // For an arithmetic operation, the implied arithmetic must be well-formed.
1140 if (Form == Arithmetic) {
1141 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1142 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1143 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1144 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1145 return ExprError();
1146 }
1147 if (!IsAddSub && !ValType->isIntegerType()) {
1148 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1149 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1150 return ExprError();
1151 }
1152 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1153 // For __atomic_*_n operations, the value type must be a scalar integral or
1154 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001155 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00001156 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1157 return ExprError();
1158 }
1159
Eli Friedmanaa769812013-09-11 03:49:34 +00001160 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1161 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00001162 // For GNU atomics, require a trivially-copyable type. This is not part of
1163 // the GNU atomics specification, but we enforce it for sanity.
1164 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001165 << Ptr->getType() << Ptr->getSourceRange();
1166 return ExprError();
1167 }
1168
Richard Smithfeea8832012-04-12 05:08:17 +00001169 // FIXME: For any builtin other than a load, the ValType must not be
1170 // const-qualified.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001171
1172 switch (ValType.getObjCLifetime()) {
1173 case Qualifiers::OCL_None:
1174 case Qualifiers::OCL_ExplicitNone:
1175 // okay
1176 break;
1177
1178 case Qualifiers::OCL_Weak:
1179 case Qualifiers::OCL_Strong:
1180 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00001181 // FIXME: Can this happen? By this point, ValType should be known
1182 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001183 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1184 << ValType << Ptr->getSourceRange();
1185 return ExprError();
1186 }
1187
1188 QualType ResultType = ValType;
Richard Smithfeea8832012-04-12 05:08:17 +00001189 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001190 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00001191 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001192 ResultType = Context.BoolTy;
1193
Richard Smithfeea8832012-04-12 05:08:17 +00001194 // The type of a parameter passed 'by value'. In the GNU atomics, such
1195 // arguments are actually passed as pointers.
1196 QualType ByValType = ValType; // 'CP'
1197 if (!IsC11 && !IsN)
1198 ByValType = Ptr->getType();
1199
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001200 // The first argument --- the pointer --- has a fixed type; we
1201 // deduce the types of the rest of the arguments accordingly. Walk
1202 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00001203 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001204 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00001205 if (i < NumVals[Form] + 1) {
1206 switch (i) {
1207 case 1:
1208 // The second argument is the non-atomic operand. For arithmetic, this
1209 // is always passed by value, and for a compare_exchange it is always
1210 // passed by address. For the rest, GNU uses by-address and C11 uses
1211 // by-value.
1212 assert(Form != Load);
1213 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1214 Ty = ValType;
1215 else if (Form == Copy || Form == Xchg)
1216 Ty = ByValType;
1217 else if (Form == Arithmetic)
1218 Ty = Context.getPointerDiffType();
1219 else
1220 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1221 break;
1222 case 2:
1223 // The third argument to compare_exchange / GNU exchange is a
1224 // (pointer to a) desired value.
1225 Ty = ByValType;
1226 break;
1227 case 3:
1228 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1229 Ty = Context.BoolTy;
1230 break;
1231 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001232 } else {
1233 // The order(s) are always converted to int.
1234 Ty = Context.IntTy;
1235 }
Richard Smithfeea8832012-04-12 05:08:17 +00001236
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001237 InitializedEntity Entity =
1238 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00001239 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001240 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1241 if (Arg.isInvalid())
1242 return true;
1243 TheCall->setArg(i, Arg.get());
1244 }
1245
Richard Smithfeea8832012-04-12 05:08:17 +00001246 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001247 SmallVector<Expr*, 5> SubExprs;
1248 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00001249 switch (Form) {
1250 case Init:
1251 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00001252 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001253 break;
1254 case Load:
1255 SubExprs.push_back(TheCall->getArg(1)); // Order
1256 break;
1257 case Copy:
1258 case Arithmetic:
1259 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001260 SubExprs.push_back(TheCall->getArg(2)); // Order
1261 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001262 break;
1263 case GNUXchg:
1264 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1265 SubExprs.push_back(TheCall->getArg(3)); // Order
1266 SubExprs.push_back(TheCall->getArg(1)); // Val1
1267 SubExprs.push_back(TheCall->getArg(2)); // Val2
1268 break;
1269 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001270 SubExprs.push_back(TheCall->getArg(3)); // Order
1271 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001272 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00001273 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00001274 break;
1275 case GNUCmpXchg:
1276 SubExprs.push_back(TheCall->getArg(4)); // Order
1277 SubExprs.push_back(TheCall->getArg(1)); // Val1
1278 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1279 SubExprs.push_back(TheCall->getArg(2)); // Val2
1280 SubExprs.push_back(TheCall->getArg(3)); // Weak
1281 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001282 }
Tim Northovere94a34c2014-03-11 10:49:14 +00001283
1284 if (SubExprs.size() >= 2 && Form != Init) {
1285 llvm::APSInt Result(32);
1286 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
1287 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00001288 Diag(SubExprs[1]->getLocStart(),
1289 diag::warn_atomic_op_has_invalid_memory_order)
1290 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00001291 }
1292
Fariborz Jahanian615de762013-05-28 17:37:39 +00001293 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1294 SubExprs, ResultType, Op,
1295 TheCall->getRParenLoc());
1296
1297 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1298 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1299 Context.AtomicUsesUnsupportedLibcall(AE))
1300 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1301 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001302
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001303 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001304}
1305
1306
John McCall29ad95b2011-08-27 01:09:30 +00001307/// checkBuiltinArgument - Given a call to a builtin function, perform
1308/// normal type-checking on the given argument, updating the call in
1309/// place. This is useful when a builtin function requires custom
1310/// type-checking for some of its arguments but not necessarily all of
1311/// them.
1312///
1313/// Returns true on error.
1314static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1315 FunctionDecl *Fn = E->getDirectCallee();
1316 assert(Fn && "builtin call without direct callee!");
1317
1318 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1319 InitializedEntity Entity =
1320 InitializedEntity::InitializeParameter(S.Context, Param);
1321
1322 ExprResult Arg = E->getArg(0);
1323 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1324 if (Arg.isInvalid())
1325 return true;
1326
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001327 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00001328 return false;
1329}
1330
Chris Lattnerdc046542009-05-08 06:58:22 +00001331/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1332/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1333/// type of its first argument. The main ActOnCallExpr routines have already
1334/// promoted the types of arguments because all of these calls are prototyped as
1335/// void(...).
1336///
1337/// This function goes through and does final semantic checking for these
1338/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00001339ExprResult
1340Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001341 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00001342 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1343 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1344
1345 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001346 if (TheCall->getNumArgs() < 1) {
1347 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1348 << 0 << 1 << TheCall->getNumArgs()
1349 << TheCall->getCallee()->getSourceRange();
1350 return ExprError();
1351 }
Mike Stump11289f42009-09-09 15:08:12 +00001352
Chris Lattnerdc046542009-05-08 06:58:22 +00001353 // Inspect the first argument of the atomic builtin. This should always be
1354 // a pointer type, whose element is an integral scalar or pointer type.
1355 // Because it is a pointer type, we don't have to worry about any implicit
1356 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001357 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00001358 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00001359 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1360 if (FirstArgResult.isInvalid())
1361 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001362 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00001363 TheCall->setArg(0, FirstArg);
1364
John McCall31168b02011-06-15 23:02:42 +00001365 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1366 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001367 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1368 << FirstArg->getType() << FirstArg->getSourceRange();
1369 return ExprError();
1370 }
Mike Stump11289f42009-09-09 15:08:12 +00001371
John McCall31168b02011-06-15 23:02:42 +00001372 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00001373 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001374 !ValType->isBlockPointerType()) {
1375 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1376 << FirstArg->getType() << FirstArg->getSourceRange();
1377 return ExprError();
1378 }
Chris Lattnerdc046542009-05-08 06:58:22 +00001379
John McCall31168b02011-06-15 23:02:42 +00001380 switch (ValType.getObjCLifetime()) {
1381 case Qualifiers::OCL_None:
1382 case Qualifiers::OCL_ExplicitNone:
1383 // okay
1384 break;
1385
1386 case Qualifiers::OCL_Weak:
1387 case Qualifiers::OCL_Strong:
1388 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00001389 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00001390 << ValType << FirstArg->getSourceRange();
1391 return ExprError();
1392 }
1393
John McCallb50451a2011-10-05 07:41:44 +00001394 // Strip any qualifiers off ValType.
1395 ValType = ValType.getUnqualifiedType();
1396
Chandler Carruth3973af72010-07-18 20:54:12 +00001397 // The majority of builtins return a value, but a few have special return
1398 // types, so allow them to override appropriately below.
1399 QualType ResultType = ValType;
1400
Chris Lattnerdc046542009-05-08 06:58:22 +00001401 // We need to figure out which concrete builtin this maps onto. For example,
1402 // __sync_fetch_and_add with a 2 byte object turns into
1403 // __sync_fetch_and_add_2.
1404#define BUILTIN_ROW(x) \
1405 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1406 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00001407
Chris Lattnerdc046542009-05-08 06:58:22 +00001408 static const unsigned BuiltinIndices[][5] = {
1409 BUILTIN_ROW(__sync_fetch_and_add),
1410 BUILTIN_ROW(__sync_fetch_and_sub),
1411 BUILTIN_ROW(__sync_fetch_and_or),
1412 BUILTIN_ROW(__sync_fetch_and_and),
1413 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump11289f42009-09-09 15:08:12 +00001414
Chris Lattnerdc046542009-05-08 06:58:22 +00001415 BUILTIN_ROW(__sync_add_and_fetch),
1416 BUILTIN_ROW(__sync_sub_and_fetch),
1417 BUILTIN_ROW(__sync_and_and_fetch),
1418 BUILTIN_ROW(__sync_or_and_fetch),
1419 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00001420
Chris Lattnerdc046542009-05-08 06:58:22 +00001421 BUILTIN_ROW(__sync_val_compare_and_swap),
1422 BUILTIN_ROW(__sync_bool_compare_and_swap),
1423 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00001424 BUILTIN_ROW(__sync_lock_release),
1425 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00001426 };
Mike Stump11289f42009-09-09 15:08:12 +00001427#undef BUILTIN_ROW
1428
Chris Lattnerdc046542009-05-08 06:58:22 +00001429 // Determine the index of the size.
1430 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00001431 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00001432 case 1: SizeIndex = 0; break;
1433 case 2: SizeIndex = 1; break;
1434 case 4: SizeIndex = 2; break;
1435 case 8: SizeIndex = 3; break;
1436 case 16: SizeIndex = 4; break;
1437 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001438 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1439 << FirstArg->getType() << FirstArg->getSourceRange();
1440 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00001441 }
Mike Stump11289f42009-09-09 15:08:12 +00001442
Chris Lattnerdc046542009-05-08 06:58:22 +00001443 // Each of these builtins has one pointer argument, followed by some number of
1444 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1445 // that we ignore. Find out which row of BuiltinIndices to read from as well
1446 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00001447 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00001448 unsigned BuiltinIndex, NumFixed = 1;
1449 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00001450 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00001451 case Builtin::BI__sync_fetch_and_add:
1452 case Builtin::BI__sync_fetch_and_add_1:
1453 case Builtin::BI__sync_fetch_and_add_2:
1454 case Builtin::BI__sync_fetch_and_add_4:
1455 case Builtin::BI__sync_fetch_and_add_8:
1456 case Builtin::BI__sync_fetch_and_add_16:
1457 BuiltinIndex = 0;
1458 break;
1459
1460 case Builtin::BI__sync_fetch_and_sub:
1461 case Builtin::BI__sync_fetch_and_sub_1:
1462 case Builtin::BI__sync_fetch_and_sub_2:
1463 case Builtin::BI__sync_fetch_and_sub_4:
1464 case Builtin::BI__sync_fetch_and_sub_8:
1465 case Builtin::BI__sync_fetch_and_sub_16:
1466 BuiltinIndex = 1;
1467 break;
1468
1469 case Builtin::BI__sync_fetch_and_or:
1470 case Builtin::BI__sync_fetch_and_or_1:
1471 case Builtin::BI__sync_fetch_and_or_2:
1472 case Builtin::BI__sync_fetch_and_or_4:
1473 case Builtin::BI__sync_fetch_and_or_8:
1474 case Builtin::BI__sync_fetch_and_or_16:
1475 BuiltinIndex = 2;
1476 break;
1477
1478 case Builtin::BI__sync_fetch_and_and:
1479 case Builtin::BI__sync_fetch_and_and_1:
1480 case Builtin::BI__sync_fetch_and_and_2:
1481 case Builtin::BI__sync_fetch_and_and_4:
1482 case Builtin::BI__sync_fetch_and_and_8:
1483 case Builtin::BI__sync_fetch_and_and_16:
1484 BuiltinIndex = 3;
1485 break;
Mike Stump11289f42009-09-09 15:08:12 +00001486
Douglas Gregor73722482011-11-28 16:30:08 +00001487 case Builtin::BI__sync_fetch_and_xor:
1488 case Builtin::BI__sync_fetch_and_xor_1:
1489 case Builtin::BI__sync_fetch_and_xor_2:
1490 case Builtin::BI__sync_fetch_and_xor_4:
1491 case Builtin::BI__sync_fetch_and_xor_8:
1492 case Builtin::BI__sync_fetch_and_xor_16:
1493 BuiltinIndex = 4;
1494 break;
1495
1496 case Builtin::BI__sync_add_and_fetch:
1497 case Builtin::BI__sync_add_and_fetch_1:
1498 case Builtin::BI__sync_add_and_fetch_2:
1499 case Builtin::BI__sync_add_and_fetch_4:
1500 case Builtin::BI__sync_add_and_fetch_8:
1501 case Builtin::BI__sync_add_and_fetch_16:
1502 BuiltinIndex = 5;
1503 break;
1504
1505 case Builtin::BI__sync_sub_and_fetch:
1506 case Builtin::BI__sync_sub_and_fetch_1:
1507 case Builtin::BI__sync_sub_and_fetch_2:
1508 case Builtin::BI__sync_sub_and_fetch_4:
1509 case Builtin::BI__sync_sub_and_fetch_8:
1510 case Builtin::BI__sync_sub_and_fetch_16:
1511 BuiltinIndex = 6;
1512 break;
1513
1514 case Builtin::BI__sync_and_and_fetch:
1515 case Builtin::BI__sync_and_and_fetch_1:
1516 case Builtin::BI__sync_and_and_fetch_2:
1517 case Builtin::BI__sync_and_and_fetch_4:
1518 case Builtin::BI__sync_and_and_fetch_8:
1519 case Builtin::BI__sync_and_and_fetch_16:
1520 BuiltinIndex = 7;
1521 break;
1522
1523 case Builtin::BI__sync_or_and_fetch:
1524 case Builtin::BI__sync_or_and_fetch_1:
1525 case Builtin::BI__sync_or_and_fetch_2:
1526 case Builtin::BI__sync_or_and_fetch_4:
1527 case Builtin::BI__sync_or_and_fetch_8:
1528 case Builtin::BI__sync_or_and_fetch_16:
1529 BuiltinIndex = 8;
1530 break;
1531
1532 case Builtin::BI__sync_xor_and_fetch:
1533 case Builtin::BI__sync_xor_and_fetch_1:
1534 case Builtin::BI__sync_xor_and_fetch_2:
1535 case Builtin::BI__sync_xor_and_fetch_4:
1536 case Builtin::BI__sync_xor_and_fetch_8:
1537 case Builtin::BI__sync_xor_and_fetch_16:
1538 BuiltinIndex = 9;
1539 break;
Mike Stump11289f42009-09-09 15:08:12 +00001540
Chris Lattnerdc046542009-05-08 06:58:22 +00001541 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001542 case Builtin::BI__sync_val_compare_and_swap_1:
1543 case Builtin::BI__sync_val_compare_and_swap_2:
1544 case Builtin::BI__sync_val_compare_and_swap_4:
1545 case Builtin::BI__sync_val_compare_and_swap_8:
1546 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001547 BuiltinIndex = 10;
Chris Lattnerdc046542009-05-08 06:58:22 +00001548 NumFixed = 2;
1549 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001550
Chris Lattnerdc046542009-05-08 06:58:22 +00001551 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001552 case Builtin::BI__sync_bool_compare_and_swap_1:
1553 case Builtin::BI__sync_bool_compare_and_swap_2:
1554 case Builtin::BI__sync_bool_compare_and_swap_4:
1555 case Builtin::BI__sync_bool_compare_and_swap_8:
1556 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001557 BuiltinIndex = 11;
Chris Lattnerdc046542009-05-08 06:58:22 +00001558 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00001559 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001560 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001561
1562 case Builtin::BI__sync_lock_test_and_set:
1563 case Builtin::BI__sync_lock_test_and_set_1:
1564 case Builtin::BI__sync_lock_test_and_set_2:
1565 case Builtin::BI__sync_lock_test_and_set_4:
1566 case Builtin::BI__sync_lock_test_and_set_8:
1567 case Builtin::BI__sync_lock_test_and_set_16:
1568 BuiltinIndex = 12;
1569 break;
1570
Chris Lattnerdc046542009-05-08 06:58:22 +00001571 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00001572 case Builtin::BI__sync_lock_release_1:
1573 case Builtin::BI__sync_lock_release_2:
1574 case Builtin::BI__sync_lock_release_4:
1575 case Builtin::BI__sync_lock_release_8:
1576 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001577 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00001578 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00001579 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001580 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001581
1582 case Builtin::BI__sync_swap:
1583 case Builtin::BI__sync_swap_1:
1584 case Builtin::BI__sync_swap_2:
1585 case Builtin::BI__sync_swap_4:
1586 case Builtin::BI__sync_swap_8:
1587 case Builtin::BI__sync_swap_16:
1588 BuiltinIndex = 14;
1589 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00001590 }
Mike Stump11289f42009-09-09 15:08:12 +00001591
Chris Lattnerdc046542009-05-08 06:58:22 +00001592 // Now that we know how many fixed arguments we expect, first check that we
1593 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001594 if (TheCall->getNumArgs() < 1+NumFixed) {
1595 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1596 << 0 << 1+NumFixed << TheCall->getNumArgs()
1597 << TheCall->getCallee()->getSourceRange();
1598 return ExprError();
1599 }
Mike Stump11289f42009-09-09 15:08:12 +00001600
Chris Lattner5b9241b2009-05-08 15:36:58 +00001601 // Get the decl for the concrete builtin from this, we can tell what the
1602 // concrete integer type we should convert to is.
1603 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1604 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001605 FunctionDecl *NewBuiltinDecl;
1606 if (NewBuiltinID == BuiltinID)
1607 NewBuiltinDecl = FDecl;
1608 else {
1609 // Perform builtin lookup to avoid redeclaring it.
1610 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1611 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1612 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1613 assert(Res.getFoundDecl());
1614 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00001615 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001616 return ExprError();
1617 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001618
John McCallcf142162010-08-07 06:22:56 +00001619 // The first argument --- the pointer --- has a fixed type; we
1620 // deduce the types of the rest of the arguments accordingly. Walk
1621 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00001622 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00001623 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00001624
Chris Lattnerdc046542009-05-08 06:58:22 +00001625 // GCC does an implicit conversion to the pointer or integer ValType. This
1626 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00001627 // Initialize the argument.
1628 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1629 ValType, /*consume*/ false);
1630 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00001631 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001632 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001633
Chris Lattnerdc046542009-05-08 06:58:22 +00001634 // Okay, we have something that *can* be converted to the right type. Check
1635 // to see if there is a potentially weird extension going on here. This can
1636 // happen when you do an atomic operation on something like an char* and
1637 // pass in 42. The 42 gets converted to char. This is even more strange
1638 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00001639 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001640 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00001641 }
Mike Stump11289f42009-09-09 15:08:12 +00001642
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001643 ASTContext& Context = this->getASTContext();
1644
1645 // Create a new DeclRefExpr to refer to the new decl.
1646 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1647 Context,
1648 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001649 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001650 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00001651 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001652 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00001653 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001654 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00001655
Chris Lattnerdc046542009-05-08 06:58:22 +00001656 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00001657 // FIXME: This loses syntactic information.
1658 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1659 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1660 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001661 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00001662
Chandler Carruthbc8cab12010-07-18 07:23:17 +00001663 // Change the result type of the call to match the original value type. This
1664 // is arbitrary, but the codegen for these builtins ins design to handle it
1665 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00001666 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001667
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001668 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00001669}
1670
Chris Lattner6436fb62009-02-18 06:01:06 +00001671/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00001672/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00001673/// Note: It might also make sense to do the UTF-16 conversion here (would
1674/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00001675bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00001676 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00001677 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1678
Douglas Gregorfb65e592011-07-27 05:40:30 +00001679 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00001680 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1681 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00001682 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00001683 }
Mike Stump11289f42009-09-09 15:08:12 +00001684
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001685 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001686 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001687 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001688 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00001689 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001690 UTF16 *ToPtr = &ToBuf[0];
1691
1692 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1693 &ToPtr, ToPtr + NumBytes,
1694 strictConversion);
1695 // Check for conversion failure.
1696 if (Result != conversionOK)
1697 Diag(Arg->getLocStart(),
1698 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1699 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00001700 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001701}
1702
Chris Lattnere202e6a2007-12-20 00:05:45 +00001703/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1704/// Emit an error and return true on failure, return false on success.
Chris Lattner08464942007-12-28 05:29:59 +00001705bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1706 Expr *Fn = TheCall->getCallee();
1707 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00001708 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001709 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001710 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1711 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00001712 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001713 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00001714 return true;
1715 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00001716
1717 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00001718 return Diag(TheCall->getLocEnd(),
1719 diag::err_typecheck_call_too_few_args_at_least)
1720 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00001721 }
1722
John McCall29ad95b2011-08-27 01:09:30 +00001723 // Type-check the first argument normally.
1724 if (checkBuiltinArgument(*this, TheCall, 0))
1725 return true;
1726
Chris Lattnere202e6a2007-12-20 00:05:45 +00001727 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00001728 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00001729 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00001730 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00001731 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00001732 else if (FunctionDecl *FD = getCurFunctionDecl())
1733 isVariadic = FD->isVariadic();
1734 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001735 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00001736
Chris Lattnere202e6a2007-12-20 00:05:45 +00001737 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00001738 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1739 return true;
1740 }
Mike Stump11289f42009-09-09 15:08:12 +00001741
Chris Lattner43be2e62007-12-19 23:59:04 +00001742 // Verify that the second argument to the builtin is the last argument of the
1743 // current function or method.
1744 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00001745 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00001746
Nico Weber9eea7642013-05-24 23:31:57 +00001747 // These are valid if SecondArgIsLastNamedArgument is false after the next
1748 // block.
1749 QualType Type;
1750 SourceLocation ParamLoc;
1751
Anders Carlsson6a8350b2008-02-11 04:20:54 +00001752 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1753 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00001754 // FIXME: This isn't correct for methods (results in bogus warning).
1755 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00001756 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00001757 if (CurBlock)
1758 LastArg = *(CurBlock->TheDecl->param_end()-1);
1759 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00001760 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00001761 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001762 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00001763 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00001764
1765 Type = PV->getType();
1766 ParamLoc = PV->getLocation();
Chris Lattner43be2e62007-12-19 23:59:04 +00001767 }
1768 }
Mike Stump11289f42009-09-09 15:08:12 +00001769
Chris Lattner43be2e62007-12-19 23:59:04 +00001770 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001771 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +00001772 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weber9eea7642013-05-24 23:31:57 +00001773 else if (Type->isReferenceType()) {
1774 Diag(Arg->getLocStart(),
1775 diag::warn_va_start_of_reference_type_is_undefined);
1776 Diag(ParamLoc, diag::note_parameter_type) << Type;
1777 }
1778
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00001779 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00001780 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00001781}
Chris Lattner43be2e62007-12-19 23:59:04 +00001782
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00001783bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
1784 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
1785 // const char *named_addr);
1786
1787 Expr *Func = Call->getCallee();
1788
1789 if (Call->getNumArgs() < 3)
1790 return Diag(Call->getLocEnd(),
1791 diag::err_typecheck_call_too_few_args_at_least)
1792 << 0 /*function call*/ << 3 << Call->getNumArgs();
1793
1794 // Determine whether the current function is variadic or not.
1795 bool IsVariadic;
1796 if (BlockScopeInfo *CurBlock = getCurBlock())
1797 IsVariadic = CurBlock->TheDecl->isVariadic();
1798 else if (FunctionDecl *FD = getCurFunctionDecl())
1799 IsVariadic = FD->isVariadic();
1800 else if (ObjCMethodDecl *MD = getCurMethodDecl())
1801 IsVariadic = MD->isVariadic();
1802 else
1803 llvm_unreachable("unexpected statement type");
1804
1805 if (!IsVariadic) {
1806 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1807 return true;
1808 }
1809
1810 // Type-check the first argument normally.
1811 if (checkBuiltinArgument(*this, Call, 0))
1812 return true;
1813
1814 static const struct {
1815 unsigned ArgNo;
1816 QualType Type;
1817 } ArgumentTypes[] = {
1818 { 1, Context.getPointerType(Context.CharTy.withConst()) },
1819 { 2, Context.getSizeType() },
1820 };
1821
1822 for (const auto &AT : ArgumentTypes) {
1823 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
1824 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
1825 continue;
1826 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
1827 << Arg->getType() << AT.Type << 1 /* different class */
1828 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
1829 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
1830 }
1831
1832 return false;
1833}
1834
Chris Lattner2da14fb2007-12-20 00:26:33 +00001835/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1836/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00001837bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1838 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00001839 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00001840 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00001841 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00001842 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001843 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001844 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00001845 << SourceRange(TheCall->getArg(2)->getLocStart(),
1846 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00001847
John Wiegley01296292011-04-08 18:41:53 +00001848 ExprResult OrigArg0 = TheCall->getArg(0);
1849 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00001850
Chris Lattner2da14fb2007-12-20 00:26:33 +00001851 // Do standard promotions between the two arguments, returning their common
1852 // type.
Chris Lattner08464942007-12-28 05:29:59 +00001853 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00001854 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1855 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00001856
1857 // Make sure any conversions are pushed back into the call; this is
1858 // type safe since unordered compare builtins are declared as "_Bool
1859 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00001860 TheCall->setArg(0, OrigArg0.get());
1861 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00001862
John Wiegley01296292011-04-08 18:41:53 +00001863 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00001864 return false;
1865
Chris Lattner2da14fb2007-12-20 00:26:33 +00001866 // If the common type isn't a real floating type, then the arguments were
1867 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00001868 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00001869 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001870 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00001871 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1872 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00001873
Chris Lattner2da14fb2007-12-20 00:26:33 +00001874 return false;
1875}
1876
Benjamin Kramer634fc102010-02-15 22:42:31 +00001877/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1878/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00001879/// to check everything. We expect the last argument to be a floating point
1880/// value.
1881bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1882 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00001883 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00001884 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00001885 if (TheCall->getNumArgs() > NumArgs)
1886 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001887 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001888 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00001889 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001890 (*(TheCall->arg_end()-1))->getLocEnd());
1891
Benjamin Kramer64aae502010-02-16 10:07:31 +00001892 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00001893
Eli Friedman7e4faac2009-08-31 20:06:00 +00001894 if (OrigArg->isTypeDependent())
1895 return false;
1896
Chris Lattner68784ef2010-05-06 05:50:07 +00001897 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00001898 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00001899 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001900 diag::err_typecheck_call_invalid_unary_fp)
1901 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001902
Chris Lattner68784ef2010-05-06 05:50:07 +00001903 // If this is an implicit conversion from float -> double, remove it.
1904 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1905 Expr *CastArg = Cast->getSubExpr();
1906 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1907 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1908 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00001909 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00001910 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00001911 }
1912 }
1913
Eli Friedman7e4faac2009-08-31 20:06:00 +00001914 return false;
1915}
1916
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001917/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1918// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00001919ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00001920 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001921 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00001922 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00001923 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1924 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001925
Nate Begemana0110022010-06-08 00:16:34 +00001926 // Determine which of the following types of shufflevector we're checking:
1927 // 1) unary, vector mask: (lhs, mask)
1928 // 2) binary, vector mask: (lhs, rhs, mask)
1929 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1930 QualType resType = TheCall->getArg(0)->getType();
1931 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00001932
Douglas Gregorc25f7662009-05-19 22:10:17 +00001933 if (!TheCall->getArg(0)->isTypeDependent() &&
1934 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00001935 QualType LHSType = TheCall->getArg(0)->getType();
1936 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00001937
Craig Topperbaca3892013-07-29 06:47:04 +00001938 if (!LHSType->isVectorType() || !RHSType->isVectorType())
1939 return ExprError(Diag(TheCall->getLocStart(),
1940 diag::err_shufflevector_non_vector)
1941 << SourceRange(TheCall->getArg(0)->getLocStart(),
1942 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00001943
Nate Begemana0110022010-06-08 00:16:34 +00001944 numElements = LHSType->getAs<VectorType>()->getNumElements();
1945 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00001946
Nate Begemana0110022010-06-08 00:16:34 +00001947 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1948 // with mask. If so, verify that RHS is an integer vector type with the
1949 // same number of elts as lhs.
1950 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00001951 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00001952 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00001953 return ExprError(Diag(TheCall->getLocStart(),
1954 diag::err_shufflevector_incompatible_vector)
1955 << SourceRange(TheCall->getArg(1)->getLocStart(),
1956 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00001957 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00001958 return ExprError(Diag(TheCall->getLocStart(),
1959 diag::err_shufflevector_incompatible_vector)
1960 << SourceRange(TheCall->getArg(0)->getLocStart(),
1961 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00001962 } else if (numElements != numResElements) {
1963 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00001964 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001965 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00001966 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001967 }
1968
1969 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00001970 if (TheCall->getArg(i)->isTypeDependent() ||
1971 TheCall->getArg(i)->isValueDependent())
1972 continue;
1973
Nate Begemana0110022010-06-08 00:16:34 +00001974 llvm::APSInt Result(32);
1975 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1976 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00001977 diag::err_shufflevector_nonconstant_argument)
1978 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001979
Craig Topper50ad5b72013-08-03 17:40:38 +00001980 // Allow -1 which will be translated to undef in the IR.
1981 if (Result.isSigned() && Result.isAllOnesValue())
1982 continue;
1983
Chris Lattner7ab824e2008-08-10 02:05:13 +00001984 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001985 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00001986 diag::err_shufflevector_argument_too_large)
1987 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001988 }
1989
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001990 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001991
Chris Lattner7ab824e2008-08-10 02:05:13 +00001992 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001993 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00001994 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001995 }
1996
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001997 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
1998 TheCall->getCallee()->getLocStart(),
1999 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002000}
Chris Lattner43be2e62007-12-19 23:59:04 +00002001
Hal Finkelc4d7c822013-09-18 03:29:45 +00002002/// SemaConvertVectorExpr - Handle __builtin_convertvector
2003ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
2004 SourceLocation BuiltinLoc,
2005 SourceLocation RParenLoc) {
2006 ExprValueKind VK = VK_RValue;
2007 ExprObjectKind OK = OK_Ordinary;
2008 QualType DstTy = TInfo->getType();
2009 QualType SrcTy = E->getType();
2010
2011 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
2012 return ExprError(Diag(BuiltinLoc,
2013 diag::err_convertvector_non_vector)
2014 << E->getSourceRange());
2015 if (!DstTy->isVectorType() && !DstTy->isDependentType())
2016 return ExprError(Diag(BuiltinLoc,
2017 diag::err_convertvector_non_vector_type));
2018
2019 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
2020 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
2021 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
2022 if (SrcElts != DstElts)
2023 return ExprError(Diag(BuiltinLoc,
2024 diag::err_convertvector_incompatible_vector)
2025 << E->getSourceRange());
2026 }
2027
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002028 return new (Context)
2029 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00002030}
2031
Daniel Dunbarb7257262008-07-21 22:59:13 +00002032/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
2033// This is declared to take (const void*, ...) and can take two
2034// optional constant int args.
2035bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00002036 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002037
Chris Lattner3b054132008-11-19 05:08:23 +00002038 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002039 return Diag(TheCall->getLocEnd(),
2040 diag::err_typecheck_call_too_many_args_at_most)
2041 << 0 /*function call*/ << 3 << NumArgs
2042 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002043
2044 // Argument 0 is checked for us and the remaining arguments must be
2045 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00002046 for (unsigned i = 1; i != NumArgs; ++i)
2047 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002048 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002049
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002050 return false;
2051}
2052
Hal Finkelf0417332014-07-17 14:25:55 +00002053/// SemaBuiltinAssume - Handle __assume (MS Extension).
2054// __assume does not evaluate its arguments, and should warn if its argument
2055// has side effects.
2056bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
2057 Expr *Arg = TheCall->getArg(0);
2058 if (Arg->isInstantiationDependent()) return false;
2059
2060 if (Arg->HasSideEffects(Context))
2061 return Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
2062 << Arg->getSourceRange();
2063
2064 return false;
2065}
2066
Eric Christopher8d0c6212010-04-17 02:26:23 +00002067/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2068/// TheCall is a constant expression.
2069bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
2070 llvm::APSInt &Result) {
2071 Expr *Arg = TheCall->getArg(ArgNum);
2072 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2073 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2074
2075 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
2076
2077 if (!Arg->isIntegerConstantExpr(Result, Context))
2078 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00002079 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00002080
Chris Lattnerd545ad12009-09-23 06:06:36 +00002081 return false;
2082}
2083
Richard Sandiford28940af2014-04-16 08:47:51 +00002084/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
2085/// TheCall is a constant expression in the range [Low, High].
2086bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
2087 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00002088 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002089
2090 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00002091 Expr *Arg = TheCall->getArg(ArgNum);
2092 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002093 return false;
2094
Eric Christopher8d0c6212010-04-17 02:26:23 +00002095 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00002096 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002097 return true;
2098
Richard Sandiford28940af2014-04-16 08:47:51 +00002099 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00002100 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00002101 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00002102
2103 return false;
2104}
2105
Eli Friedmanc97d0142009-05-03 06:04:26 +00002106/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002107/// This checks that val is a constant 1.
2108bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
2109 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00002110 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00002111
Eric Christopher8d0c6212010-04-17 02:26:23 +00002112 // TODO: This is less than ideal. Overload this to take a value.
2113 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2114 return true;
2115
2116 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002117 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
2118 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
2119
2120 return false;
2121}
2122
Richard Smithd7293d72013-08-05 18:49:43 +00002123namespace {
2124enum StringLiteralCheckType {
2125 SLCT_NotALiteral,
2126 SLCT_UncheckedLiteral,
2127 SLCT_CheckedLiteral
2128};
2129}
2130
Richard Smith55ce3522012-06-25 20:30:08 +00002131// Determine if an expression is a string literal or constant string.
2132// If this function returns false on the arguments to a function expecting a
2133// format string, we will usually need to emit a warning.
2134// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00002135static StringLiteralCheckType
2136checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
2137 bool HasVAListArg, unsigned format_idx,
2138 unsigned firstDataArg, Sema::FormatStringType Type,
2139 Sema::VariadicCallType CallType, bool InFunctionCall,
2140 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek808829352010-09-09 03:51:39 +00002141 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00002142 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00002143 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002144
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002145 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00002146
Richard Smithd7293d72013-08-05 18:49:43 +00002147 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00002148 // Technically -Wformat-nonliteral does not warn about this case.
2149 // The behavior of printf and friends in this case is implementation
2150 // dependent. Ideally if the format string cannot be null then
2151 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00002152 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00002153
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002154 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00002155 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002156 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00002157 // The expression is a literal if both sub-expressions were, and it was
2158 // completely checked only if both sub-expressions were checked.
2159 const AbstractConditionalOperator *C =
2160 cast<AbstractConditionalOperator>(E);
2161 StringLiteralCheckType Left =
Richard Smithd7293d72013-08-05 18:49:43 +00002162 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002163 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002164 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002165 if (Left == SLCT_NotALiteral)
2166 return SLCT_NotALiteral;
2167 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00002168 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002169 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002170 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002171 return Left < Right ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002172 }
2173
2174 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00002175 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2176 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002177 }
2178
John McCallc07a0c72011-02-17 10:25:35 +00002179 case Stmt::OpaqueValueExprClass:
2180 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2181 E = src;
2182 goto tryAgain;
2183 }
Richard Smith55ce3522012-06-25 20:30:08 +00002184 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00002185
Ted Kremeneka8890832011-02-24 23:03:04 +00002186 case Stmt::PredefinedExprClass:
2187 // While __func__, etc., are technically not string literals, they
2188 // cannot contain format specifiers and thus are not a security
2189 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00002190 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00002191
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002192 case Stmt::DeclRefExprClass: {
2193 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002194
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002195 // As an exception, do not flag errors for variables binding to
2196 // const string literals.
2197 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2198 bool isConstant = false;
2199 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002200
Richard Smithd7293d72013-08-05 18:49:43 +00002201 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2202 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00002203 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00002204 isConstant = T.isConstant(S.Context) &&
2205 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00002206 } else if (T->isObjCObjectPointerType()) {
2207 // In ObjC, there is usually no "const ObjectPointer" type,
2208 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00002209 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002210 }
Mike Stump11289f42009-09-09 15:08:12 +00002211
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002212 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002213 if (const Expr *Init = VD->getAnyInitializer()) {
2214 // Look through initializers like const char c[] = { "foo" }
2215 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2216 if (InitList->isStringLiteralInit())
2217 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2218 }
Richard Smithd7293d72013-08-05 18:49:43 +00002219 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002220 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002221 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002222 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002223 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002224 }
Mike Stump11289f42009-09-09 15:08:12 +00002225
Anders Carlssonb012ca92009-06-28 19:55:58 +00002226 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2227 // special check to see if the format string is a function parameter
2228 // of the function calling the printf function. If the function
2229 // has an attribute indicating it is a printf-like function, then we
2230 // should suppress warnings concerning non-literals being used in a call
2231 // to a vprintf function. For example:
2232 //
2233 // void
2234 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2235 // va_list ap;
2236 // va_start(ap, fmt);
2237 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2238 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00002239 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002240 if (HasVAListArg) {
2241 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2242 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2243 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002244 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002245 // adjust for implicit parameter
2246 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2247 if (MD->isInstance())
2248 ++PVIndex;
2249 // We also check if the formats are compatible.
2250 // We can't pass a 'scanf' string to a 'printf' function.
2251 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00002252 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00002253 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002254 }
2255 }
2256 }
2257 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002258 }
Mike Stump11289f42009-09-09 15:08:12 +00002259
Richard Smith55ce3522012-06-25 20:30:08 +00002260 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002261 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002262
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002263 case Stmt::CallExprClass:
2264 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002265 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002266 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2267 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2268 unsigned ArgIndex = FA->getFormatIdx();
2269 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2270 if (MD->isInstance())
2271 --ArgIndex;
2272 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00002273
Richard Smithd7293d72013-08-05 18:49:43 +00002274 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002275 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002276 Type, CallType, InFunctionCall,
2277 CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002278 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2279 unsigned BuiltinID = FD->getBuiltinID();
2280 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2281 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2282 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00002283 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002284 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002285 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002286 InFunctionCall, CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002287 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002288 }
2289 }
Mike Stump11289f42009-09-09 15:08:12 +00002290
Richard Smith55ce3522012-06-25 20:30:08 +00002291 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002292 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002293 case Stmt::ObjCStringLiteralClass:
2294 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00002295 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002296
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002297 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002298 StrE = ObjCFExpr->getString();
2299 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002300 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002301
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002302 if (StrE) {
Richard Smithd7293d72013-08-05 18:49:43 +00002303 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2304 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002305 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002306 }
Mike Stump11289f42009-09-09 15:08:12 +00002307
Richard Smith55ce3522012-06-25 20:30:08 +00002308 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002309 }
Mike Stump11289f42009-09-09 15:08:12 +00002310
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002311 default:
Richard Smith55ce3522012-06-25 20:30:08 +00002312 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002313 }
2314}
2315
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002316Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00002317 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002318 .Case("scanf", FST_Scanf)
2319 .Cases("printf", "printf0", FST_Printf)
2320 .Cases("NSString", "CFString", FST_NSString)
2321 .Case("strftime", FST_Strftime)
2322 .Case("strfmon", FST_Strfmon)
2323 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
2324 .Default(FST_Unknown);
2325}
2326
Jordan Rose3e0ec582012-07-19 18:10:23 +00002327/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00002328/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002329/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002330bool Sema::CheckFormatArguments(const FormatAttr *Format,
2331 ArrayRef<const Expr *> Args,
2332 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002333 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002334 SourceLocation Loc, SourceRange Range,
2335 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00002336 FormatStringInfo FSI;
2337 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002338 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00002339 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00002340 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002341 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002342}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00002343
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002344bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002345 bool HasVAListArg, unsigned format_idx,
2346 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002347 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002348 SourceLocation Loc, SourceRange Range,
2349 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00002350 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002351 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002352 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00002353 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002354 }
Mike Stump11289f42009-09-09 15:08:12 +00002355
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002356 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002357
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002358 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00002359 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002360 // Dynamically generated format strings are difficult to
2361 // automatically vet at compile time. Requiring that format strings
2362 // are string literals: (1) permits the checking of format strings by
2363 // the compiler and thereby (2) can practically remove the source of
2364 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00002365
Mike Stump11289f42009-09-09 15:08:12 +00002366 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00002367 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00002368 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00002369 // the same format string checking logic for both ObjC and C strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002370 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00002371 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2372 format_idx, firstDataArg, Type, CallType,
2373 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002374 if (CT != SLCT_NotALiteral)
2375 // Literal format string found, check done!
2376 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00002377
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002378 // Strftime is particular as it always uses a single 'time' argument,
2379 // so it is safe to pass a non-literal string.
2380 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00002381 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002382
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002383 // Do not emit diag when the string param is a macro expansion and the
2384 // format is either NSString or CFString. This is a hack to prevent
2385 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2386 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupas2b7da832012-05-04 21:08:08 +00002387 if (Type == FST_NSString &&
2388 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith55ce3522012-06-25 20:30:08 +00002389 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002390
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002391 // If there are no arguments specified, warn with -Wformat-security, otherwise
2392 // warn only with -Wformat-nonliteral.
Eli Friedman0e5d6772013-06-18 18:10:01 +00002393 if (Args.size() == firstDataArg)
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002394 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002395 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002396 << OrigFormatExpr->getSourceRange();
2397 else
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002398 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002399 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002400 << OrigFormatExpr->getSourceRange();
Richard Smith55ce3522012-06-25 20:30:08 +00002401 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002402}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002403
Ted Kremenekab278de2010-01-28 23:39:18 +00002404namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00002405class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2406protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00002407 Sema &S;
2408 const StringLiteral *FExpr;
2409 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002410 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00002411 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00002412 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00002413 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002414 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00002415 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00002416 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00002417 bool usesPositionalArgs;
2418 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00002419 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00002420 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00002421 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002422public:
Ted Kremenek02087932010-07-16 02:11:22 +00002423 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002424 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002425 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002426 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002427 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002428 Sema::VariadicCallType callType,
2429 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremenekab278de2010-01-28 23:39:18 +00002430 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002431 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2432 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002433 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00002434 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00002435 inFunctionCall(inFunctionCall), CallType(callType),
2436 CheckedVarArgs(CheckedVarArgs) {
2437 CoveredArgs.resize(numDataArgs);
2438 CoveredArgs.reset();
2439 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002440
Ted Kremenek019d2242010-01-29 01:50:07 +00002441 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002442
Ted Kremenek02087932010-07-16 02:11:22 +00002443 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002444 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002445
Jordan Rose92303592012-09-08 04:00:03 +00002446 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002447 const analyze_format_string::FormatSpecifier &FS,
2448 const analyze_format_string::ConversionSpecifier &CS,
2449 const char *startSpecifier, unsigned specifierLen,
2450 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00002451
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002452 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002453 const analyze_format_string::FormatSpecifier &FS,
2454 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002455
2456 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002457 const analyze_format_string::ConversionSpecifier &CS,
2458 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002459
Craig Toppere14c0f82014-03-12 04:55:44 +00002460 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002461
Craig Toppere14c0f82014-03-12 04:55:44 +00002462 void HandleInvalidPosition(const char *startSpecifier,
2463 unsigned specifierLen,
2464 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002465
Craig Toppere14c0f82014-03-12 04:55:44 +00002466 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002467
Craig Toppere14c0f82014-03-12 04:55:44 +00002468 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002469
Richard Trieu03cf7b72011-10-28 00:41:25 +00002470 template <typename Range>
2471 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2472 const Expr *ArgumentExpr,
2473 PartialDiagnostic PDiag,
2474 SourceLocation StringLoc,
2475 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002476 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002477
Ted Kremenek02087932010-07-16 02:11:22 +00002478protected:
Ted Kremenekce815422010-07-19 21:25:57 +00002479 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2480 const char *startSpec,
2481 unsigned specifierLen,
2482 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002483
2484 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2485 const char *startSpec,
2486 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00002487
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002488 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00002489 CharSourceRange getSpecifierRange(const char *startSpecifier,
2490 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00002491 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002492
Ted Kremenek5739de72010-01-29 01:06:55 +00002493 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002494
2495 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2496 const analyze_format_string::ConversionSpecifier &CS,
2497 const char *startSpecifier, unsigned specifierLen,
2498 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002499
2500 template <typename Range>
2501 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2502 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002503 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00002504};
2505}
2506
Ted Kremenek02087932010-07-16 02:11:22 +00002507SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00002508 return OrigFormatExpr->getSourceRange();
2509}
2510
Ted Kremenek02087932010-07-16 02:11:22 +00002511CharSourceRange CheckFormatHandler::
2512getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00002513 SourceLocation Start = getLocationOfByte(startSpecifier);
2514 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2515
2516 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002517 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00002518
2519 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002520}
2521
Ted Kremenek02087932010-07-16 02:11:22 +00002522SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002523 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00002524}
2525
Ted Kremenek02087932010-07-16 02:11:22 +00002526void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2527 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00002528 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2529 getLocationOfByte(startSpecifier),
2530 /*IsStringLocation*/true,
2531 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00002532}
2533
Jordan Rose92303592012-09-08 04:00:03 +00002534void CheckFormatHandler::HandleInvalidLengthModifier(
2535 const analyze_format_string::FormatSpecifier &FS,
2536 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00002537 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00002538 using namespace analyze_format_string;
2539
2540 const LengthModifier &LM = FS.getLengthModifier();
2541 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2542
2543 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002544 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00002545 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002546 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002547 getLocationOfByte(LM.getStart()),
2548 /*IsStringLocation*/true,
2549 getSpecifierRange(startSpecifier, specifierLen));
2550
2551 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2552 << FixedLM->toString()
2553 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2554
2555 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002556 FixItHint Hint;
2557 if (DiagID == diag::warn_format_nonsensical_length)
2558 Hint = FixItHint::CreateRemoval(LMRange);
2559
2560 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002561 getLocationOfByte(LM.getStart()),
2562 /*IsStringLocation*/true,
2563 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00002564 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00002565 }
2566}
2567
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002568void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00002569 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002570 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002571 using namespace analyze_format_string;
2572
2573 const LengthModifier &LM = FS.getLengthModifier();
2574 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2575
2576 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002577 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00002578 if (FixedLM) {
2579 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2580 << LM.toString() << 0,
2581 getLocationOfByte(LM.getStart()),
2582 /*IsStringLocation*/true,
2583 getSpecifierRange(startSpecifier, specifierLen));
2584
2585 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2586 << FixedLM->toString()
2587 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2588
2589 } else {
2590 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2591 << LM.toString() << 0,
2592 getLocationOfByte(LM.getStart()),
2593 /*IsStringLocation*/true,
2594 getSpecifierRange(startSpecifier, specifierLen));
2595 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002596}
2597
2598void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2599 const analyze_format_string::ConversionSpecifier &CS,
2600 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00002601 using namespace analyze_format_string;
2602
2603 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00002604 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00002605 if (FixedCS) {
2606 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2607 << CS.toString() << /*conversion specifier*/1,
2608 getLocationOfByte(CS.getStart()),
2609 /*IsStringLocation*/true,
2610 getSpecifierRange(startSpecifier, specifierLen));
2611
2612 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2613 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2614 << FixedCS->toString()
2615 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2616 } else {
2617 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2618 << CS.toString() << /*conversion specifier*/1,
2619 getLocationOfByte(CS.getStart()),
2620 /*IsStringLocation*/true,
2621 getSpecifierRange(startSpecifier, specifierLen));
2622 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002623}
2624
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002625void CheckFormatHandler::HandlePosition(const char *startPos,
2626 unsigned posLen) {
2627 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2628 getLocationOfByte(startPos),
2629 /*IsStringLocation*/true,
2630 getSpecifierRange(startPos, posLen));
2631}
2632
Ted Kremenekd1668192010-02-27 01:41:03 +00002633void
Ted Kremenek02087932010-07-16 02:11:22 +00002634CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2635 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002636 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2637 << (unsigned) p,
2638 getLocationOfByte(startPos), /*IsStringLocation*/true,
2639 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00002640}
2641
Ted Kremenek02087932010-07-16 02:11:22 +00002642void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00002643 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002644 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2645 getLocationOfByte(startPos),
2646 /*IsStringLocation*/true,
2647 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00002648}
2649
Ted Kremenek02087932010-07-16 02:11:22 +00002650void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002651 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00002652 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002653 EmitFormatDiagnostic(
2654 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2655 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2656 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00002657 }
Ted Kremenek02087932010-07-16 02:11:22 +00002658}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002659
Jordan Rose58bbe422012-07-19 18:10:08 +00002660// Note that this may return NULL if there was an error parsing or building
2661// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00002662const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002663 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00002664}
2665
2666void CheckFormatHandler::DoneProcessing() {
2667 // Does the number of data arguments exceed the number of
2668 // format conversions in the format string?
2669 if (!HasVAListArg) {
2670 // Find any arguments that weren't covered.
2671 CoveredArgs.flip();
2672 signed notCoveredArg = CoveredArgs.find_first();
2673 if (notCoveredArg >= 0) {
2674 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose58bbe422012-07-19 18:10:08 +00002675 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2676 SourceLocation Loc = E->getLocStart();
2677 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2678 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2679 Loc, /*IsStringLocation*/false,
2680 getFormatStringRange());
2681 }
Bob Wilson23cd4342012-05-03 19:47:19 +00002682 }
Ted Kremenek02087932010-07-16 02:11:22 +00002683 }
2684 }
2685}
2686
Ted Kremenekce815422010-07-19 21:25:57 +00002687bool
2688CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2689 SourceLocation Loc,
2690 const char *startSpec,
2691 unsigned specifierLen,
2692 const char *csStart,
2693 unsigned csLen) {
2694
2695 bool keepGoing = true;
2696 if (argIndex < NumDataArgs) {
2697 // Consider the argument coverered, even though the specifier doesn't
2698 // make sense.
2699 CoveredArgs.set(argIndex);
2700 }
2701 else {
2702 // If argIndex exceeds the number of data arguments we
2703 // don't issue a warning because that is just a cascade of warnings (and
2704 // they may have intended '%%' anyway). We don't want to continue processing
2705 // the format string after this point, however, as we will like just get
2706 // gibberish when trying to match arguments.
2707 keepGoing = false;
2708 }
2709
Richard Trieu03cf7b72011-10-28 00:41:25 +00002710 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2711 << StringRef(csStart, csLen),
2712 Loc, /*IsStringLocation*/true,
2713 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekce815422010-07-19 21:25:57 +00002714
2715 return keepGoing;
2716}
2717
Richard Trieu03cf7b72011-10-28 00:41:25 +00002718void
2719CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2720 const char *startSpec,
2721 unsigned specifierLen) {
2722 EmitFormatDiagnostic(
2723 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2724 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2725}
2726
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002727bool
2728CheckFormatHandler::CheckNumArgs(
2729 const analyze_format_string::FormatSpecifier &FS,
2730 const analyze_format_string::ConversionSpecifier &CS,
2731 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2732
2733 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002734 PartialDiagnostic PDiag = FS.usesPositionalArg()
2735 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2736 << (argIndex+1) << NumDataArgs)
2737 : S.PDiag(diag::warn_printf_insufficient_data_args);
2738 EmitFormatDiagnostic(
2739 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2740 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002741 return false;
2742 }
2743 return true;
2744}
2745
Richard Trieu03cf7b72011-10-28 00:41:25 +00002746template<typename Range>
2747void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2748 SourceLocation Loc,
2749 bool IsStringLocation,
2750 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00002751 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002752 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00002753 Loc, IsStringLocation, StringRange, FixIt);
2754}
2755
2756/// \brief If the format string is not within the funcion call, emit a note
2757/// so that the function call and string are in diagnostic messages.
2758///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002759/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00002760/// call and only one diagnostic message will be produced. Otherwise, an
2761/// extra note will be emitted pointing to location of the format string.
2762///
2763/// \param ArgumentExpr the expression that is passed as the format string
2764/// argument in the function call. Used for getting locations when two
2765/// diagnostics are emitted.
2766///
2767/// \param PDiag the callee should already have provided any strings for the
2768/// diagnostic message. This function only adds locations and fixits
2769/// to diagnostics.
2770///
2771/// \param Loc primary location for diagnostic. If two diagnostics are
2772/// required, one will be at Loc and a new SourceLocation will be created for
2773/// the other one.
2774///
2775/// \param IsStringLocation if true, Loc points to the format string should be
2776/// used for the note. Otherwise, Loc points to the argument list and will
2777/// be used with PDiag.
2778///
2779/// \param StringRange some or all of the string to highlight. This is
2780/// templated so it can accept either a CharSourceRange or a SourceRange.
2781///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002782/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002783template<typename Range>
2784void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2785 const Expr *ArgumentExpr,
2786 PartialDiagnostic PDiag,
2787 SourceLocation Loc,
2788 bool IsStringLocation,
2789 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00002790 ArrayRef<FixItHint> FixIt) {
2791 if (InFunctionCall) {
2792 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2793 D << StringRange;
2794 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2795 I != E; ++I) {
2796 D << *I;
2797 }
2798 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002799 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2800 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00002801
2802 const Sema::SemaDiagnosticBuilder &Note =
2803 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2804 diag::note_format_string_defined);
2805
2806 Note << StringRange;
2807 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2808 I != E; ++I) {
2809 Note << *I;
2810 }
Richard Trieu03cf7b72011-10-28 00:41:25 +00002811 }
2812}
2813
Ted Kremenek02087932010-07-16 02:11:22 +00002814//===--- CHECK: Printf format string checking ------------------------------===//
2815
2816namespace {
2817class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002818 bool ObjCContext;
Ted Kremenek02087932010-07-16 02:11:22 +00002819public:
2820 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2821 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002822 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00002823 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002824 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002825 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002826 Sema::VariadicCallType CallType,
2827 llvm::SmallBitVector &CheckedVarArgs)
2828 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2829 numDataArgs, beg, hasVAListArg, Args,
2830 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
2831 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00002832 {}
2833
Craig Toppere14c0f82014-03-12 04:55:44 +00002834
Ted Kremenek02087932010-07-16 02:11:22 +00002835 bool HandleInvalidPrintfConversionSpecifier(
2836 const analyze_printf::PrintfSpecifier &FS,
2837 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002838 unsigned specifierLen) override;
2839
Ted Kremenek02087932010-07-16 02:11:22 +00002840 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2841 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002842 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00002843 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2844 const char *StartSpecifier,
2845 unsigned SpecifierLen,
2846 const Expr *E);
2847
Ted Kremenek02087932010-07-16 02:11:22 +00002848 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2849 const char *startSpecifier, unsigned specifierLen);
2850 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2851 const analyze_printf::OptionalAmount &Amt,
2852 unsigned type,
2853 const char *startSpecifier, unsigned specifierLen);
2854 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2855 const analyze_printf::OptionalFlag &flag,
2856 const char *startSpecifier, unsigned specifierLen);
2857 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2858 const analyze_printf::OptionalFlag &ignoredFlag,
2859 const analyze_printf::OptionalFlag &flag,
2860 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002861 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00002862 const Expr *E);
Richard Smith55ce3522012-06-25 20:30:08 +00002863
Ted Kremenek02087932010-07-16 02:11:22 +00002864};
2865}
2866
2867bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2868 const analyze_printf::PrintfSpecifier &FS,
2869 const char *startSpecifier,
2870 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002871 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00002872 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00002873
Ted Kremenekce815422010-07-19 21:25:57 +00002874 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2875 getLocationOfByte(CS.getStart()),
2876 startSpecifier, specifierLen,
2877 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00002878}
2879
Ted Kremenek02087932010-07-16 02:11:22 +00002880bool CheckPrintfHandler::HandleAmount(
2881 const analyze_format_string::OptionalAmount &Amt,
2882 unsigned k, const char *startSpecifier,
2883 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00002884
2885 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00002886 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00002887 unsigned argIndex = Amt.getArgIndex();
2888 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002889 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2890 << k,
2891 getLocationOfByte(Amt.getStart()),
2892 /*IsStringLocation*/true,
2893 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00002894 // Don't do any more checking. We will just emit
2895 // spurious errors.
2896 return false;
2897 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002898
Ted Kremenek5739de72010-01-29 01:06:55 +00002899 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00002900 // Although not in conformance with C99, we also allow the argument to be
2901 // an 'unsigned int' as that is a reasonably safe case. GCC also
2902 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00002903 CoveredArgs.set(argIndex);
2904 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00002905 if (!Arg)
2906 return false;
2907
Ted Kremenek5739de72010-01-29 01:06:55 +00002908 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002909
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002910 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
2911 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002912
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002913 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002914 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002915 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00002916 << T << Arg->getSourceRange(),
2917 getLocationOfByte(Amt.getStart()),
2918 /*IsStringLocation*/true,
2919 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00002920 // Don't do any more checking. We will just emit
2921 // spurious errors.
2922 return false;
2923 }
2924 }
2925 }
2926 return true;
2927}
Ted Kremenek5739de72010-01-29 01:06:55 +00002928
Tom Careb49ec692010-06-17 19:00:27 +00002929void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00002930 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002931 const analyze_printf::OptionalAmount &Amt,
2932 unsigned type,
2933 const char *startSpecifier,
2934 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002935 const analyze_printf::PrintfConversionSpecifier &CS =
2936 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00002937
Richard Trieu03cf7b72011-10-28 00:41:25 +00002938 FixItHint fixit =
2939 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2940 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2941 Amt.getConstantLength()))
2942 : FixItHint();
2943
2944 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2945 << type << CS.toString(),
2946 getLocationOfByte(Amt.getStart()),
2947 /*IsStringLocation*/true,
2948 getSpecifierRange(startSpecifier, specifierLen),
2949 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00002950}
2951
Ted Kremenek02087932010-07-16 02:11:22 +00002952void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002953 const analyze_printf::OptionalFlag &flag,
2954 const char *startSpecifier,
2955 unsigned specifierLen) {
2956 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002957 const analyze_printf::PrintfConversionSpecifier &CS =
2958 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00002959 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2960 << flag.toString() << CS.toString(),
2961 getLocationOfByte(flag.getPosition()),
2962 /*IsStringLocation*/true,
2963 getSpecifierRange(startSpecifier, specifierLen),
2964 FixItHint::CreateRemoval(
2965 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00002966}
2967
2968void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00002969 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002970 const analyze_printf::OptionalFlag &ignoredFlag,
2971 const analyze_printf::OptionalFlag &flag,
2972 const char *startSpecifier,
2973 unsigned specifierLen) {
2974 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002975 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2976 << ignoredFlag.toString() << flag.toString(),
2977 getLocationOfByte(ignoredFlag.getPosition()),
2978 /*IsStringLocation*/true,
2979 getSpecifierRange(startSpecifier, specifierLen),
2980 FixItHint::CreateRemoval(
2981 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00002982}
2983
Richard Smith55ce3522012-06-25 20:30:08 +00002984// Determines if the specified is a C++ class or struct containing
2985// a member with the specified name and kind (e.g. a CXXMethodDecl named
2986// "c_str()").
2987template<typename MemberKind>
2988static llvm::SmallPtrSet<MemberKind*, 1>
2989CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2990 const RecordType *RT = Ty->getAs<RecordType>();
2991 llvm::SmallPtrSet<MemberKind*, 1> Results;
2992
2993 if (!RT)
2994 return Results;
2995 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00002996 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00002997 return Results;
2998
Alp Tokerb6cc5922014-05-03 03:45:55 +00002999 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00003000 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00003001 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00003002
3003 // We just need to include all members of the right kind turned up by the
3004 // filter, at this point.
3005 if (S.LookupQualifiedName(R, RT->getDecl()))
3006 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3007 NamedDecl *decl = (*I)->getUnderlyingDecl();
3008 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
3009 Results.insert(FK);
3010 }
3011 return Results;
3012}
3013
Richard Smith2868a732014-02-28 01:36:39 +00003014/// Check if we could call '.c_str()' on an object.
3015///
3016/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
3017/// allow the call, or if it would be ambiguous).
3018bool Sema::hasCStrMethod(const Expr *E) {
3019 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3020 MethodSet Results =
3021 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
3022 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3023 MI != ME; ++MI)
3024 if ((*MI)->getMinRequiredArguments() == 0)
3025 return true;
3026 return false;
3027}
3028
Richard Smith55ce3522012-06-25 20:30:08 +00003029// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003030// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00003031// Returns true when a c_str() conversion method is found.
3032bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00003033 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00003034 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3035
3036 MethodSet Results =
3037 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
3038
3039 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3040 MI != ME; ++MI) {
3041 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00003042 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00003043 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00003044 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00003045 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00003046 S.Diag(E->getLocStart(), diag::note_printf_c_str)
3047 << "c_str()"
3048 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
3049 return true;
3050 }
3051 }
3052
3053 return false;
3054}
3055
Ted Kremenekab278de2010-01-28 23:39:18 +00003056bool
Ted Kremenek02087932010-07-16 02:11:22 +00003057CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00003058 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00003059 const char *startSpecifier,
3060 unsigned specifierLen) {
3061
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003062 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00003063 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003064 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00003065
Ted Kremenek6cd69422010-07-19 22:01:06 +00003066 if (FS.consumesDataArgument()) {
3067 if (atFirstArg) {
3068 atFirstArg = false;
3069 usesPositionalArgs = FS.usesPositionalArg();
3070 }
3071 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003072 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3073 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003074 return false;
3075 }
Ted Kremenek5739de72010-01-29 01:06:55 +00003076 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003077
Ted Kremenekd1668192010-02-27 01:41:03 +00003078 // First check if the field width, precision, and conversion specifier
3079 // have matching data arguments.
3080 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
3081 startSpecifier, specifierLen)) {
3082 return false;
3083 }
3084
3085 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
3086 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003087 return false;
3088 }
3089
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003090 if (!CS.consumesDataArgument()) {
3091 // FIXME: Technically specifying a precision or field width here
3092 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00003093 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003094 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003095
Ted Kremenek4a49d982010-02-26 19:18:41 +00003096 // Consume the argument.
3097 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00003098 if (argIndex < NumDataArgs) {
3099 // The check to see if the argIndex is valid will come later.
3100 // We set the bit here because we may exit early from this
3101 // function if we encounter some other error.
3102 CoveredArgs.set(argIndex);
3103 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00003104
3105 // Check for using an Objective-C specific conversion specifier
3106 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003107 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00003108 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
3109 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00003110 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003111
Tom Careb49ec692010-06-17 19:00:27 +00003112 // Check for invalid use of field width
3113 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00003114 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00003115 startSpecifier, specifierLen);
3116 }
3117
3118 // Check for invalid use of precision
3119 if (!FS.hasValidPrecision()) {
3120 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
3121 startSpecifier, specifierLen);
3122 }
3123
3124 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00003125 if (!FS.hasValidThousandsGroupingPrefix())
3126 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003127 if (!FS.hasValidLeadingZeros())
3128 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
3129 if (!FS.hasValidPlusPrefix())
3130 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00003131 if (!FS.hasValidSpacePrefix())
3132 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003133 if (!FS.hasValidAlternativeForm())
3134 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3135 if (!FS.hasValidLeftJustified())
3136 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3137
3138 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00003139 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3140 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3141 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003142 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3143 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3144 startSpecifier, specifierLen);
3145
3146 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003147 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003148 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3149 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003150 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003151 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003152 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003153 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3154 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00003155
Jordan Rose92303592012-09-08 04:00:03 +00003156 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3157 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3158
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003159 // The remaining checks depend on the data arguments.
3160 if (HasVAListArg)
3161 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003162
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003163 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003164 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003165
Jordan Rose58bbe422012-07-19 18:10:08 +00003166 const Expr *Arg = getDataArg(argIndex);
3167 if (!Arg)
3168 return true;
3169
3170 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00003171}
3172
Jordan Roseaee34382012-09-05 22:56:26 +00003173static bool requiresParensToAddCast(const Expr *E) {
3174 // FIXME: We should have a general way to reason about operator
3175 // precedence and whether parens are actually needed here.
3176 // Take care of a few common cases where they aren't.
3177 const Expr *Inside = E->IgnoreImpCasts();
3178 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3179 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3180
3181 switch (Inside->getStmtClass()) {
3182 case Stmt::ArraySubscriptExprClass:
3183 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003184 case Stmt::CharacterLiteralClass:
3185 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003186 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003187 case Stmt::FloatingLiteralClass:
3188 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003189 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003190 case Stmt::ObjCArrayLiteralClass:
3191 case Stmt::ObjCBoolLiteralExprClass:
3192 case Stmt::ObjCBoxedExprClass:
3193 case Stmt::ObjCDictionaryLiteralClass:
3194 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003195 case Stmt::ObjCIvarRefExprClass:
3196 case Stmt::ObjCMessageExprClass:
3197 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003198 case Stmt::ObjCStringLiteralClass:
3199 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003200 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003201 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003202 case Stmt::UnaryOperatorClass:
3203 return false;
3204 default:
3205 return true;
3206 }
3207}
3208
Richard Smith55ce3522012-06-25 20:30:08 +00003209bool
3210CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3211 const char *StartSpecifier,
3212 unsigned SpecifierLen,
3213 const Expr *E) {
3214 using namespace analyze_format_string;
3215 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003216 // Now type check the data expression that matches the
3217 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003218 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3219 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00003220 if (!AT.isValid())
3221 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00003222
Jordan Rose598ec092012-12-05 18:44:40 +00003223 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00003224 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3225 ExprTy = TET->getUnderlyingExpr()->getType();
3226 }
3227
Jordan Rose598ec092012-12-05 18:44:40 +00003228 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003229 return true;
Jordan Rose98709982012-06-04 22:48:57 +00003230
Jordan Rose22b74712012-09-05 22:56:19 +00003231 // Look through argument promotions for our error message's reported type.
3232 // This includes the integral and floating promotions, but excludes array
3233 // and function pointer decay; seeing that an argument intended to be a
3234 // string has type 'char [6]' is probably more confusing than 'char *'.
3235 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3236 if (ICE->getCastKind() == CK_IntegralCast ||
3237 ICE->getCastKind() == CK_FloatingCast) {
3238 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00003239 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00003240
3241 // Check if we didn't match because of an implicit cast from a 'char'
3242 // or 'short' to an 'int'. This is done because printf is a varargs
3243 // function.
3244 if (ICE->getType() == S.Context.IntTy ||
3245 ICE->getType() == S.Context.UnsignedIntTy) {
3246 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00003247 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003248 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00003249 }
Jordan Rose98709982012-06-04 22:48:57 +00003250 }
Jordan Rose598ec092012-12-05 18:44:40 +00003251 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3252 // Special case for 'a', which has type 'int' in C.
3253 // Note, however, that we do /not/ want to treat multibyte constants like
3254 // 'MooV' as characters! This form is deprecated but still exists.
3255 if (ExprTy == S.Context.IntTy)
3256 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3257 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00003258 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003259
Jordan Rosebc53ed12014-05-31 04:12:14 +00003260 // Look through enums to their underlying type.
3261 bool IsEnum = false;
3262 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
3263 ExprTy = EnumTy->getDecl()->getIntegerType();
3264 IsEnum = true;
3265 }
3266
Jordan Rose0e5badd2012-12-05 18:44:49 +00003267 // %C in an Objective-C context prints a unichar, not a wchar_t.
3268 // If the argument is an integer of some kind, believe the %C and suggest
3269 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00003270 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003271 if (ObjCContext &&
3272 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3273 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3274 !ExprTy->isCharType()) {
3275 // 'unichar' is defined as a typedef of unsigned short, but we should
3276 // prefer using the typedef if it is visible.
3277 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00003278
3279 // While we are here, check if the value is an IntegerLiteral that happens
3280 // to be within the valid range.
3281 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3282 const llvm::APInt &V = IL->getValue();
3283 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3284 return true;
3285 }
3286
Jordan Rose0e5badd2012-12-05 18:44:49 +00003287 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3288 Sema::LookupOrdinaryName);
3289 if (S.LookupName(Result, S.getCurScope())) {
3290 NamedDecl *ND = Result.getFoundDecl();
3291 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3292 if (TD->getUnderlyingType() == IntendedTy)
3293 IntendedTy = S.Context.getTypedefType(TD);
3294 }
3295 }
3296 }
3297
3298 // Special-case some of Darwin's platform-independence types by suggesting
3299 // casts to primitive types that are known to be large enough.
3300 bool ShouldNotPrintDirectly = false;
Jordan Roseaee34382012-09-05 22:56:26 +00003301 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003302 // Use a 'while' to peel off layers of typedefs.
3303 QualType TyTy = IntendedTy;
3304 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
Jordan Roseaee34382012-09-05 22:56:26 +00003305 StringRef Name = UserTy->getDecl()->getName();
Jordan Rose0e5badd2012-12-05 18:44:49 +00003306 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Jordan Roseaee34382012-09-05 22:56:26 +00003307 .Case("NSInteger", S.Context.LongTy)
3308 .Case("NSUInteger", S.Context.UnsignedLongTy)
3309 .Case("SInt32", S.Context.IntTy)
3310 .Case("UInt32", S.Context.UnsignedIntTy)
Jordan Rose0e5badd2012-12-05 18:44:49 +00003311 .Default(QualType());
3312
3313 if (!CastTy.isNull()) {
3314 ShouldNotPrintDirectly = true;
3315 IntendedTy = CastTy;
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003316 break;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003317 }
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003318 TyTy = UserTy->desugar();
Jordan Roseaee34382012-09-05 22:56:26 +00003319 }
3320 }
3321
Jordan Rose22b74712012-09-05 22:56:19 +00003322 // We may be able to offer a FixItHint if it is a supported type.
3323 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00003324 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00003325 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003326
Jordan Rose22b74712012-09-05 22:56:19 +00003327 if (success) {
3328 // Get the fix string from the fixed format specifier
3329 SmallString<16> buf;
3330 llvm::raw_svector_ostream os(buf);
3331 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003332
Jordan Roseaee34382012-09-05 22:56:26 +00003333 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3334
Jordan Rose0e5badd2012-12-05 18:44:49 +00003335 if (IntendedTy == ExprTy) {
3336 // In this case, the specifier is wrong and should be changed to match
3337 // the argument.
3338 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003339 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3340 << AT.getRepresentativeTypeName(S.Context) << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003341 << E->getSourceRange(),
3342 E->getLocStart(),
3343 /*IsStringLocation*/false,
3344 SpecRange,
3345 FixItHint::CreateReplacement(SpecRange, os.str()));
3346
3347 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00003348 // The canonical type for formatting this value is different from the
3349 // actual type of the expression. (This occurs, for example, with Darwin's
3350 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3351 // should be printed as 'long' for 64-bit compatibility.)
3352 // Rather than emitting a normal format/argument mismatch, we want to
3353 // add a cast to the recommended type (and correct the format string
3354 // if necessary).
3355 SmallString<16> CastBuf;
3356 llvm::raw_svector_ostream CastFix(CastBuf);
3357 CastFix << "(";
3358 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3359 CastFix << ")";
3360
3361 SmallVector<FixItHint,4> Hints;
3362 if (!AT.matchesType(S.Context, IntendedTy))
3363 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3364
3365 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3366 // If there's already a cast present, just replace it.
3367 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3368 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3369
3370 } else if (!requiresParensToAddCast(E)) {
3371 // If the expression has high enough precedence,
3372 // just write the C-style cast.
3373 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3374 CastFix.str()));
3375 } else {
3376 // Otherwise, add parens around the expression as well as the cast.
3377 CastFix << "(";
3378 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3379 CastFix.str()));
3380
Alp Tokerb6cc5922014-05-03 03:45:55 +00003381 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00003382 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3383 }
3384
Jordan Rose0e5badd2012-12-05 18:44:49 +00003385 if (ShouldNotPrintDirectly) {
3386 // The expression has a type that should not be printed directly.
3387 // We extract the name from the typedef because we don't want to show
3388 // the underlying type in the diagnostic.
3389 StringRef Name = cast<TypedefType>(ExprTy)->getDecl()->getName();
Jordan Roseaee34382012-09-05 22:56:26 +00003390
Jordan Rose0e5badd2012-12-05 18:44:49 +00003391 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00003392 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003393 << E->getSourceRange(),
3394 E->getLocStart(), /*IsStringLocation=*/false,
3395 SpecRange, Hints);
3396 } else {
3397 // In this case, the expression could be printed using a different
3398 // specifier, but we've decided that the specifier is probably correct
3399 // and we should cast instead. Just use the normal warning message.
3400 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003401 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3402 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003403 << E->getSourceRange(),
3404 E->getLocStart(), /*IsStringLocation*/false,
3405 SpecRange, Hints);
3406 }
Jordan Roseaee34382012-09-05 22:56:26 +00003407 }
Jordan Rose22b74712012-09-05 22:56:19 +00003408 } else {
3409 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3410 SpecifierLen);
3411 // Since the warning for passing non-POD types to variadic functions
3412 // was deferred until now, we emit a warning for non-POD
3413 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00003414 switch (S.isValidVarArgType(ExprTy)) {
3415 case Sema::VAK_Valid:
3416 case Sema::VAK_ValidInCXX11:
Jordan Rose22b74712012-09-05 22:56:19 +00003417 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003418 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3419 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Richard Smithd7293d72013-08-05 18:49:43 +00003420 << CSR
3421 << E->getSourceRange(),
3422 E->getLocStart(), /*IsStringLocation*/false, CSR);
3423 break;
3424
3425 case Sema::VAK_Undefined:
3426 EmitFormatDiagnostic(
3427 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003428 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00003429 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00003430 << CallType
3431 << AT.getRepresentativeTypeName(S.Context)
3432 << CSR
3433 << E->getSourceRange(),
3434 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00003435 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00003436 break;
3437
3438 case Sema::VAK_Invalid:
3439 if (ExprTy->isObjCObjectType())
3440 EmitFormatDiagnostic(
3441 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3442 << S.getLangOpts().CPlusPlus11
3443 << ExprTy
3444 << CallType
3445 << AT.getRepresentativeTypeName(S.Context)
3446 << CSR
3447 << E->getSourceRange(),
3448 E->getLocStart(), /*IsStringLocation*/false, CSR);
3449 else
3450 // FIXME: If this is an initializer list, suggest removing the braces
3451 // or inserting a cast to the target type.
3452 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3453 << isa<InitListExpr>(E) << ExprTy << CallType
3454 << AT.getRepresentativeTypeName(S.Context)
3455 << E->getSourceRange();
3456 break;
3457 }
3458
3459 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3460 "format string specifier index out of range");
3461 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003462 }
3463
Ted Kremenekab278de2010-01-28 23:39:18 +00003464 return true;
3465}
3466
Ted Kremenek02087932010-07-16 02:11:22 +00003467//===--- CHECK: Scanf format string checking ------------------------------===//
3468
3469namespace {
3470class CheckScanfHandler : public CheckFormatHandler {
3471public:
3472 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3473 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003474 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003475 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003476 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003477 Sema::VariadicCallType CallType,
3478 llvm::SmallBitVector &CheckedVarArgs)
3479 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3480 numDataArgs, beg, hasVAListArg,
3481 Args, formatIdx, inFunctionCall, CallType,
3482 CheckedVarArgs)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003483 {}
Ted Kremenek02087932010-07-16 02:11:22 +00003484
3485 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3486 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003487 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00003488
3489 bool HandleInvalidScanfConversionSpecifier(
3490 const analyze_scanf::ScanfSpecifier &FS,
3491 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003492 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003493
Craig Toppere14c0f82014-03-12 04:55:44 +00003494 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00003495};
Ted Kremenek019d2242010-01-29 01:50:07 +00003496}
Ted Kremenekab278de2010-01-28 23:39:18 +00003497
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003498void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3499 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003500 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3501 getLocationOfByte(end), /*IsStringLocation*/true,
3502 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003503}
3504
Ted Kremenekce815422010-07-19 21:25:57 +00003505bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3506 const analyze_scanf::ScanfSpecifier &FS,
3507 const char *startSpecifier,
3508 unsigned specifierLen) {
3509
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003510 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003511 FS.getConversionSpecifier();
3512
3513 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3514 getLocationOfByte(CS.getStart()),
3515 startSpecifier, specifierLen,
3516 CS.getStart(), CS.getLength());
3517}
3518
Ted Kremenek02087932010-07-16 02:11:22 +00003519bool CheckScanfHandler::HandleScanfSpecifier(
3520 const analyze_scanf::ScanfSpecifier &FS,
3521 const char *startSpecifier,
3522 unsigned specifierLen) {
3523
3524 using namespace analyze_scanf;
3525 using namespace analyze_format_string;
3526
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003527 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003528
Ted Kremenek6cd69422010-07-19 22:01:06 +00003529 // Handle case where '%' and '*' don't consume an argument. These shouldn't
3530 // be used to decide if we are using positional arguments consistently.
3531 if (FS.consumesDataArgument()) {
3532 if (atFirstArg) {
3533 atFirstArg = false;
3534 usesPositionalArgs = FS.usesPositionalArg();
3535 }
3536 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003537 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3538 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003539 return false;
3540 }
Ted Kremenek02087932010-07-16 02:11:22 +00003541 }
3542
3543 // Check if the field with is non-zero.
3544 const OptionalAmount &Amt = FS.getFieldWidth();
3545 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3546 if (Amt.getConstantAmount() == 0) {
3547 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3548 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00003549 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3550 getLocationOfByte(Amt.getStart()),
3551 /*IsStringLocation*/true, R,
3552 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00003553 }
3554 }
3555
3556 if (!FS.consumesDataArgument()) {
3557 // FIXME: Technically specifying a precision or field width here
3558 // makes no sense. Worth issuing a warning at some point.
3559 return true;
3560 }
3561
3562 // Consume the argument.
3563 unsigned argIndex = FS.getArgIndex();
3564 if (argIndex < NumDataArgs) {
3565 // The check to see if the argIndex is valid will come later.
3566 // We set the bit here because we may exit early from this
3567 // function if we encounter some other error.
3568 CoveredArgs.set(argIndex);
3569 }
3570
Ted Kremenek4407ea42010-07-20 20:04:47 +00003571 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003572 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003573 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3574 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003575 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003576 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003577 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003578 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3579 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003580
Jordan Rose92303592012-09-08 04:00:03 +00003581 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3582 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3583
Ted Kremenek02087932010-07-16 02:11:22 +00003584 // The remaining checks depend on the data arguments.
3585 if (HasVAListArg)
3586 return true;
3587
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003588 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00003589 return false;
Ted Kremenek02087932010-07-16 02:11:22 +00003590
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003591 // Check that the argument type matches the format specifier.
3592 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00003593 if (!Ex)
3594 return true;
3595
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00003596 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3597 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003598 ScanfSpecifier fixedFS = FS;
Jordan Rose177b0a32014-03-20 03:32:39 +00003599 bool success = fixedFS.fixType(Ex->getType(),
3600 Ex->IgnoreImpCasts()->getType(),
3601 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003602
3603 if (success) {
3604 // Get the fix string from the fixed format specifier.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003605 SmallString<128> buf;
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003606 llvm::raw_svector_ostream os(buf);
3607 fixedFS.toString(os);
3608
3609 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003610 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3611 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() << false
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003612 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00003613 Ex->getLocStart(),
3614 /*IsStringLocation*/false,
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003615 getSpecifierRange(startSpecifier, specifierLen),
3616 FixItHint::CreateReplacement(
3617 getSpecifierRange(startSpecifier, specifierLen),
3618 os.str()));
3619 } else {
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003620 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003621 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3622 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() << false
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003623 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00003624 Ex->getLocStart(),
3625 /*IsStringLocation*/false,
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003626 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003627 }
3628 }
3629
Ted Kremenek02087932010-07-16 02:11:22 +00003630 return true;
3631}
3632
3633void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00003634 const Expr *OrigFormatExpr,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003635 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003636 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003637 unsigned firstDataArg, FormatStringType Type,
Richard Smithd7293d72013-08-05 18:49:43 +00003638 bool inFunctionCall, VariadicCallType CallType,
3639 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00003640
Ted Kremenekab278de2010-01-28 23:39:18 +00003641 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00003642 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003643 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003644 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00003645 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3646 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00003647 return;
3648 }
Ted Kremenek02087932010-07-16 02:11:22 +00003649
Ted Kremenekab278de2010-01-28 23:39:18 +00003650 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003651 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00003652 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00003653 // Account for cases where the string literal is truncated in a declaration.
3654 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
3655 assert(T && "String literal not of constant array type!");
3656 size_t TypeSize = T->getSize().getZExtValue();
3657 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003658 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00003659
3660 // Emit a warning if the string literal is truncated and does not contain an
3661 // embedded null character.
3662 if (TypeSize <= StrRef.size() &&
3663 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
3664 CheckFormatHandler::EmitFormatDiagnostic(
3665 *this, inFunctionCall, Args[format_idx],
3666 PDiag(diag::warn_printf_format_string_not_null_terminated),
3667 FExpr->getLocStart(),
3668 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
3669 return;
3670 }
3671
Ted Kremenekab278de2010-01-28 23:39:18 +00003672 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00003673 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003674 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003675 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00003676 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3677 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00003678 return;
3679 }
Ted Kremenek02087932010-07-16 02:11:22 +00003680
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003681 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek02087932010-07-16 02:11:22 +00003682 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003683 numDataArgs, (Type == FST_NSString),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003684 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00003685 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00003686
Hans Wennborg23926bd2011-12-15 10:25:47 +00003687 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00003688 getLangOpts(),
3689 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00003690 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003691 } else if (Type == FST_Scanf) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003692 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003693 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00003694 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00003695
Hans Wennborg23926bd2011-12-15 10:25:47 +00003696 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00003697 getLangOpts(),
3698 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00003699 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003700 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00003701}
3702
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003703//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
3704
3705// Returns the related absolute value function that is larger, of 0 if one
3706// does not exist.
3707static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
3708 switch (AbsFunction) {
3709 default:
3710 return 0;
3711
3712 case Builtin::BI__builtin_abs:
3713 return Builtin::BI__builtin_labs;
3714 case Builtin::BI__builtin_labs:
3715 return Builtin::BI__builtin_llabs;
3716 case Builtin::BI__builtin_llabs:
3717 return 0;
3718
3719 case Builtin::BI__builtin_fabsf:
3720 return Builtin::BI__builtin_fabs;
3721 case Builtin::BI__builtin_fabs:
3722 return Builtin::BI__builtin_fabsl;
3723 case Builtin::BI__builtin_fabsl:
3724 return 0;
3725
3726 case Builtin::BI__builtin_cabsf:
3727 return Builtin::BI__builtin_cabs;
3728 case Builtin::BI__builtin_cabs:
3729 return Builtin::BI__builtin_cabsl;
3730 case Builtin::BI__builtin_cabsl:
3731 return 0;
3732
3733 case Builtin::BIabs:
3734 return Builtin::BIlabs;
3735 case Builtin::BIlabs:
3736 return Builtin::BIllabs;
3737 case Builtin::BIllabs:
3738 return 0;
3739
3740 case Builtin::BIfabsf:
3741 return Builtin::BIfabs;
3742 case Builtin::BIfabs:
3743 return Builtin::BIfabsl;
3744 case Builtin::BIfabsl:
3745 return 0;
3746
3747 case Builtin::BIcabsf:
3748 return Builtin::BIcabs;
3749 case Builtin::BIcabs:
3750 return Builtin::BIcabsl;
3751 case Builtin::BIcabsl:
3752 return 0;
3753 }
3754}
3755
3756// Returns the argument type of the absolute value function.
3757static QualType getAbsoluteValueArgumentType(ASTContext &Context,
3758 unsigned AbsType) {
3759 if (AbsType == 0)
3760 return QualType();
3761
3762 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3763 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
3764 if (Error != ASTContext::GE_None)
3765 return QualType();
3766
3767 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
3768 if (!FT)
3769 return QualType();
3770
3771 if (FT->getNumParams() != 1)
3772 return QualType();
3773
3774 return FT->getParamType(0);
3775}
3776
3777// Returns the best absolute value function, or zero, based on type and
3778// current absolute value function.
3779static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
3780 unsigned AbsFunctionKind) {
3781 unsigned BestKind = 0;
3782 uint64_t ArgSize = Context.getTypeSize(ArgType);
3783 for (unsigned Kind = AbsFunctionKind; Kind != 0;
3784 Kind = getLargerAbsoluteValueFunction(Kind)) {
3785 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
3786 if (Context.getTypeSize(ParamType) >= ArgSize) {
3787 if (BestKind == 0)
3788 BestKind = Kind;
3789 else if (Context.hasSameType(ParamType, ArgType)) {
3790 BestKind = Kind;
3791 break;
3792 }
3793 }
3794 }
3795 return BestKind;
3796}
3797
3798enum AbsoluteValueKind {
3799 AVK_Integer,
3800 AVK_Floating,
3801 AVK_Complex
3802};
3803
3804static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
3805 if (T->isIntegralOrEnumerationType())
3806 return AVK_Integer;
3807 if (T->isRealFloatingType())
3808 return AVK_Floating;
3809 if (T->isAnyComplexType())
3810 return AVK_Complex;
3811
3812 llvm_unreachable("Type not integer, floating, or complex");
3813}
3814
3815// Changes the absolute value function to a different type. Preserves whether
3816// the function is a builtin.
3817static unsigned changeAbsFunction(unsigned AbsKind,
3818 AbsoluteValueKind ValueKind) {
3819 switch (ValueKind) {
3820 case AVK_Integer:
3821 switch (AbsKind) {
3822 default:
3823 return 0;
3824 case Builtin::BI__builtin_fabsf:
3825 case Builtin::BI__builtin_fabs:
3826 case Builtin::BI__builtin_fabsl:
3827 case Builtin::BI__builtin_cabsf:
3828 case Builtin::BI__builtin_cabs:
3829 case Builtin::BI__builtin_cabsl:
3830 return Builtin::BI__builtin_abs;
3831 case Builtin::BIfabsf:
3832 case Builtin::BIfabs:
3833 case Builtin::BIfabsl:
3834 case Builtin::BIcabsf:
3835 case Builtin::BIcabs:
3836 case Builtin::BIcabsl:
3837 return Builtin::BIabs;
3838 }
3839 case AVK_Floating:
3840 switch (AbsKind) {
3841 default:
3842 return 0;
3843 case Builtin::BI__builtin_abs:
3844 case Builtin::BI__builtin_labs:
3845 case Builtin::BI__builtin_llabs:
3846 case Builtin::BI__builtin_cabsf:
3847 case Builtin::BI__builtin_cabs:
3848 case Builtin::BI__builtin_cabsl:
3849 return Builtin::BI__builtin_fabsf;
3850 case Builtin::BIabs:
3851 case Builtin::BIlabs:
3852 case Builtin::BIllabs:
3853 case Builtin::BIcabsf:
3854 case Builtin::BIcabs:
3855 case Builtin::BIcabsl:
3856 return Builtin::BIfabsf;
3857 }
3858 case AVK_Complex:
3859 switch (AbsKind) {
3860 default:
3861 return 0;
3862 case Builtin::BI__builtin_abs:
3863 case Builtin::BI__builtin_labs:
3864 case Builtin::BI__builtin_llabs:
3865 case Builtin::BI__builtin_fabsf:
3866 case Builtin::BI__builtin_fabs:
3867 case Builtin::BI__builtin_fabsl:
3868 return Builtin::BI__builtin_cabsf;
3869 case Builtin::BIabs:
3870 case Builtin::BIlabs:
3871 case Builtin::BIllabs:
3872 case Builtin::BIfabsf:
3873 case Builtin::BIfabs:
3874 case Builtin::BIfabsl:
3875 return Builtin::BIcabsf;
3876 }
3877 }
3878 llvm_unreachable("Unable to convert function");
3879}
3880
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00003881static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003882 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
3883 if (!FnInfo)
3884 return 0;
3885
3886 switch (FDecl->getBuiltinID()) {
3887 default:
3888 return 0;
3889 case Builtin::BI__builtin_abs:
3890 case Builtin::BI__builtin_fabs:
3891 case Builtin::BI__builtin_fabsf:
3892 case Builtin::BI__builtin_fabsl:
3893 case Builtin::BI__builtin_labs:
3894 case Builtin::BI__builtin_llabs:
3895 case Builtin::BI__builtin_cabs:
3896 case Builtin::BI__builtin_cabsf:
3897 case Builtin::BI__builtin_cabsl:
3898 case Builtin::BIabs:
3899 case Builtin::BIlabs:
3900 case Builtin::BIllabs:
3901 case Builtin::BIfabs:
3902 case Builtin::BIfabsf:
3903 case Builtin::BIfabsl:
3904 case Builtin::BIcabs:
3905 case Builtin::BIcabsf:
3906 case Builtin::BIcabsl:
3907 return FDecl->getBuiltinID();
3908 }
3909 llvm_unreachable("Unknown Builtin type");
3910}
3911
3912// If the replacement is valid, emit a note with replacement function.
3913// Additionally, suggest including the proper header if not already included.
3914static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00003915 unsigned AbsKind, QualType ArgType) {
3916 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00003917 const char *HeaderName = nullptr;
3918 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00003919 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
3920 FunctionName = "std::abs";
3921 if (ArgType->isIntegralOrEnumerationType()) {
3922 HeaderName = "cstdlib";
3923 } else if (ArgType->isRealFloatingType()) {
3924 HeaderName = "cmath";
3925 } else {
3926 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003927 }
Richard Trieubeffb832014-04-15 23:47:53 +00003928
3929 // Lookup all std::abs
3930 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00003931 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00003932 R.suppressDiagnostics();
3933 S.LookupQualifiedName(R, Std);
3934
3935 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003936 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00003937 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
3938 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
3939 } else {
3940 FDecl = dyn_cast<FunctionDecl>(I);
3941 }
3942 if (!FDecl)
3943 continue;
3944
3945 // Found std::abs(), check that they are the right ones.
3946 if (FDecl->getNumParams() != 1)
3947 continue;
3948
3949 // Check that the parameter type can handle the argument.
3950 QualType ParamType = FDecl->getParamDecl(0)->getType();
3951 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
3952 S.Context.getTypeSize(ArgType) <=
3953 S.Context.getTypeSize(ParamType)) {
3954 // Found a function, don't need the header hint.
3955 EmitHeaderHint = false;
3956 break;
3957 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003958 }
Richard Trieubeffb832014-04-15 23:47:53 +00003959 }
3960 } else {
3961 FunctionName = S.Context.BuiltinInfo.GetName(AbsKind);
3962 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
3963
3964 if (HeaderName) {
3965 DeclarationName DN(&S.Context.Idents.get(FunctionName));
3966 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
3967 R.suppressDiagnostics();
3968 S.LookupName(R, S.getCurScope());
3969
3970 if (R.isSingleResult()) {
3971 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3972 if (FD && FD->getBuiltinID() == AbsKind) {
3973 EmitHeaderHint = false;
3974 } else {
3975 return;
3976 }
3977 } else if (!R.empty()) {
3978 return;
3979 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003980 }
3981 }
3982
3983 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00003984 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003985
Richard Trieubeffb832014-04-15 23:47:53 +00003986 if (!HeaderName)
3987 return;
3988
3989 if (!EmitHeaderHint)
3990 return;
3991
Alp Toker5d96e0a2014-07-11 20:53:51 +00003992 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
3993 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00003994}
3995
3996static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
3997 if (!FDecl)
3998 return false;
3999
4000 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
4001 return false;
4002
4003 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
4004
4005 while (ND && ND->isInlineNamespace()) {
4006 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004007 }
Richard Trieubeffb832014-04-15 23:47:53 +00004008
4009 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
4010 return false;
4011
4012 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
4013 return false;
4014
4015 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004016}
4017
4018// Warn when using the wrong abs() function.
4019void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
4020 const FunctionDecl *FDecl,
4021 IdentifierInfo *FnInfo) {
4022 if (Call->getNumArgs() != 1)
4023 return;
4024
4025 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00004026 bool IsStdAbs = IsFunctionStdAbs(FDecl);
4027 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004028 return;
4029
4030 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
4031 QualType ParamType = Call->getArg(0)->getType();
4032
Alp Toker5d96e0a2014-07-11 20:53:51 +00004033 // Unsigned types cannot be negative. Suggest removing the absolute value
4034 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004035 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00004036 const char *FunctionName =
4037 IsStdAbs ? "std::abs" : Context.BuiltinInfo.GetName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004038 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
4039 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00004040 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004041 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
4042 return;
4043 }
4044
Richard Trieubeffb832014-04-15 23:47:53 +00004045 // std::abs has overloads which prevent most of the absolute value problems
4046 // from occurring.
4047 if (IsStdAbs)
4048 return;
4049
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004050 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
4051 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
4052
4053 // The argument and parameter are the same kind. Check if they are the right
4054 // size.
4055 if (ArgValueKind == ParamValueKind) {
4056 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
4057 return;
4058
4059 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
4060 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
4061 << FDecl << ArgType << ParamType;
4062
4063 if (NewAbsKind == 0)
4064 return;
4065
4066 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00004067 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004068 return;
4069 }
4070
4071 // ArgValueKind != ParamValueKind
4072 // The wrong type of absolute value function was used. Attempt to find the
4073 // proper one.
4074 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
4075 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
4076 if (NewAbsKind == 0)
4077 return;
4078
4079 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
4080 << FDecl << ParamValueKind << ArgValueKind;
4081
4082 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00004083 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004084 return;
4085}
4086
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004087//===--- CHECK: Standard memory functions ---------------------------------===//
4088
Nico Weber0e6daef2013-12-26 23:38:39 +00004089/// \brief Takes the expression passed to the size_t parameter of functions
4090/// such as memcmp, strncat, etc and warns if it's a comparison.
4091///
4092/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
4093static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
4094 IdentifierInfo *FnName,
4095 SourceLocation FnLoc,
4096 SourceLocation RParenLoc) {
4097 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
4098 if (!Size)
4099 return false;
4100
4101 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
4102 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
4103 return false;
4104
Nico Weber0e6daef2013-12-26 23:38:39 +00004105 SourceRange SizeRange = Size->getSourceRange();
4106 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
4107 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00004108 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00004109 << FnName << FixItHint::CreateInsertion(
4110 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00004111 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00004112 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00004113 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00004114 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
4115 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00004116
4117 return true;
4118}
4119
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004120/// \brief Determine whether the given type is or contains a dynamic class type
4121/// (e.g., whether it has a vtable).
4122static const CXXRecordDecl *getContainedDynamicClass(QualType T,
4123 bool &IsContained) {
4124 // Look through array types while ignoring qualifiers.
4125 const Type *Ty = T->getBaseElementTypeUnsafe();
4126 IsContained = false;
4127
4128 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
4129 RD = RD ? RD->getDefinition() : nullptr;
4130 if (!RD)
4131 return nullptr;
4132
4133 if (RD->isDynamicClass())
4134 return RD;
4135
4136 // Check all the fields. If any bases were dynamic, the class is dynamic.
4137 // It's impossible for a class to transitively contain itself by value, so
4138 // infinite recursion is impossible.
4139 for (auto *FD : RD->fields()) {
4140 bool SubContained;
4141 if (const CXXRecordDecl *ContainedRD =
4142 getContainedDynamicClass(FD->getType(), SubContained)) {
4143 IsContained = true;
4144 return ContainedRD;
4145 }
4146 }
4147
4148 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00004149}
4150
Chandler Carruth889ed862011-06-21 23:04:20 +00004151/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004152/// otherwise returns NULL.
4153static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Weberc5e73862011-06-14 16:14:58 +00004154 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004155 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4156 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
4157 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004158
Craig Topperc3ec1492014-05-26 06:22:03 +00004159 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004160}
4161
Chandler Carruth889ed862011-06-21 23:04:20 +00004162/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004163static QualType getSizeOfArgType(const Expr* E) {
4164 if (const UnaryExprOrTypeTraitExpr *SizeOf =
4165 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4166 if (SizeOf->getKind() == clang::UETT_SizeOf)
4167 return SizeOf->getTypeOfArgument();
4168
4169 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00004170}
4171
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004172/// \brief Check for dangerous or invalid arguments to memset().
4173///
Chandler Carruthac687262011-06-03 06:23:57 +00004174/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004175/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
4176/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004177///
4178/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004179void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00004180 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004181 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00004182 assert(BId != 0);
4183
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004184 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00004185 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00004186 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00004187 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004188 return;
4189
Anna Zaks22122702012-01-17 00:37:07 +00004190 unsigned LastArg = (BId == Builtin::BImemset ||
4191 BId == Builtin::BIstrndup ? 1 : 2);
4192 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00004193 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004194
Nico Weber0e6daef2013-12-26 23:38:39 +00004195 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
4196 Call->getLocStart(), Call->getRParenLoc()))
4197 return;
4198
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004199 // We have special checking when the length is a sizeof expression.
4200 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
4201 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
4202 llvm::FoldingSetNodeID SizeOfArgID;
4203
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004204 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
4205 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004206 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004207
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004208 QualType DestTy = Dest->getType();
4209 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
4210 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00004211
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004212 // Never warn about void type pointers. This can be used to suppress
4213 // false positives.
4214 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004215 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004216
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004217 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
4218 // actually comparing the expressions for equality. Because computing the
4219 // expression IDs can be expensive, we only do this if the diagnostic is
4220 // enabled.
4221 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004222 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
4223 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004224 // We only compute IDs for expressions if the warning is enabled, and
4225 // cache the sizeof arg's ID.
4226 if (SizeOfArgID == llvm::FoldingSetNodeID())
4227 SizeOfArg->Profile(SizeOfArgID, Context, true);
4228 llvm::FoldingSetNodeID DestID;
4229 Dest->Profile(DestID, Context, true);
4230 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00004231 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
4232 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004233 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00004234 StringRef ReadableName = FnName->getName();
4235
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004236 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00004237 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004238 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00004239 if (!PointeeTy->isIncompleteType() &&
4240 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004241 ActionIdx = 2; // If the pointee's size is sizeof(char),
4242 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00004243
4244 // If the function is defined as a builtin macro, do not show macro
4245 // expansion.
4246 SourceLocation SL = SizeOfArg->getExprLoc();
4247 SourceRange DSR = Dest->getSourceRange();
4248 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00004249 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00004250
4251 if (SM.isMacroArgExpansion(SL)) {
4252 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
4253 SL = SM.getSpellingLoc(SL);
4254 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
4255 SM.getSpellingLoc(DSR.getEnd()));
4256 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
4257 SM.getSpellingLoc(SSR.getEnd()));
4258 }
4259
Anna Zaksd08d9152012-05-30 23:14:52 +00004260 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004261 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00004262 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00004263 << PointeeTy
4264 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00004265 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00004266 << SSR);
4267 DiagRuntimeBehavior(SL, SizeOfArg,
4268 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
4269 << ActionIdx
4270 << SSR);
4271
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004272 break;
4273 }
4274 }
4275
4276 // Also check for cases where the sizeof argument is the exact same
4277 // type as the memory argument, and where it points to a user-defined
4278 // record type.
4279 if (SizeOfArgTy != QualType()) {
4280 if (PointeeTy->isRecordType() &&
4281 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
4282 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
4283 PDiag(diag::warn_sizeof_pointer_type_memaccess)
4284 << FnName << SizeOfArgTy << ArgIdx
4285 << PointeeTy << Dest->getSourceRange()
4286 << LenExpr->getSourceRange());
4287 break;
4288 }
Nico Weberc5e73862011-06-14 16:14:58 +00004289 }
4290
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004291 // Always complain about dynamic classes.
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004292 bool IsContained;
4293 if (const CXXRecordDecl *ContainedRD =
4294 getContainedDynamicClass(PointeeTy, IsContained)) {
Anna Zaks22122702012-01-17 00:37:07 +00004295
4296 unsigned OperationType = 0;
4297 // "overwritten" if we're warning about the destination for any call
4298 // but memcmp; otherwise a verb appropriate to the call.
4299 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
4300 if (BId == Builtin::BImemcpy)
4301 OperationType = 1;
4302 else if(BId == Builtin::BImemmove)
4303 OperationType = 2;
4304 else if (BId == Builtin::BImemcmp)
4305 OperationType = 3;
4306 }
4307
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004308 DiagRuntimeBehavior(
4309 Dest->getExprLoc(), Dest,
4310 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks22122702012-01-17 00:37:07 +00004311 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004312 << FnName << IsContained << ContainedRD << OperationType
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004313 << Call->getCallee()->getSourceRange());
Anna Zaks22122702012-01-17 00:37:07 +00004314 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
4315 BId != Builtin::BImemset)
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004316 DiagRuntimeBehavior(
4317 Dest->getExprLoc(), Dest,
4318 PDiag(diag::warn_arc_object_memaccess)
4319 << ArgIdx << FnName << PointeeTy
4320 << Call->getCallee()->getSourceRange());
John McCall31168b02011-06-15 23:02:42 +00004321 else
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004322 continue;
John McCall31168b02011-06-15 23:02:42 +00004323
4324 DiagRuntimeBehavior(
4325 Dest->getExprLoc(), Dest,
Chandler Carruthac687262011-06-03 06:23:57 +00004326 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004327 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
4328 break;
4329 }
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004330 }
4331}
4332
Ted Kremenek6865f772011-08-18 20:55:45 +00004333// A little helper routine: ignore addition and subtraction of integer literals.
4334// This intentionally does not ignore all integer constant expressions because
4335// we don't want to remove sizeof().
4336static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
4337 Ex = Ex->IgnoreParenCasts();
4338
4339 for (;;) {
4340 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
4341 if (!BO || !BO->isAdditiveOp())
4342 break;
4343
4344 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
4345 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
4346
4347 if (isa<IntegerLiteral>(RHS))
4348 Ex = LHS;
4349 else if (isa<IntegerLiteral>(LHS))
4350 Ex = RHS;
4351 else
4352 break;
4353 }
4354
4355 return Ex;
4356}
4357
Anna Zaks13b08572012-08-08 21:42:23 +00004358static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
4359 ASTContext &Context) {
4360 // Only handle constant-sized or VLAs, but not flexible members.
4361 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
4362 // Only issue the FIXIT for arrays of size > 1.
4363 if (CAT->getSize().getSExtValue() <= 1)
4364 return false;
4365 } else if (!Ty->isVariableArrayType()) {
4366 return false;
4367 }
4368 return true;
4369}
4370
Ted Kremenek6865f772011-08-18 20:55:45 +00004371// Warn if the user has made the 'size' argument to strlcpy or strlcat
4372// be the size of the source, instead of the destination.
4373void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
4374 IdentifierInfo *FnName) {
4375
4376 // Don't crash if the user has the wrong number of arguments
4377 if (Call->getNumArgs() != 3)
4378 return;
4379
4380 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
4381 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00004382 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00004383
4384 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
4385 Call->getLocStart(), Call->getRParenLoc()))
4386 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00004387
4388 // Look for 'strlcpy(dst, x, sizeof(x))'
4389 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
4390 CompareWithSrc = Ex;
4391 else {
4392 // Look for 'strlcpy(dst, x, strlen(x))'
4393 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00004394 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
4395 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00004396 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
4397 }
4398 }
4399
4400 if (!CompareWithSrc)
4401 return;
4402
4403 // Determine if the argument to sizeof/strlen is equal to the source
4404 // argument. In principle there's all kinds of things you could do
4405 // here, for instance creating an == expression and evaluating it with
4406 // EvaluateAsBooleanCondition, but this uses a more direct technique:
4407 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
4408 if (!SrcArgDRE)
4409 return;
4410
4411 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
4412 if (!CompareWithSrcDRE ||
4413 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
4414 return;
4415
4416 const Expr *OriginalSizeArg = Call->getArg(2);
4417 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
4418 << OriginalSizeArg->getSourceRange() << FnName;
4419
4420 // Output a FIXIT hint if the destination is an array (rather than a
4421 // pointer to an array). This could be enhanced to handle some
4422 // pointers if we know the actual size, like if DstArg is 'array+2'
4423 // we could say 'sizeof(array)-2'.
4424 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00004425 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00004426 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004427
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004428 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004429 llvm::raw_svector_ostream OS(sizeString);
4430 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004431 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00004432 OS << ")";
4433
4434 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
4435 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
4436 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00004437}
4438
Anna Zaks314cd092012-02-01 19:08:57 +00004439/// Check if two expressions refer to the same declaration.
4440static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
4441 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
4442 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
4443 return D1->getDecl() == D2->getDecl();
4444 return false;
4445}
4446
4447static const Expr *getStrlenExprArg(const Expr *E) {
4448 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
4449 const FunctionDecl *FD = CE->getDirectCallee();
4450 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00004451 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00004452 return CE->getArg(0)->IgnoreParenCasts();
4453 }
Craig Topperc3ec1492014-05-26 06:22:03 +00004454 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00004455}
4456
4457// Warn on anti-patterns as the 'size' argument to strncat.
4458// The correct size argument should look like following:
4459// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
4460void Sema::CheckStrncatArguments(const CallExpr *CE,
4461 IdentifierInfo *FnName) {
4462 // Don't crash if the user has the wrong number of arguments.
4463 if (CE->getNumArgs() < 3)
4464 return;
4465 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
4466 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
4467 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
4468
Nico Weber0e6daef2013-12-26 23:38:39 +00004469 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
4470 CE->getRParenLoc()))
4471 return;
4472
Anna Zaks314cd092012-02-01 19:08:57 +00004473 // Identify common expressions, which are wrongly used as the size argument
4474 // to strncat and may lead to buffer overflows.
4475 unsigned PatternType = 0;
4476 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
4477 // - sizeof(dst)
4478 if (referToTheSameDecl(SizeOfArg, DstArg))
4479 PatternType = 1;
4480 // - sizeof(src)
4481 else if (referToTheSameDecl(SizeOfArg, SrcArg))
4482 PatternType = 2;
4483 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
4484 if (BE->getOpcode() == BO_Sub) {
4485 const Expr *L = BE->getLHS()->IgnoreParenCasts();
4486 const Expr *R = BE->getRHS()->IgnoreParenCasts();
4487 // - sizeof(dst) - strlen(dst)
4488 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
4489 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
4490 PatternType = 1;
4491 // - sizeof(src) - (anything)
4492 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
4493 PatternType = 2;
4494 }
4495 }
4496
4497 if (PatternType == 0)
4498 return;
4499
Anna Zaks5069aa32012-02-03 01:27:37 +00004500 // Generate the diagnostic.
4501 SourceLocation SL = LenArg->getLocStart();
4502 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00004503 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00004504
4505 // If the function is defined as a builtin macro, do not show macro expansion.
4506 if (SM.isMacroArgExpansion(SL)) {
4507 SL = SM.getSpellingLoc(SL);
4508 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
4509 SM.getSpellingLoc(SR.getEnd()));
4510 }
4511
Anna Zaks13b08572012-08-08 21:42:23 +00004512 // Check if the destination is an array (rather than a pointer to an array).
4513 QualType DstTy = DstArg->getType();
4514 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
4515 Context);
4516 if (!isKnownSizeArray) {
4517 if (PatternType == 1)
4518 Diag(SL, diag::warn_strncat_wrong_size) << SR;
4519 else
4520 Diag(SL, diag::warn_strncat_src_size) << SR;
4521 return;
4522 }
4523
Anna Zaks314cd092012-02-01 19:08:57 +00004524 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00004525 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004526 else
Anna Zaks5069aa32012-02-03 01:27:37 +00004527 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004528
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004529 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00004530 llvm::raw_svector_ostream OS(sizeString);
4531 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004532 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00004533 OS << ") - ";
4534 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004535 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00004536 OS << ") - 1";
4537
Anna Zaks5069aa32012-02-03 01:27:37 +00004538 Diag(SL, diag::note_strncat_wrong_size)
4539 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00004540}
4541
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004542//===--- CHECK: Return Address of Stack Variable --------------------------===//
4543
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004544static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4545 Decl *ParentDecl);
4546static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
4547 Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004548
4549/// CheckReturnStackAddr - Check if a return statement returns the address
4550/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004551static void
4552CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
4553 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00004554
Craig Topperc3ec1492014-05-26 06:22:03 +00004555 Expr *stackE = nullptr;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004556 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004557
4558 // Perform checking for returned stack addresses, local blocks,
4559 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00004560 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004561 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004562 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00004563 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004564 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004565 }
4566
Craig Topperc3ec1492014-05-26 06:22:03 +00004567 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004568 return; // Nothing suspicious was found.
4569
4570 SourceLocation diagLoc;
4571 SourceRange diagRange;
4572 if (refVars.empty()) {
4573 diagLoc = stackE->getLocStart();
4574 diagRange = stackE->getSourceRange();
4575 } else {
4576 // We followed through a reference variable. 'stackE' contains the
4577 // problematic expression but we will warn at the return statement pointing
4578 // at the reference variable. We will later display the "trail" of
4579 // reference variables using notes.
4580 diagLoc = refVars[0]->getLocStart();
4581 diagRange = refVars[0]->getSourceRange();
4582 }
4583
4584 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004585 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004586 : diag::warn_ret_stack_addr)
4587 << DR->getDecl()->getDeclName() << diagRange;
4588 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004589 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004590 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004591 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004592 } else { // local temporary.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004593 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
4594 : diag::warn_ret_local_temp_addr)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004595 << diagRange;
4596 }
4597
4598 // Display the "trail" of reference variables that we followed until we
4599 // found the problematic expression using notes.
4600 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
4601 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
4602 // If this var binds to another reference var, show the range of the next
4603 // var, otherwise the var binds to the problematic expression, in which case
4604 // show the range of the expression.
4605 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
4606 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004607 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
4608 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004609 }
4610}
4611
4612/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
4613/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004614/// to a location on the stack, a local block, an address of a label, or a
4615/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004616/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004617/// encounter a subexpression that (1) clearly does not lead to one of the
4618/// above problematic expressions (2) is something we cannot determine leads to
4619/// a problematic expression based on such local checking.
4620///
4621/// Both EvalAddr and EvalVal follow through reference variables to evaluate
4622/// the expression that they point to. Such variables are added to the
4623/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004624///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00004625/// EvalAddr processes expressions that are pointers that are used as
4626/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004627/// At the base case of the recursion is a check for the above problematic
4628/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004629///
4630/// This implementation handles:
4631///
4632/// * pointer-to-pointer casts
4633/// * implicit conversions from array references to pointers
4634/// * taking the address of fields
4635/// * arbitrary interplay between "&" and "*" operators
4636/// * pointer arithmetic from an address of a stack variable
4637/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004638static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4639 Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004640 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00004641 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004642
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004643 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00004644 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004645 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004646 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00004647 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00004648
Peter Collingbourne91147592011-04-15 00:35:48 +00004649 E = E->IgnoreParens();
4650
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004651 // Our "symbolic interpreter" is just a dispatch off the currently
4652 // viewed AST node. We then recursively traverse the AST by calling
4653 // EvalAddr and EvalVal appropriately.
4654 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004655 case Stmt::DeclRefExprClass: {
4656 DeclRefExpr *DR = cast<DeclRefExpr>(E);
4657
Richard Smith40f08eb2014-01-30 22:05:38 +00004658 // If we leave the immediate function, the lifetime isn't about to end.
4659 if (DR->refersToEnclosingLocal())
Craig Topperc3ec1492014-05-26 06:22:03 +00004660 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00004661
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004662 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
4663 // If this is a reference variable, follow through to the expression that
4664 // it points to.
4665 if (V->hasLocalStorage() &&
4666 V->getType()->isReferenceType() && V->hasInit()) {
4667 // Add the reference variable to the "trail".
4668 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004669 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004670 }
4671
Craig Topperc3ec1492014-05-26 06:22:03 +00004672 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004673 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004674
Chris Lattner934edb22007-12-28 05:31:15 +00004675 case Stmt::UnaryOperatorClass: {
4676 // The only unary operator that make sense to handle here
4677 // is AddrOf. All others don't make sense as pointers.
4678 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004679
John McCalle3027922010-08-25 11:45:40 +00004680 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004681 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004682 else
Craig Topperc3ec1492014-05-26 06:22:03 +00004683 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004684 }
Mike Stump11289f42009-09-09 15:08:12 +00004685
Chris Lattner934edb22007-12-28 05:31:15 +00004686 case Stmt::BinaryOperatorClass: {
4687 // Handle pointer arithmetic. All other binary operators are not valid
4688 // in this context.
4689 BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00004690 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00004691
John McCalle3027922010-08-25 11:45:40 +00004692 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00004693 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004694
Chris Lattner934edb22007-12-28 05:31:15 +00004695 Expr *Base = B->getLHS();
4696
4697 // Determine which argument is the real pointer base. It could be
4698 // the RHS argument instead of the LHS.
4699 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00004700
Chris Lattner934edb22007-12-28 05:31:15 +00004701 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004702 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004703 }
Steve Naroff2752a172008-09-10 19:17:48 +00004704
Chris Lattner934edb22007-12-28 05:31:15 +00004705 // For conditional operators we need to see if either the LHS or RHS are
4706 // valid DeclRefExpr*s. If one of them is valid, we return it.
4707 case Stmt::ConditionalOperatorClass: {
4708 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004709
Chris Lattner934edb22007-12-28 05:31:15 +00004710 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004711 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
4712 if (Expr *LHSExpr = C->getLHS()) {
4713 // In C++, we can have a throw-expression, which has 'void' type.
4714 if (!LHSExpr->getType()->isVoidType())
4715 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004716 return LHS;
4717 }
Chris Lattner934edb22007-12-28 05:31:15 +00004718
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004719 // In C++, we can have a throw-expression, which has 'void' type.
4720 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00004721 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004722
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004723 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004724 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004725
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004726 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00004727 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004728 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00004729 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004730
4731 case Stmt::AddrLabelExprClass:
4732 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00004733
John McCall28fc7092011-11-10 05:35:25 +00004734 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004735 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
4736 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00004737
Ted Kremenekc3b4c522008-08-07 00:49:01 +00004738 // For casts, we need to handle conversions from arrays to
4739 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00004740 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00004741 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00004742 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00004743 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00004744 case Stmt::CXXStaticCastExprClass:
4745 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00004746 case Stmt::CXXConstCastExprClass:
4747 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8195ad72012-02-23 23:04:32 +00004748 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
4749 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00004750 case CK_LValueToRValue:
4751 case CK_NoOp:
4752 case CK_BaseToDerived:
4753 case CK_DerivedToBase:
4754 case CK_UncheckedDerivedToBase:
4755 case CK_Dynamic:
4756 case CK_CPointerToObjCPointerCast:
4757 case CK_BlockPointerToObjCPointerCast:
4758 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004759 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00004760
4761 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004762 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00004763
Richard Trieudadefde2014-07-02 04:39:38 +00004764 case CK_BitCast:
4765 if (SubExpr->getType()->isAnyPointerType() ||
4766 SubExpr->getType()->isBlockPointerType() ||
4767 SubExpr->getType()->isObjCQualifiedIdType())
4768 return EvalAddr(SubExpr, refVars, ParentDecl);
4769 else
4770 return nullptr;
4771
Eli Friedman8195ad72012-02-23 23:04:32 +00004772 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00004773 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00004774 }
Chris Lattner934edb22007-12-28 05:31:15 +00004775 }
Mike Stump11289f42009-09-09 15:08:12 +00004776
Douglas Gregorfe314812011-06-21 17:03:29 +00004777 case Stmt::MaterializeTemporaryExprClass:
4778 if (Expr *Result = EvalAddr(
4779 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004780 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00004781 return Result;
4782
4783 return E;
4784
Chris Lattner934edb22007-12-28 05:31:15 +00004785 // Everything else: we simply don't reason about them.
4786 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00004787 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00004788 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004789}
Mike Stump11289f42009-09-09 15:08:12 +00004790
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004791
4792/// EvalVal - This function is complements EvalAddr in the mutual recursion.
4793/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004794static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4795 Decl *ParentDecl) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004796do {
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00004797 // We should only be called for evaluating non-pointer expressions, or
4798 // expressions with a pointer type that are not used as references but instead
4799 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00004800
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004801 // Our "symbolic interpreter" is just a dispatch off the currently
4802 // viewed AST node. We then recursively traverse the AST by calling
4803 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00004804
4805 E = E->IgnoreParens();
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004806 switch (E->getStmtClass()) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004807 case Stmt::ImplicitCastExprClass: {
4808 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall2536c6d2010-08-25 10:28:54 +00004809 if (IE->getValueKind() == VK_LValue) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004810 E = IE->getSubExpr();
4811 continue;
4812 }
Craig Topperc3ec1492014-05-26 06:22:03 +00004813 return nullptr;
Ted Kremenekb7861562010-08-04 20:01:07 +00004814 }
4815
John McCall28fc7092011-11-10 05:35:25 +00004816 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004817 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00004818
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004819 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004820 // When we hit a DeclRefExpr we are looking at code that refers to a
4821 // variable's name. If it's not a reference variable we check if it has
4822 // local storage within the function, and if so, return the expression.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004823 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004824
Richard Smith40f08eb2014-01-30 22:05:38 +00004825 // If we leave the immediate function, the lifetime isn't about to end.
4826 if (DR->refersToEnclosingLocal())
Craig Topperc3ec1492014-05-26 06:22:03 +00004827 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00004828
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004829 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
4830 // Check if it refers to itself, e.g. "int& i = i;".
4831 if (V == ParentDecl)
4832 return DR;
4833
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004834 if (V->hasLocalStorage()) {
4835 if (!V->getType()->isReferenceType())
4836 return DR;
4837
4838 // Reference variable, follow through to the expression that
4839 // it points to.
4840 if (V->hasInit()) {
4841 // Add the reference variable to the "trail".
4842 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004843 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004844 }
4845 }
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004846 }
Mike Stump11289f42009-09-09 15:08:12 +00004847
Craig Topperc3ec1492014-05-26 06:22:03 +00004848 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004849 }
Mike Stump11289f42009-09-09 15:08:12 +00004850
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004851 case Stmt::UnaryOperatorClass: {
4852 // The only unary operator that make sense to handle here
4853 // is Deref. All others don't resolve to a "name." This includes
4854 // handling all sorts of rvalues passed to a unary operator.
4855 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004856
John McCalle3027922010-08-25 11:45:40 +00004857 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004858 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004859
Craig Topperc3ec1492014-05-26 06:22:03 +00004860 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004861 }
Mike Stump11289f42009-09-09 15:08:12 +00004862
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004863 case Stmt::ArraySubscriptExprClass: {
4864 // Array subscripts are potential references to data on the stack. We
4865 // retrieve the DeclRefExpr* for the array variable if it indeed
4866 // has local storage.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004867 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004868 }
Mike Stump11289f42009-09-09 15:08:12 +00004869
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004870 case Stmt::ConditionalOperatorClass: {
4871 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004872 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004873 ConditionalOperator *C = cast<ConditionalOperator>(E);
4874
Anders Carlsson801c5c72007-11-30 19:04:31 +00004875 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004876 if (Expr *LHSExpr = C->getLHS()) {
4877 // In C++, we can have a throw-expression, which has 'void' type.
4878 if (!LHSExpr->getType()->isVoidType())
4879 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
4880 return LHS;
4881 }
4882
4883 // In C++, we can have a throw-expression, which has 'void' type.
4884 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00004885 return nullptr;
Anders Carlsson801c5c72007-11-30 19:04:31 +00004886
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004887 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004888 }
Mike Stump11289f42009-09-09 15:08:12 +00004889
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004890 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00004891 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004892 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004893
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004894 // Check for indirect access. We only want direct field accesses.
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00004895 if (M->isArrow())
Craig Topperc3ec1492014-05-26 06:22:03 +00004896 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00004897
4898 // Check whether the member type is itself a reference, in which case
4899 // we're not going to refer to the member, but to what the member refers to.
4900 if (M->getMemberDecl()->getType()->isReferenceType())
Craig Topperc3ec1492014-05-26 06:22:03 +00004901 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00004902
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004903 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004904 }
Mike Stump11289f42009-09-09 15:08:12 +00004905
Douglas Gregorfe314812011-06-21 17:03:29 +00004906 case Stmt::MaterializeTemporaryExprClass:
4907 if (Expr *Result = EvalVal(
4908 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004909 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00004910 return Result;
4911
4912 return E;
4913
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004914 default:
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004915 // Check that we don't return or take the address of a reference to a
4916 // temporary. This is only useful in C++.
4917 if (!E->isTypeDependent() && E->isRValue())
4918 return E;
4919
4920 // Everything else: we simply don't reason about them.
Craig Topperc3ec1492014-05-26 06:22:03 +00004921 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004922 }
Ted Kremenekb7861562010-08-04 20:01:07 +00004923} while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004924}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004925
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004926void
4927Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
4928 SourceLocation ReturnLoc,
4929 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00004930 const AttrVec *Attrs,
4931 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004932 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
4933
4934 // Check if the return value is null but should not be.
Benjamin Kramerae852a62014-02-23 14:34:50 +00004935 if (Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs) &&
4936 CheckNonNullExpr(*this, RetValExp))
4937 Diag(ReturnLoc, diag::warn_null_ret)
4938 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00004939
4940 // C++11 [basic.stc.dynamic.allocation]p4:
4941 // If an allocation function declared with a non-throwing
4942 // exception-specification fails to allocate storage, it shall return
4943 // a null pointer. Any other allocation function that fails to allocate
4944 // storage shall indicate failure only by throwing an exception [...]
4945 if (FD) {
4946 OverloadedOperatorKind Op = FD->getOverloadedOperator();
4947 if (Op == OO_New || Op == OO_Array_New) {
4948 const FunctionProtoType *Proto
4949 = FD->getType()->castAs<FunctionProtoType>();
4950 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
4951 CheckNonNullExpr(*this, RetValExp))
4952 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
4953 << FD << getLangOpts().CPlusPlus11;
4954 }
4955 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004956}
4957
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004958//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
4959
4960/// Check for comparisons of floating point operands using != and ==.
4961/// Issue a warning if these are no self-comparisons, as they are not likely
4962/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00004963void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00004964 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
4965 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004966
4967 // Special case: check for x == x (which is OK).
4968 // Do not emit warnings for such cases.
4969 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
4970 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
4971 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00004972 return;
Mike Stump11289f42009-09-09 15:08:12 +00004973
4974
Ted Kremenekeda40e22007-11-29 00:59:04 +00004975 // Special case: check for comparisons against literals that can be exactly
4976 // represented by APFloat. In such cases, do not emit a warning. This
4977 // is a heuristic: often comparison against such literals are used to
4978 // detect if a value in a variable has not changed. This clearly can
4979 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00004980 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
4981 if (FLL->isExact())
4982 return;
4983 } else
4984 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
4985 if (FLR->isExact())
4986 return;
Mike Stump11289f42009-09-09 15:08:12 +00004987
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004988 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00004989 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00004990 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00004991 return;
Mike Stump11289f42009-09-09 15:08:12 +00004992
David Blaikie1f4ff152012-07-16 20:47:22 +00004993 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00004994 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00004995 return;
Mike Stump11289f42009-09-09 15:08:12 +00004996
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004997 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00004998 Diag(Loc, diag::warn_floatingpoint_eq)
4999 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005000}
John McCallca01b222010-01-04 23:21:16 +00005001
John McCall70aa5392010-01-06 05:24:50 +00005002//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
5003//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00005004
John McCall70aa5392010-01-06 05:24:50 +00005005namespace {
John McCallca01b222010-01-04 23:21:16 +00005006
John McCall70aa5392010-01-06 05:24:50 +00005007/// Structure recording the 'active' range of an integer-valued
5008/// expression.
5009struct IntRange {
5010 /// The number of bits active in the int.
5011 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00005012
John McCall70aa5392010-01-06 05:24:50 +00005013 /// True if the int is known not to have negative values.
5014 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00005015
John McCall70aa5392010-01-06 05:24:50 +00005016 IntRange(unsigned Width, bool NonNegative)
5017 : Width(Width), NonNegative(NonNegative)
5018 {}
John McCallca01b222010-01-04 23:21:16 +00005019
John McCall817d4af2010-11-10 23:38:19 +00005020 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00005021 static IntRange forBoolType() {
5022 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00005023 }
5024
John McCall817d4af2010-11-10 23:38:19 +00005025 /// Returns the range of an opaque value of the given integral type.
5026 static IntRange forValueOfType(ASTContext &C, QualType T) {
5027 return forValueOfCanonicalType(C,
5028 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00005029 }
5030
John McCall817d4af2010-11-10 23:38:19 +00005031 /// Returns the range of an opaque value of a canonical integral type.
5032 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00005033 assert(T->isCanonicalUnqualified());
5034
5035 if (const VectorType *VT = dyn_cast<VectorType>(T))
5036 T = VT->getElementType().getTypePtr();
5037 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5038 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005039 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5040 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00005041
David Majnemer6a426652013-06-07 22:07:20 +00005042 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00005043 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00005044 EnumDecl *Enum = ET->getDecl();
5045 if (!Enum->isCompleteDefinition())
5046 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00005047
David Majnemer6a426652013-06-07 22:07:20 +00005048 unsigned NumPositive = Enum->getNumPositiveBits();
5049 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00005050
David Majnemer6a426652013-06-07 22:07:20 +00005051 if (NumNegative == 0)
5052 return IntRange(NumPositive, true/*NonNegative*/);
5053 else
5054 return IntRange(std::max(NumPositive + 1, NumNegative),
5055 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00005056 }
John McCall70aa5392010-01-06 05:24:50 +00005057
5058 const BuiltinType *BT = cast<BuiltinType>(T);
5059 assert(BT->isInteger());
5060
5061 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5062 }
5063
John McCall817d4af2010-11-10 23:38:19 +00005064 /// Returns the "target" range of a canonical integral type, i.e.
5065 /// the range of values expressible in the type.
5066 ///
5067 /// This matches forValueOfCanonicalType except that enums have the
5068 /// full range of their type, not the range of their enumerators.
5069 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
5070 assert(T->isCanonicalUnqualified());
5071
5072 if (const VectorType *VT = dyn_cast<VectorType>(T))
5073 T = VT->getElementType().getTypePtr();
5074 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5075 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005076 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5077 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00005078 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00005079 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00005080
5081 const BuiltinType *BT = cast<BuiltinType>(T);
5082 assert(BT->isInteger());
5083
5084 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5085 }
5086
5087 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00005088 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00005089 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00005090 L.NonNegative && R.NonNegative);
5091 }
5092
John McCall817d4af2010-11-10 23:38:19 +00005093 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00005094 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00005095 return IntRange(std::min(L.Width, R.Width),
5096 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00005097 }
5098};
5099
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005100static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
5101 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005102 if (value.isSigned() && value.isNegative())
5103 return IntRange(value.getMinSignedBits(), false);
5104
5105 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00005106 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00005107
5108 // isNonNegative() just checks the sign bit without considering
5109 // signedness.
5110 return IntRange(value.getActiveBits(), true);
5111}
5112
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005113static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
5114 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005115 if (result.isInt())
5116 return GetValueRange(C, result.getInt(), MaxWidth);
5117
5118 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00005119 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
5120 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
5121 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
5122 R = IntRange::join(R, El);
5123 }
John McCall70aa5392010-01-06 05:24:50 +00005124 return R;
5125 }
5126
5127 if (result.isComplexInt()) {
5128 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
5129 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
5130 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00005131 }
5132
5133 // This can happen with lossless casts to intptr_t of "based" lvalues.
5134 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00005135 // FIXME: The only reason we need to pass the type in here is to get
5136 // the sign right on this one case. It would be nice if APValue
5137 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005138 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00005139 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00005140}
John McCall70aa5392010-01-06 05:24:50 +00005141
Eli Friedmane6d33952013-07-08 20:20:06 +00005142static QualType GetExprType(Expr *E) {
5143 QualType Ty = E->getType();
5144 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
5145 Ty = AtomicRHS->getValueType();
5146 return Ty;
5147}
5148
John McCall70aa5392010-01-06 05:24:50 +00005149/// Pseudo-evaluate the given integer expression, estimating the
5150/// range of values it might take.
5151///
5152/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005153static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005154 E = E->IgnoreParens();
5155
5156 // Try a full evaluation first.
5157 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00005158 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00005159 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00005160
5161 // I think we only want to look through implicit casts here; if the
5162 // user has an explicit widening cast, we should treat the value as
5163 // being of the new, wider type.
5164 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00005165 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00005166 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
5167
Eli Friedmane6d33952013-07-08 20:20:06 +00005168 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00005169
John McCalle3027922010-08-25 11:45:40 +00005170 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall2ce81ad2010-01-06 22:07:33 +00005171
John McCall70aa5392010-01-06 05:24:50 +00005172 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00005173 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00005174 return OutputTypeRange;
5175
5176 IntRange SubRange
5177 = GetExprRange(C, CE->getSubExpr(),
5178 std::min(MaxWidth, OutputTypeRange.Width));
5179
5180 // Bail out if the subexpr's range is as wide as the cast type.
5181 if (SubRange.Width >= OutputTypeRange.Width)
5182 return OutputTypeRange;
5183
5184 // Otherwise, we take the smaller width, and we're non-negative if
5185 // either the output type or the subexpr is.
5186 return IntRange(SubRange.Width,
5187 SubRange.NonNegative || OutputTypeRange.NonNegative);
5188 }
5189
5190 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5191 // If we can fold the condition, just take that operand.
5192 bool CondResult;
5193 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
5194 return GetExprRange(C, CondResult ? CO->getTrueExpr()
5195 : CO->getFalseExpr(),
5196 MaxWidth);
5197
5198 // Otherwise, conservatively merge.
5199 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
5200 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
5201 return IntRange::join(L, R);
5202 }
5203
5204 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5205 switch (BO->getOpcode()) {
5206
5207 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00005208 case BO_LAnd:
5209 case BO_LOr:
5210 case BO_LT:
5211 case BO_GT:
5212 case BO_LE:
5213 case BO_GE:
5214 case BO_EQ:
5215 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00005216 return IntRange::forBoolType();
5217
John McCallc3688382011-07-13 06:35:24 +00005218 // The type of the assignments is the type of the LHS, so the RHS
5219 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00005220 case BO_MulAssign:
5221 case BO_DivAssign:
5222 case BO_RemAssign:
5223 case BO_AddAssign:
5224 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00005225 case BO_XorAssign:
5226 case BO_OrAssign:
5227 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00005228 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00005229
John McCallc3688382011-07-13 06:35:24 +00005230 // Simple assignments just pass through the RHS, which will have
5231 // been coerced to the LHS type.
5232 case BO_Assign:
5233 // TODO: bitfields?
5234 return GetExprRange(C, BO->getRHS(), MaxWidth);
5235
John McCall70aa5392010-01-06 05:24:50 +00005236 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005237 case BO_PtrMemD:
5238 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00005239 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005240
John McCall2ce81ad2010-01-06 22:07:33 +00005241 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00005242 case BO_And:
5243 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00005244 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
5245 GetExprRange(C, BO->getRHS(), MaxWidth));
5246
John McCall70aa5392010-01-06 05:24:50 +00005247 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00005248 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00005249 // ...except that we want to treat '1 << (blah)' as logically
5250 // positive. It's an important idiom.
5251 if (IntegerLiteral *I
5252 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
5253 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005254 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00005255 return IntRange(R.Width, /*NonNegative*/ true);
5256 }
5257 }
5258 // fallthrough
5259
John McCalle3027922010-08-25 11:45:40 +00005260 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00005261 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005262
John McCall2ce81ad2010-01-06 22:07:33 +00005263 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00005264 case BO_Shr:
5265 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00005266 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5267
5268 // If the shift amount is a positive constant, drop the width by
5269 // that much.
5270 llvm::APSInt shift;
5271 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
5272 shift.isNonNegative()) {
5273 unsigned zext = shift.getZExtValue();
5274 if (zext >= L.Width)
5275 L.Width = (L.NonNegative ? 0 : 1);
5276 else
5277 L.Width -= zext;
5278 }
5279
5280 return L;
5281 }
5282
5283 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00005284 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00005285 return GetExprRange(C, BO->getRHS(), MaxWidth);
5286
John McCall2ce81ad2010-01-06 22:07:33 +00005287 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00005288 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00005289 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00005290 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005291 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005292
John McCall51431812011-07-14 22:39:48 +00005293 // The width of a division result is mostly determined by the size
5294 // of the LHS.
5295 case BO_Div: {
5296 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005297 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005298 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5299
5300 // If the divisor is constant, use that.
5301 llvm::APSInt divisor;
5302 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
5303 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
5304 if (log2 >= L.Width)
5305 L.Width = (L.NonNegative ? 0 : 1);
5306 else
5307 L.Width = std::min(L.Width - log2, MaxWidth);
5308 return L;
5309 }
5310
5311 // Otherwise, just use the LHS's width.
5312 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5313 return IntRange(L.Width, L.NonNegative && R.NonNegative);
5314 }
5315
5316 // The result of a remainder can't be larger than the result of
5317 // either side.
5318 case BO_Rem: {
5319 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005320 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005321 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5322 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5323
5324 IntRange meet = IntRange::meet(L, R);
5325 meet.Width = std::min(meet.Width, MaxWidth);
5326 return meet;
5327 }
5328
5329 // The default behavior is okay for these.
5330 case BO_Mul:
5331 case BO_Add:
5332 case BO_Xor:
5333 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00005334 break;
5335 }
5336
John McCall51431812011-07-14 22:39:48 +00005337 // The default case is to treat the operation as if it were closed
5338 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00005339 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5340 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
5341 return IntRange::join(L, R);
5342 }
5343
5344 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5345 switch (UO->getOpcode()) {
5346 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00005347 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00005348 return IntRange::forBoolType();
5349
5350 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005351 case UO_Deref:
5352 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00005353 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005354
5355 default:
5356 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
5357 }
5358 }
5359
Ted Kremeneka553fbf2013-10-14 18:55:27 +00005360 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5361 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
5362
John McCalld25db7e2013-05-06 21:39:12 +00005363 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00005364 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00005365 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00005366
Eli Friedmane6d33952013-07-08 20:20:06 +00005367 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005368}
John McCall263a48b2010-01-04 23:31:57 +00005369
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005370static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005371 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00005372}
5373
John McCall263a48b2010-01-04 23:31:57 +00005374/// Checks whether the given value, which currently has the given
5375/// source semantics, has the same value when coerced through the
5376/// target semantics.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005377static bool IsSameFloatAfterCast(const llvm::APFloat &value,
5378 const llvm::fltSemantics &Src,
5379 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005380 llvm::APFloat truncated = value;
5381
5382 bool ignored;
5383 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
5384 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
5385
5386 return truncated.bitwiseIsEqual(value);
5387}
5388
5389/// Checks whether the given value, which currently has the given
5390/// source semantics, has the same value when coerced through the
5391/// target semantics.
5392///
5393/// The value might be a vector of floats (or a complex number).
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005394static bool IsSameFloatAfterCast(const APValue &value,
5395 const llvm::fltSemantics &Src,
5396 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005397 if (value.isFloat())
5398 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
5399
5400 if (value.isVector()) {
5401 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
5402 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
5403 return false;
5404 return true;
5405 }
5406
5407 assert(value.isComplexFloat());
5408 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
5409 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
5410}
5411
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005412static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005413
Ted Kremenek6274be42010-09-23 21:43:44 +00005414static bool IsZero(Sema &S, Expr *E) {
5415 // Suppress cases where we are comparing against an enum constant.
5416 if (const DeclRefExpr *DR =
5417 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
5418 if (isa<EnumConstantDecl>(DR->getDecl()))
5419 return false;
5420
5421 // Suppress cases where the '0' value is expanded from a macro.
5422 if (E->getLocStart().isMacroID())
5423 return false;
5424
John McCallcc7e5bf2010-05-06 08:58:33 +00005425 llvm::APSInt Value;
5426 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
5427}
5428
John McCall2551c1b2010-10-06 00:25:24 +00005429static bool HasEnumType(Expr *E) {
5430 // Strip off implicit integral promotions.
5431 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005432 if (ICE->getCastKind() != CK_IntegralCast &&
5433 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00005434 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005435 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00005436 }
5437
5438 return E->getType()->isEnumeralType();
5439}
5440
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005441static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00005442 // Disable warning in template instantiations.
5443 if (!S.ActiveTemplateInstantiations.empty())
5444 return;
5445
John McCalle3027922010-08-25 11:45:40 +00005446 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00005447 if (E->isValueDependent())
5448 return;
5449
John McCalle3027922010-08-25 11:45:40 +00005450 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005451 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005452 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005453 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005454 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005455 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005456 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005457 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005458 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005459 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005460 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005461 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005462 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005463 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005464 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005465 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5466 }
5467}
5468
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005469static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005470 Expr *Constant, Expr *Other,
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005471 llvm::APSInt Value,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005472 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00005473 // Disable warning in template instantiations.
5474 if (!S.ActiveTemplateInstantiations.empty())
5475 return;
5476
Richard Trieu0f097742014-04-04 04:13:47 +00005477 // TODO: Investigate using GetExprRange() to get tighter bounds
5478 // on the bit ranges.
5479 QualType OtherT = Other->getType();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005480 if (const AtomicType *AT = dyn_cast<AtomicType>(OtherT))
5481 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00005482 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
5483 unsigned OtherWidth = OtherRange.Width;
5484
5485 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
5486
Richard Trieu560910c2012-11-14 22:50:24 +00005487 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00005488 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00005489 return;
5490
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005491 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00005492 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00005493
Richard Trieu0f097742014-04-04 04:13:47 +00005494 // Used for diagnostic printout.
5495 enum {
5496 LiteralConstant = 0,
5497 CXXBoolLiteralTrue,
5498 CXXBoolLiteralFalse
5499 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00005500
Richard Trieu0f097742014-04-04 04:13:47 +00005501 if (!OtherIsBooleanType) {
5502 QualType ConstantT = Constant->getType();
5503 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00005504
Richard Trieu0f097742014-04-04 04:13:47 +00005505 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
5506 return;
5507 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
5508 "comparison with non-integer type");
5509
5510 bool ConstantSigned = ConstantT->isSignedIntegerType();
5511 bool CommonSigned = CommonT->isSignedIntegerType();
5512
5513 bool EqualityOnly = false;
5514
5515 if (CommonSigned) {
5516 // The common type is signed, therefore no signed to unsigned conversion.
5517 if (!OtherRange.NonNegative) {
5518 // Check that the constant is representable in type OtherT.
5519 if (ConstantSigned) {
5520 if (OtherWidth >= Value.getMinSignedBits())
5521 return;
5522 } else { // !ConstantSigned
5523 if (OtherWidth >= Value.getActiveBits() + 1)
5524 return;
5525 }
5526 } else { // !OtherSigned
5527 // Check that the constant is representable in type OtherT.
5528 // Negative values are out of range.
5529 if (ConstantSigned) {
5530 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
5531 return;
5532 } else { // !ConstantSigned
5533 if (OtherWidth >= Value.getActiveBits())
5534 return;
5535 }
Richard Trieu560910c2012-11-14 22:50:24 +00005536 }
Richard Trieu0f097742014-04-04 04:13:47 +00005537 } else { // !CommonSigned
5538 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00005539 if (OtherWidth >= Value.getActiveBits())
5540 return;
Craig Toppercf360162014-06-18 05:13:11 +00005541 } else { // OtherSigned
5542 assert(!ConstantSigned &&
5543 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00005544 // Check to see if the constant is representable in OtherT.
5545 if (OtherWidth > Value.getActiveBits())
5546 return;
5547 // Check to see if the constant is equivalent to a negative value
5548 // cast to CommonT.
5549 if (S.Context.getIntWidth(ConstantT) ==
5550 S.Context.getIntWidth(CommonT) &&
5551 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
5552 return;
5553 // The constant value rests between values that OtherT can represent
5554 // after conversion. Relational comparison still works, but equality
5555 // comparisons will be tautological.
5556 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00005557 }
5558 }
Richard Trieu0f097742014-04-04 04:13:47 +00005559
5560 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
5561
5562 if (op == BO_EQ || op == BO_NE) {
5563 IsTrue = op == BO_NE;
5564 } else if (EqualityOnly) {
5565 return;
5566 } else if (RhsConstant) {
5567 if (op == BO_GT || op == BO_GE)
5568 IsTrue = !PositiveConstant;
5569 else // op == BO_LT || op == BO_LE
5570 IsTrue = PositiveConstant;
5571 } else {
5572 if (op == BO_LT || op == BO_LE)
5573 IsTrue = !PositiveConstant;
5574 else // op == BO_GT || op == BO_GE
5575 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00005576 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005577 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00005578 // Other isKnownToHaveBooleanValue
5579 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
5580 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
5581 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
5582
5583 static const struct LinkedConditions {
5584 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
5585 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
5586 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
5587 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
5588 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
5589 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
5590
5591 } TruthTable = {
5592 // Constant on LHS. | Constant on RHS. |
5593 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
5594 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
5595 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
5596 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
5597 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
5598 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
5599 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
5600 };
5601
5602 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
5603
5604 enum ConstantValue ConstVal = Zero;
5605 if (Value.isUnsigned() || Value.isNonNegative()) {
5606 if (Value == 0) {
5607 LiteralOrBoolConstant =
5608 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
5609 ConstVal = Zero;
5610 } else if (Value == 1) {
5611 LiteralOrBoolConstant =
5612 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
5613 ConstVal = One;
5614 } else {
5615 LiteralOrBoolConstant = LiteralConstant;
5616 ConstVal = GT_One;
5617 }
5618 } else {
5619 ConstVal = LT_Zero;
5620 }
5621
5622 CompareBoolWithConstantResult CmpRes;
5623
5624 switch (op) {
5625 case BO_LT:
5626 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
5627 break;
5628 case BO_GT:
5629 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
5630 break;
5631 case BO_LE:
5632 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
5633 break;
5634 case BO_GE:
5635 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
5636 break;
5637 case BO_EQ:
5638 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
5639 break;
5640 case BO_NE:
5641 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
5642 break;
5643 default:
5644 CmpRes = Unkwn;
5645 break;
5646 }
5647
5648 if (CmpRes == AFals) {
5649 IsTrue = false;
5650 } else if (CmpRes == ATrue) {
5651 IsTrue = true;
5652 } else {
5653 return;
5654 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005655 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005656
5657 // If this is a comparison to an enum constant, include that
5658 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00005659 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005660 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
5661 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
5662
5663 SmallString<64> PrettySourceValue;
5664 llvm::raw_svector_ostream OS(PrettySourceValue);
5665 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00005666 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005667 else
5668 OS << Value;
5669
Richard Trieu0f097742014-04-04 04:13:47 +00005670 S.DiagRuntimeBehavior(
5671 E->getOperatorLoc(), E,
5672 S.PDiag(diag::warn_out_of_range_compare)
5673 << OS.str() << LiteralOrBoolConstant
5674 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
5675 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005676}
5677
John McCallcc7e5bf2010-05-06 08:58:33 +00005678/// Analyze the operands of the given comparison. Implements the
5679/// fallback case from AnalyzeComparison.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005680static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00005681 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5682 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00005683}
John McCall263a48b2010-01-04 23:31:57 +00005684
John McCallca01b222010-01-04 23:21:16 +00005685/// \brief Implements -Wsign-compare.
5686///
Richard Trieu82402a02011-09-15 21:56:47 +00005687/// \param E the binary operator to check for warnings
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005688static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005689 // The type the comparison is being performed in.
5690 QualType T = E->getLHS()->getType();
5691 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
5692 && "comparison with mismatched types");
Fariborz Jahanian282071e2012-09-18 17:46:26 +00005693 if (E->isValueDependent())
5694 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005695
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005696 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
5697 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005698
5699 bool IsComparisonConstant = false;
5700
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005701 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005702 // of 'true' or 'false'.
5703 if (T->isIntegralType(S.Context)) {
5704 llvm::APSInt RHSValue;
5705 bool IsRHSIntegralLiteral =
5706 RHS->isIntegerConstantExpr(RHSValue, S.Context);
5707 llvm::APSInt LHSValue;
5708 bool IsLHSIntegralLiteral =
5709 LHS->isIntegerConstantExpr(LHSValue, S.Context);
5710 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
5711 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
5712 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
5713 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
5714 else
5715 IsComparisonConstant =
5716 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005717 } else if (!T->hasUnsignedIntegerRepresentation())
5718 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005719
John McCallcc7e5bf2010-05-06 08:58:33 +00005720 // We don't do anything special if this isn't an unsigned integral
5721 // comparison: we're only interested in integral comparisons, and
5722 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00005723 //
5724 // We also don't care about value-dependent expressions or expressions
5725 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005726 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00005727 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005728
John McCallcc7e5bf2010-05-06 08:58:33 +00005729 // Check to see if one of the (unmodified) operands is of different
5730 // signedness.
5731 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00005732 if (LHS->getType()->hasSignedIntegerRepresentation()) {
5733 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00005734 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00005735 signedOperand = LHS;
5736 unsignedOperand = RHS;
5737 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
5738 signedOperand = RHS;
5739 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00005740 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00005741 CheckTrivialUnsignedComparison(S, E);
5742 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005743 }
5744
John McCallcc7e5bf2010-05-06 08:58:33 +00005745 // Otherwise, calculate the effective range of the signed operand.
5746 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00005747
John McCallcc7e5bf2010-05-06 08:58:33 +00005748 // Go ahead and analyze implicit conversions in the operands. Note
5749 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00005750 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
5751 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00005752
John McCallcc7e5bf2010-05-06 08:58:33 +00005753 // If the signed range is non-negative, -Wsign-compare won't fire,
5754 // but we should still check for comparisons which are always true
5755 // or false.
5756 if (signedRange.NonNegative)
5757 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005758
5759 // For (in)equality comparisons, if the unsigned operand is a
5760 // constant which cannot collide with a overflowed signed operand,
5761 // then reinterpreting the signed operand as unsigned will not
5762 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00005763 if (E->isEqualityOp()) {
5764 unsigned comparisonWidth = S.Context.getIntWidth(T);
5765 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00005766
John McCallcc7e5bf2010-05-06 08:58:33 +00005767 // We should never be unable to prove that the unsigned operand is
5768 // non-negative.
5769 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
5770
5771 if (unsignedRange.Width < comparisonWidth)
5772 return;
5773 }
5774
Douglas Gregorbfb4a212012-05-01 01:53:49 +00005775 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
5776 S.PDiag(diag::warn_mixed_sign_comparison)
5777 << LHS->getType() << RHS->getType()
5778 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00005779}
5780
John McCall1f425642010-11-11 03:21:53 +00005781/// Analyzes an attempt to assign the given value to a bitfield.
5782///
5783/// Returns true if there was something fishy about the attempt.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005784static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
5785 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00005786 assert(Bitfield->isBitField());
5787 if (Bitfield->isInvalidDecl())
5788 return false;
5789
John McCalldeebbcf2010-11-11 05:33:51 +00005790 // White-list bool bitfields.
5791 if (Bitfield->getType()->isBooleanType())
5792 return false;
5793
Douglas Gregor789adec2011-02-04 13:09:01 +00005794 // Ignore value- or type-dependent expressions.
5795 if (Bitfield->getBitWidth()->isValueDependent() ||
5796 Bitfield->getBitWidth()->isTypeDependent() ||
5797 Init->isValueDependent() ||
5798 Init->isTypeDependent())
5799 return false;
5800
John McCall1f425642010-11-11 03:21:53 +00005801 Expr *OriginalInit = Init->IgnoreParenImpCasts();
5802
Richard Smith5fab0c92011-12-28 19:48:30 +00005803 llvm::APSInt Value;
5804 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00005805 return false;
5806
John McCall1f425642010-11-11 03:21:53 +00005807 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00005808 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00005809
5810 if (OriginalWidth <= FieldWidth)
5811 return false;
5812
Eli Friedmanc267a322012-01-26 23:11:39 +00005813 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00005814 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00005815 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00005816
Eli Friedmanc267a322012-01-26 23:11:39 +00005817 // Check whether the stored value is equal to the original value.
5818 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00005819 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00005820 return false;
5821
Eli Friedmanc267a322012-01-26 23:11:39 +00005822 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00005823 // therefore don't strictly fit into a signed bitfield of width 1.
5824 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00005825 return false;
5826
John McCall1f425642010-11-11 03:21:53 +00005827 std::string PrettyValue = Value.toString(10);
5828 std::string PrettyTrunc = TruncatedValue.toString(10);
5829
5830 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
5831 << PrettyValue << PrettyTrunc << OriginalInit->getType()
5832 << Init->getSourceRange();
5833
5834 return true;
5835}
5836
John McCalld2a53122010-11-09 23:24:47 +00005837/// Analyze the given simple or compound assignment for warning-worthy
5838/// operations.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005839static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00005840 // Just recurse on the LHS.
5841 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5842
5843 // We want to recurse on the RHS as normal unless we're assigning to
5844 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00005845 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005846 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00005847 E->getOperatorLoc())) {
5848 // Recurse, ignoring any implicit conversions on the RHS.
5849 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
5850 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00005851 }
5852 }
5853
5854 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
5855}
5856
John McCall263a48b2010-01-04 23:31:57 +00005857/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005858static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00005859 SourceLocation CContext, unsigned diag,
5860 bool pruneControlFlow = false) {
5861 if (pruneControlFlow) {
5862 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5863 S.PDiag(diag)
5864 << SourceType << T << E->getSourceRange()
5865 << SourceRange(CContext));
5866 return;
5867 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00005868 S.Diag(E->getExprLoc(), diag)
5869 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
5870}
5871
Chandler Carruth7f3654f2011-04-05 06:47:57 +00005872/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005873static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00005874 SourceLocation CContext, unsigned diag,
5875 bool pruneControlFlow = false) {
5876 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00005877}
5878
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005879/// Diagnose an implicit cast from a literal expression. Does not warn when the
5880/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00005881void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
5882 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005883 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00005884 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005885 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00005886 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
5887 T->hasUnsignedIntegerRepresentation());
5888 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00005889 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005890 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00005891 return;
5892
Eli Friedman07185912013-08-29 23:44:43 +00005893 // FIXME: Force the precision of the source value down so we don't print
5894 // digits which are usually useless (we don't really care here if we
5895 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
5896 // would automatically print the shortest representation, but it's a bit
5897 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00005898 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00005899 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
5900 precision = (precision * 59 + 195) / 196;
5901 Value.toString(PrettySourceValue, precision);
5902
David Blaikie9b88cc02012-05-15 17:18:27 +00005903 SmallString<16> PrettyTargetValue;
David Blaikie7555b6a2012-05-15 16:56:36 +00005904 if (T->isSpecificBuiltinType(BuiltinType::Bool))
5905 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
5906 else
David Blaikie9b88cc02012-05-15 17:18:27 +00005907 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00005908
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005909 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikie7555b6a2012-05-15 16:56:36 +00005910 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
5911 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00005912}
5913
John McCall18a2c2c2010-11-09 22:22:12 +00005914std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
5915 if (!Range.Width) return "0";
5916
5917 llvm::APSInt ValueInRange = Value;
5918 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00005919 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00005920 return ValueInRange.toString(10);
5921}
5922
Hans Wennborgf4ad2322012-08-28 15:44:30 +00005923static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
5924 if (!isa<ImplicitCastExpr>(Ex))
5925 return false;
5926
5927 Expr *InnerE = Ex->IgnoreParenImpCasts();
5928 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
5929 const Type *Source =
5930 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5931 if (Target->isDependentType())
5932 return false;
5933
5934 const BuiltinType *FloatCandidateBT =
5935 dyn_cast<BuiltinType>(ToBool ? Source : Target);
5936 const Type *BoolCandidateType = ToBool ? Target : Source;
5937
5938 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
5939 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
5940}
5941
5942void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
5943 SourceLocation CC) {
5944 unsigned NumArgs = TheCall->getNumArgs();
5945 for (unsigned i = 0; i < NumArgs; ++i) {
5946 Expr *CurrA = TheCall->getArg(i);
5947 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
5948 continue;
5949
5950 bool IsSwapped = ((i > 0) &&
5951 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
5952 IsSwapped |= ((i < (NumArgs - 1)) &&
5953 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
5954 if (IsSwapped) {
5955 // Warn on this floating-point to bool conversion.
5956 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
5957 CurrA->getType(), CC,
5958 diag::warn_impcast_floating_point_to_bool);
5959 }
5960 }
5961}
5962
John McCallcc7e5bf2010-05-06 08:58:33 +00005963void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00005964 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005965 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00005966
John McCallcc7e5bf2010-05-06 08:58:33 +00005967 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
5968 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
5969 if (Source == Target) return;
5970 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00005971
Chandler Carruthc22845a2011-07-26 05:40:03 +00005972 // If the conversion context location is invalid don't complain. We also
5973 // don't want to emit a warning if the issue occurs from the expansion of
5974 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
5975 // delay this check as long as possible. Once we detect we are in that
5976 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005977 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00005978 return;
5979
Richard Trieu021baa32011-09-23 20:10:00 +00005980 // Diagnose implicit casts to bool.
5981 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
5982 if (isa<StringLiteral>(E))
5983 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00005984 // and expressions, for instance, assert(0 && "error here"), are
5985 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00005986 return DiagnoseImpCast(S, E, T, CC,
5987 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00005988 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
5989 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
5990 // This covers the literal expressions that evaluate to Objective-C
5991 // objects.
5992 return DiagnoseImpCast(S, E, T, CC,
5993 diag::warn_impcast_objective_c_literal_to_bool);
5994 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00005995 if (Source->isPointerType() || Source->canDecayToPointerType()) {
5996 // Warn on pointer to bool conversion that is always true.
5997 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
5998 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00005999 }
Richard Trieu021baa32011-09-23 20:10:00 +00006000 }
John McCall263a48b2010-01-04 23:31:57 +00006001
6002 // Strip vector types.
6003 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006004 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006005 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006006 return;
John McCallacf0ee52010-10-08 02:01:28 +00006007 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006008 }
Chris Lattneree7286f2011-06-14 04:51:15 +00006009
6010 // If the vector cast is cast between two vectors of the same size, it is
6011 // a bitcast, not a conversion.
6012 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
6013 return;
John McCall263a48b2010-01-04 23:31:57 +00006014
6015 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
6016 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
6017 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00006018 if (auto VecTy = dyn_cast<VectorType>(Target))
6019 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00006020
6021 // Strip complex types.
6022 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006023 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006024 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006025 return;
6026
John McCallacf0ee52010-10-08 02:01:28 +00006027 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006028 }
John McCall263a48b2010-01-04 23:31:57 +00006029
6030 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
6031 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
6032 }
6033
6034 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
6035 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
6036
6037 // If the source is floating point...
6038 if (SourceBT && SourceBT->isFloatingPoint()) {
6039 // ...and the target is floating point...
6040 if (TargetBT && TargetBT->isFloatingPoint()) {
6041 // ...then warn if we're dropping FP rank.
6042
6043 // Builtin FP kinds are ordered by increasing FP rank.
6044 if (SourceBT->getKind() > TargetBT->getKind()) {
6045 // Don't warn about float constants that are precisely
6046 // representable in the target type.
6047 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00006048 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00006049 // Value might be a float, a float vector, or a float complex.
6050 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00006051 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
6052 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00006053 return;
6054 }
6055
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006056 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006057 return;
6058
John McCallacf0ee52010-10-08 02:01:28 +00006059 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall263a48b2010-01-04 23:31:57 +00006060 }
6061 return;
6062 }
6063
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006064 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00006065 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006066 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006067 return;
6068
Chandler Carruth22c7a792011-02-17 11:05:49 +00006069 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00006070 // We also want to warn on, e.g., "int i = -1.234"
6071 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
6072 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
6073 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
6074
Chandler Carruth016ef402011-04-10 08:36:24 +00006075 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
6076 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00006077 } else {
6078 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
6079 }
6080 }
John McCall263a48b2010-01-04 23:31:57 +00006081
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006082 // If the target is bool, warn if expr is a function or method call.
6083 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
6084 isa<CallExpr>(E)) {
6085 // Check last argument of function call to see if it is an
6086 // implicit cast from a type matching the type the result
6087 // is being cast to.
6088 CallExpr *CEx = cast<CallExpr>(E);
6089 unsigned NumArgs = CEx->getNumArgs();
6090 if (NumArgs > 0) {
6091 Expr *LastA = CEx->getArg(NumArgs - 1);
6092 Expr *InnerE = LastA->IgnoreParenImpCasts();
6093 const Type *InnerType =
6094 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6095 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
6096 // Warn on this floating-point to bool conversion
6097 DiagnoseImpCast(S, E, T, CC,
6098 diag::warn_impcast_floating_point_to_bool);
6099 }
6100 }
6101 }
John McCall263a48b2010-01-04 23:31:57 +00006102 return;
6103 }
6104
Richard Trieubeaf3452011-05-29 19:59:02 +00006105 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
David Blaikie9366d2b2012-06-19 21:19:06 +00006106 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
David Blaikiea1edff02012-11-08 00:41:20 +00006107 && !Target->isBlockPointerType() && !Target->isMemberPointerType()
David Blaikiebcd4b552013-02-16 00:56:22 +00006108 && Target->isScalarType() && !Target->isNullPtrType()) {
David Blaikieae12b182012-03-16 20:30:12 +00006109 SourceLocation Loc = E->getSourceRange().getBegin();
6110 if (Loc.isMacroID())
6111 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
David Blaikie18e9ac72012-05-15 21:57:38 +00006112 if (!Loc.isMacroID() || CC.isMacroID())
6113 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
6114 << T << clang::SourceRange(CC)
Richard Smithf7ec86a2013-09-20 00:27:40 +00006115 << FixItHint::CreateReplacement(Loc,
6116 S.getFixItZeroLiteralForType(T, Loc));
Richard Trieubeaf3452011-05-29 19:59:02 +00006117 }
6118
David Blaikie9366d2b2012-06-19 21:19:06 +00006119 if (!Source->isIntegerType() || !Target->isIntegerType())
6120 return;
6121
David Blaikie7555b6a2012-05-15 16:56:36 +00006122 // TODO: remove this early return once the false positives for constant->bool
6123 // in templates, macros, etc, are reduced or removed.
6124 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
6125 return;
6126
John McCallcc7e5bf2010-05-06 08:58:33 +00006127 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00006128 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00006129
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006130 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00006131 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006132 // TODO: this should happen for bitfield stores, too.
6133 llvm::APSInt Value(32);
6134 if (E->isIntegerConstantExpr(Value, S.Context)) {
6135 if (S.SourceMgr.isInSystemMacro(CC))
6136 return;
6137
John McCall18a2c2c2010-11-09 22:22:12 +00006138 std::string PrettySourceValue = Value.toString(10);
6139 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006140
Ted Kremenek33ba9952011-10-22 02:37:33 +00006141 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6142 S.PDiag(diag::warn_impcast_integer_precision_constant)
6143 << PrettySourceValue << PrettyTargetValue
6144 << E->getType() << T << E->getSourceRange()
6145 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00006146 return;
6147 }
6148
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006149 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
6150 if (S.SourceMgr.isInSystemMacro(CC))
6151 return;
6152
David Blaikie9455da02012-04-12 22:40:54 +00006153 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00006154 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
6155 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00006156 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00006157 }
6158
6159 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
6160 (!TargetRange.NonNegative && SourceRange.NonNegative &&
6161 SourceRange.Width == TargetRange.Width)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006162
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006163 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006164 return;
6165
John McCallcc7e5bf2010-05-06 08:58:33 +00006166 unsigned DiagID = diag::warn_impcast_integer_sign;
6167
6168 // Traditionally, gcc has warned about this under -Wsign-compare.
6169 // We also want to warn about it in -Wconversion.
6170 // So if -Wconversion is off, use a completely identical diagnostic
6171 // in the sign-compare group.
6172 // The conditional-checking code will
6173 if (ICContext) {
6174 DiagID = diag::warn_impcast_integer_sign_conditional;
6175 *ICContext = true;
6176 }
6177
John McCallacf0ee52010-10-08 02:01:28 +00006178 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00006179 }
6180
Douglas Gregora78f1932011-02-22 02:45:07 +00006181 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00006182 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
6183 // type, to give us better diagnostics.
6184 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00006185 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00006186 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6187 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
6188 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
6189 SourceType = S.Context.getTypeDeclType(Enum);
6190 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
6191 }
6192 }
6193
Douglas Gregora78f1932011-02-22 02:45:07 +00006194 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
6195 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00006196 if (SourceEnum->getDecl()->hasNameForLinkage() &&
6197 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006198 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006199 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006200 return;
6201
Douglas Gregor364f7db2011-03-12 00:14:31 +00006202 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00006203 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006204 }
Douglas Gregora78f1932011-02-22 02:45:07 +00006205
John McCall263a48b2010-01-04 23:31:57 +00006206 return;
6207}
6208
David Blaikie18e9ac72012-05-15 21:57:38 +00006209void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6210 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006211
6212void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00006213 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006214 E = E->IgnoreParenImpCasts();
6215
6216 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00006217 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006218
John McCallacf0ee52010-10-08 02:01:28 +00006219 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006220 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006221 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00006222 return;
6223}
6224
David Blaikie18e9ac72012-05-15 21:57:38 +00006225void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6226 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00006227 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00006228
6229 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00006230 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
6231 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006232
6233 // If -Wconversion would have warned about either of the candidates
6234 // for a signedness conversion to the context type...
6235 if (!Suspicious) return;
6236
6237 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006238 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00006239 return;
6240
John McCallcc7e5bf2010-05-06 08:58:33 +00006241 // ...then check whether it would have warned about either of the
6242 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00006243 if (E->getType() == T) return;
6244
6245 Suspicious = false;
6246 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
6247 E->getType(), CC, &Suspicious);
6248 if (!Suspicious)
6249 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00006250 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006251}
6252
6253/// AnalyzeImplicitConversions - Find and report any interesting
6254/// implicit conversions in the given expression. There are a couple
6255/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00006256void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00006257 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00006258 Expr *E = OrigE->IgnoreParenImpCasts();
6259
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00006260 if (E->isTypeDependent() || E->isValueDependent())
6261 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00006262
John McCallcc7e5bf2010-05-06 08:58:33 +00006263 // For conditional operators, we analyze the arguments as if they
6264 // were being fed directly into the output.
6265 if (isa<ConditionalOperator>(E)) {
6266 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00006267 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006268 return;
6269 }
6270
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006271 // Check implicit argument conversions for function calls.
6272 if (CallExpr *Call = dyn_cast<CallExpr>(E))
6273 CheckImplicitArgumentConversions(S, Call, CC);
6274
John McCallcc7e5bf2010-05-06 08:58:33 +00006275 // Go ahead and check any implicit conversions we might have skipped.
6276 // The non-canonical typecheck is just an optimization;
6277 // CheckImplicitConversion will filter out dead implicit conversions.
6278 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006279 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006280
6281 // Now continue drilling into this expression.
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006282
6283 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006284 if (POE->getResultExpr())
6285 E = POE->getResultExpr();
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006286 }
6287
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006288 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
6289 return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
6290
John McCallcc7e5bf2010-05-06 08:58:33 +00006291 // Skip past explicit casts.
6292 if (isa<ExplicitCastExpr>(E)) {
6293 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00006294 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006295 }
6296
John McCalld2a53122010-11-09 23:24:47 +00006297 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6298 // Do a somewhat different check with comparison operators.
6299 if (BO->isComparisonOp())
6300 return AnalyzeComparison(S, BO);
6301
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006302 // And with simple assignments.
6303 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00006304 return AnalyzeAssignment(S, BO);
6305 }
John McCallcc7e5bf2010-05-06 08:58:33 +00006306
6307 // These break the otherwise-useful invariant below. Fortunately,
6308 // we don't really need to recurse into them, because any internal
6309 // expressions should have been analyzed already when they were
6310 // built into statements.
6311 if (isa<StmtExpr>(E)) return;
6312
6313 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00006314 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00006315
6316 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00006317 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00006318 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00006319 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Richard Trieu021baa32011-09-23 20:10:00 +00006320 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor73456262012-02-09 10:18:50 +00006321 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00006322 if (!ChildExpr)
6323 continue;
6324
Richard Trieu955231d2014-01-25 01:10:35 +00006325 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00006326 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00006327 // Ignore checking string literals that are in logical and operators.
6328 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00006329 continue;
6330 AnalyzeImplicitConversions(S, ChildExpr, CC);
6331 }
John McCallcc7e5bf2010-05-06 08:58:33 +00006332}
6333
6334} // end anonymous namespace
6335
Richard Trieu3bb8b562014-02-26 02:36:06 +00006336enum {
6337 AddressOf,
6338 FunctionPointer,
6339 ArrayPointer
6340};
6341
Richard Trieuc1888e02014-06-28 23:25:37 +00006342// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
6343// Returns true when emitting a warning about taking the address of a reference.
6344static bool CheckForReference(Sema &SemaRef, const Expr *E,
6345 PartialDiagnostic PD) {
6346 E = E->IgnoreParenImpCasts();
6347
6348 const FunctionDecl *FD = nullptr;
6349
6350 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
6351 if (!DRE->getDecl()->getType()->isReferenceType())
6352 return false;
6353 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6354 if (!M->getMemberDecl()->getType()->isReferenceType())
6355 return false;
6356 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
6357 if (!Call->getCallReturnType()->isReferenceType())
6358 return false;
6359 FD = Call->getDirectCallee();
6360 } else {
6361 return false;
6362 }
6363
6364 SemaRef.Diag(E->getExprLoc(), PD);
6365
6366 // If possible, point to location of function.
6367 if (FD) {
6368 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
6369 }
6370
6371 return true;
6372}
6373
Richard Trieu4cbff5c2014-08-08 22:41:43 +00006374// Returns true if the SourceLocation is expanded from any macro body.
6375// Returns false if the SourceLocation is invalid, is from not in a macro
6376// expansion, or is from expanded from a top-level macro argument.
6377static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
6378 if (Loc.isInvalid())
6379 return false;
6380
6381 while (Loc.isMacroID()) {
6382 if (SM.isMacroBodyExpansion(Loc))
6383 return true;
6384 Loc = SM.getImmediateMacroCallerLoc(Loc);
6385 }
6386
6387 return false;
6388}
6389
Richard Trieu3bb8b562014-02-26 02:36:06 +00006390/// \brief Diagnose pointers that are always non-null.
6391/// \param E the expression containing the pointer
6392/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
6393/// compared to a null pointer
6394/// \param IsEqual True when the comparison is equal to a null pointer
6395/// \param Range Extra SourceRange to highlight in the diagnostic
6396void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
6397 Expr::NullPointerConstantKind NullKind,
6398 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00006399 if (!E)
6400 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006401
6402 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00006403 if (E->getExprLoc().isMacroID()) {
6404 const SourceManager &SM = getSourceManager();
6405 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
6406 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00006407 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00006408 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00006409 E = E->IgnoreImpCasts();
6410
6411 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
6412
Richard Trieuf7432752014-06-06 21:39:26 +00006413 if (isa<CXXThisExpr>(E)) {
6414 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
6415 : diag::warn_this_bool_conversion;
6416 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
6417 return;
6418 }
6419
Richard Trieu3bb8b562014-02-26 02:36:06 +00006420 bool IsAddressOf = false;
6421
6422 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6423 if (UO->getOpcode() != UO_AddrOf)
6424 return;
6425 IsAddressOf = true;
6426 E = UO->getSubExpr();
6427 }
6428
Richard Trieuc1888e02014-06-28 23:25:37 +00006429 if (IsAddressOf) {
6430 unsigned DiagID = IsCompare
6431 ? diag::warn_address_of_reference_null_compare
6432 : diag::warn_address_of_reference_bool_conversion;
6433 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
6434 << IsEqual;
6435 if (CheckForReference(*this, E, PD)) {
6436 return;
6437 }
6438 }
6439
Richard Trieu3bb8b562014-02-26 02:36:06 +00006440 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00006441 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006442 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
6443 D = R->getDecl();
6444 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6445 D = M->getMemberDecl();
6446 }
6447
6448 // Weak Decls can be null.
6449 if (!D || D->isWeak())
6450 return;
6451
6452 QualType T = D->getType();
6453 const bool IsArray = T->isArrayType();
6454 const bool IsFunction = T->isFunctionType();
6455
Richard Trieuc1888e02014-06-28 23:25:37 +00006456 // Address of function is used to silence the function warning.
6457 if (IsAddressOf && IsFunction) {
6458 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006459 }
6460
6461 // Found nothing.
6462 if (!IsAddressOf && !IsFunction && !IsArray)
6463 return;
6464
6465 // Pretty print the expression for the diagnostic.
6466 std::string Str;
6467 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00006468 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00006469
6470 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
6471 : diag::warn_impcast_pointer_to_bool;
6472 unsigned DiagType;
6473 if (IsAddressOf)
6474 DiagType = AddressOf;
6475 else if (IsFunction)
6476 DiagType = FunctionPointer;
6477 else if (IsArray)
6478 DiagType = ArrayPointer;
6479 else
6480 llvm_unreachable("Could not determine diagnostic.");
6481 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
6482 << Range << IsEqual;
6483
6484 if (!IsFunction)
6485 return;
6486
6487 // Suggest '&' to silence the function warning.
6488 Diag(E->getExprLoc(), diag::note_function_warning_silence)
6489 << FixItHint::CreateInsertion(E->getLocStart(), "&");
6490
6491 // Check to see if '()' fixit should be emitted.
6492 QualType ReturnType;
6493 UnresolvedSet<4> NonTemplateOverloads;
6494 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
6495 if (ReturnType.isNull())
6496 return;
6497
6498 if (IsCompare) {
6499 // There are two cases here. If there is null constant, the only suggest
6500 // for a pointer return type. If the null is 0, then suggest if the return
6501 // type is a pointer or an integer type.
6502 if (!ReturnType->isPointerType()) {
6503 if (NullKind == Expr::NPCK_ZeroExpression ||
6504 NullKind == Expr::NPCK_ZeroLiteral) {
6505 if (!ReturnType->isIntegerType())
6506 return;
6507 } else {
6508 return;
6509 }
6510 }
6511 } else { // !IsCompare
6512 // For function to bool, only suggest if the function pointer has bool
6513 // return type.
6514 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
6515 return;
6516 }
6517 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00006518 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00006519}
6520
6521
John McCallcc7e5bf2010-05-06 08:58:33 +00006522/// Diagnoses "dangerous" implicit conversions within the given
6523/// expression (which is a full expression). Implements -Wconversion
6524/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00006525///
6526/// \param CC the "context" location of the implicit conversion, i.e.
6527/// the most location of the syntactic entity requiring the implicit
6528/// conversion
6529void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006530 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00006531 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00006532 return;
6533
6534 // Don't diagnose for value- or type-dependent expressions.
6535 if (E->isTypeDependent() || E->isValueDependent())
6536 return;
6537
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006538 // Check for array bounds violations in cases where the check isn't triggered
6539 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
6540 // ArraySubscriptExpr is on the RHS of a variable initialization.
6541 CheckArrayAccess(E);
6542
John McCallacf0ee52010-10-08 02:01:28 +00006543 // This is not the right CC for (e.g.) a variable initialization.
6544 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006545}
6546
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006547/// Diagnose when expression is an integer constant expression and its evaluation
6548/// results in integer overflow
6549void Sema::CheckForIntOverflow (Expr *E) {
Richard Smithe9ff7702013-11-05 22:23:30 +00006550 if (isa<BinaryOperator>(E->IgnoreParens()))
6551 E->EvaluateForOverflow(Context);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006552}
6553
Richard Smithc406cb72013-01-17 01:17:56 +00006554namespace {
6555/// \brief Visitor for expressions which looks for unsequenced operations on the
6556/// same object.
6557class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00006558 typedef EvaluatedExprVisitor<SequenceChecker> Base;
6559
Richard Smithc406cb72013-01-17 01:17:56 +00006560 /// \brief A tree of sequenced regions within an expression. Two regions are
6561 /// unsequenced if one is an ancestor or a descendent of the other. When we
6562 /// finish processing an expression with sequencing, such as a comma
6563 /// expression, we fold its tree nodes into its parent, since they are
6564 /// unsequenced with respect to nodes we will visit later.
6565 class SequenceTree {
6566 struct Value {
6567 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
6568 unsigned Parent : 31;
6569 bool Merged : 1;
6570 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006571 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00006572
6573 public:
6574 /// \brief A region within an expression which may be sequenced with respect
6575 /// to some other region.
6576 class Seq {
6577 explicit Seq(unsigned N) : Index(N) {}
6578 unsigned Index;
6579 friend class SequenceTree;
6580 public:
6581 Seq() : Index(0) {}
6582 };
6583
6584 SequenceTree() { Values.push_back(Value(0)); }
6585 Seq root() const { return Seq(0); }
6586
6587 /// \brief Create a new sequence of operations, which is an unsequenced
6588 /// subset of \p Parent. This sequence of operations is sequenced with
6589 /// respect to other children of \p Parent.
6590 Seq allocate(Seq Parent) {
6591 Values.push_back(Value(Parent.Index));
6592 return Seq(Values.size() - 1);
6593 }
6594
6595 /// \brief Merge a sequence of operations into its parent.
6596 void merge(Seq S) {
6597 Values[S.Index].Merged = true;
6598 }
6599
6600 /// \brief Determine whether two operations are unsequenced. This operation
6601 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
6602 /// should have been merged into its parent as appropriate.
6603 bool isUnsequenced(Seq Cur, Seq Old) {
6604 unsigned C = representative(Cur.Index);
6605 unsigned Target = representative(Old.Index);
6606 while (C >= Target) {
6607 if (C == Target)
6608 return true;
6609 C = Values[C].Parent;
6610 }
6611 return false;
6612 }
6613
6614 private:
6615 /// \brief Pick a representative for a sequence.
6616 unsigned representative(unsigned K) {
6617 if (Values[K].Merged)
6618 // Perform path compression as we go.
6619 return Values[K].Parent = representative(Values[K].Parent);
6620 return K;
6621 }
6622 };
6623
6624 /// An object for which we can track unsequenced uses.
6625 typedef NamedDecl *Object;
6626
6627 /// Different flavors of object usage which we track. We only track the
6628 /// least-sequenced usage of each kind.
6629 enum UsageKind {
6630 /// A read of an object. Multiple unsequenced reads are OK.
6631 UK_Use,
6632 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00006633 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00006634 UK_ModAsValue,
6635 /// A modification of an object which is not sequenced before the value
6636 /// computation of the expression, such as n++.
6637 UK_ModAsSideEffect,
6638
6639 UK_Count = UK_ModAsSideEffect + 1
6640 };
6641
6642 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00006643 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00006644 Expr *Use;
6645 SequenceTree::Seq Seq;
6646 };
6647
6648 struct UsageInfo {
6649 UsageInfo() : Diagnosed(false) {}
6650 Usage Uses[UK_Count];
6651 /// Have we issued a diagnostic for this variable already?
6652 bool Diagnosed;
6653 };
6654 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
6655
6656 Sema &SemaRef;
6657 /// Sequenced regions within the expression.
6658 SequenceTree Tree;
6659 /// Declaration modifications and references which we have seen.
6660 UsageInfoMap UsageMap;
6661 /// The region we are currently within.
6662 SequenceTree::Seq Region;
6663 /// Filled in with declarations which were modified as a side-effect
6664 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006665 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00006666 /// Expressions to check later. We defer checking these to reduce
6667 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006668 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00006669
6670 /// RAII object wrapping the visitation of a sequenced subexpression of an
6671 /// expression. At the end of this process, the side-effects of the evaluation
6672 /// become sequenced with respect to the value computation of the result, so
6673 /// we downgrade any UK_ModAsSideEffect within the evaluation to
6674 /// UK_ModAsValue.
6675 struct SequencedSubexpression {
6676 SequencedSubexpression(SequenceChecker &Self)
6677 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
6678 Self.ModAsSideEffect = &ModAsSideEffect;
6679 }
6680 ~SequencedSubexpression() {
6681 for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) {
6682 UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first];
6683 U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second;
6684 Self.addUsage(U, ModAsSideEffect[I].first,
6685 ModAsSideEffect[I].second.Use, UK_ModAsValue);
6686 }
6687 Self.ModAsSideEffect = OldModAsSideEffect;
6688 }
6689
6690 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006691 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
6692 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00006693 };
6694
Richard Smith40238f02013-06-20 22:21:56 +00006695 /// RAII object wrapping the visitation of a subexpression which we might
6696 /// choose to evaluate as a constant. If any subexpression is evaluated and
6697 /// found to be non-constant, this allows us to suppress the evaluation of
6698 /// the outer expression.
6699 class EvaluationTracker {
6700 public:
6701 EvaluationTracker(SequenceChecker &Self)
6702 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
6703 Self.EvalTracker = this;
6704 }
6705 ~EvaluationTracker() {
6706 Self.EvalTracker = Prev;
6707 if (Prev)
6708 Prev->EvalOK &= EvalOK;
6709 }
6710
6711 bool evaluate(const Expr *E, bool &Result) {
6712 if (!EvalOK || E->isValueDependent())
6713 return false;
6714 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
6715 return EvalOK;
6716 }
6717
6718 private:
6719 SequenceChecker &Self;
6720 EvaluationTracker *Prev;
6721 bool EvalOK;
6722 } *EvalTracker;
6723
Richard Smithc406cb72013-01-17 01:17:56 +00006724 /// \brief Find the object which is produced by the specified expression,
6725 /// if any.
6726 Object getObject(Expr *E, bool Mod) const {
6727 E = E->IgnoreParenCasts();
6728 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6729 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
6730 return getObject(UO->getSubExpr(), Mod);
6731 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6732 if (BO->getOpcode() == BO_Comma)
6733 return getObject(BO->getRHS(), Mod);
6734 if (Mod && BO->isAssignmentOp())
6735 return getObject(BO->getLHS(), Mod);
6736 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
6737 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
6738 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
6739 return ME->getMemberDecl();
6740 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6741 // FIXME: If this is a reference, map through to its value.
6742 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00006743 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00006744 }
6745
6746 /// \brief Note that an object was modified or used by an expression.
6747 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
6748 Usage &U = UI.Uses[UK];
6749 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
6750 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
6751 ModAsSideEffect->push_back(std::make_pair(O, U));
6752 U.Use = Ref;
6753 U.Seq = Region;
6754 }
6755 }
6756 /// \brief Check whether a modification or use conflicts with a prior usage.
6757 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
6758 bool IsModMod) {
6759 if (UI.Diagnosed)
6760 return;
6761
6762 const Usage &U = UI.Uses[OtherKind];
6763 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
6764 return;
6765
6766 Expr *Mod = U.Use;
6767 Expr *ModOrUse = Ref;
6768 if (OtherKind == UK_Use)
6769 std::swap(Mod, ModOrUse);
6770
6771 SemaRef.Diag(Mod->getExprLoc(),
6772 IsModMod ? diag::warn_unsequenced_mod_mod
6773 : diag::warn_unsequenced_mod_use)
6774 << O << SourceRange(ModOrUse->getExprLoc());
6775 UI.Diagnosed = true;
6776 }
6777
6778 void notePreUse(Object O, Expr *Use) {
6779 UsageInfo &U = UsageMap[O];
6780 // Uses conflict with other modifications.
6781 checkUsage(O, U, Use, UK_ModAsValue, false);
6782 }
6783 void notePostUse(Object O, Expr *Use) {
6784 UsageInfo &U = UsageMap[O];
6785 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
6786 addUsage(U, O, Use, UK_Use);
6787 }
6788
6789 void notePreMod(Object O, Expr *Mod) {
6790 UsageInfo &U = UsageMap[O];
6791 // Modifications conflict with other modifications and with uses.
6792 checkUsage(O, U, Mod, UK_ModAsValue, true);
6793 checkUsage(O, U, Mod, UK_Use, false);
6794 }
6795 void notePostMod(Object O, Expr *Use, UsageKind UK) {
6796 UsageInfo &U = UsageMap[O];
6797 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
6798 addUsage(U, O, Use, UK);
6799 }
6800
6801public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006802 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00006803 : Base(S.Context), SemaRef(S), Region(Tree.root()),
6804 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00006805 Visit(E);
6806 }
6807
6808 void VisitStmt(Stmt *S) {
6809 // Skip all statements which aren't expressions for now.
6810 }
6811
6812 void VisitExpr(Expr *E) {
6813 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00006814 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00006815 }
6816
6817 void VisitCastExpr(CastExpr *E) {
6818 Object O = Object();
6819 if (E->getCastKind() == CK_LValueToRValue)
6820 O = getObject(E->getSubExpr(), false);
6821
6822 if (O)
6823 notePreUse(O, E);
6824 VisitExpr(E);
6825 if (O)
6826 notePostUse(O, E);
6827 }
6828
6829 void VisitBinComma(BinaryOperator *BO) {
6830 // C++11 [expr.comma]p1:
6831 // Every value computation and side effect associated with the left
6832 // expression is sequenced before every value computation and side
6833 // effect associated with the right expression.
6834 SequenceTree::Seq LHS = Tree.allocate(Region);
6835 SequenceTree::Seq RHS = Tree.allocate(Region);
6836 SequenceTree::Seq OldRegion = Region;
6837
6838 {
6839 SequencedSubexpression SeqLHS(*this);
6840 Region = LHS;
6841 Visit(BO->getLHS());
6842 }
6843
6844 Region = RHS;
6845 Visit(BO->getRHS());
6846
6847 Region = OldRegion;
6848
6849 // Forget that LHS and RHS are sequenced. They are both unsequenced
6850 // with respect to other stuff.
6851 Tree.merge(LHS);
6852 Tree.merge(RHS);
6853 }
6854
6855 void VisitBinAssign(BinaryOperator *BO) {
6856 // The modification is sequenced after the value computation of the LHS
6857 // and RHS, so check it before inspecting the operands and update the
6858 // map afterwards.
6859 Object O = getObject(BO->getLHS(), true);
6860 if (!O)
6861 return VisitExpr(BO);
6862
6863 notePreMod(O, BO);
6864
6865 // C++11 [expr.ass]p7:
6866 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
6867 // only once.
6868 //
6869 // Therefore, for a compound assignment operator, O is considered used
6870 // everywhere except within the evaluation of E1 itself.
6871 if (isa<CompoundAssignOperator>(BO))
6872 notePreUse(O, BO);
6873
6874 Visit(BO->getLHS());
6875
6876 if (isa<CompoundAssignOperator>(BO))
6877 notePostUse(O, BO);
6878
6879 Visit(BO->getRHS());
6880
Richard Smith83e37bee2013-06-26 23:16:51 +00006881 // C++11 [expr.ass]p1:
6882 // the assignment is sequenced [...] before the value computation of the
6883 // assignment expression.
6884 // C11 6.5.16/3 has no such rule.
6885 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6886 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00006887 }
6888 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
6889 VisitBinAssign(CAO);
6890 }
6891
6892 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
6893 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
6894 void VisitUnaryPreIncDec(UnaryOperator *UO) {
6895 Object O = getObject(UO->getSubExpr(), true);
6896 if (!O)
6897 return VisitExpr(UO);
6898
6899 notePreMod(O, UO);
6900 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00006901 // C++11 [expr.pre.incr]p1:
6902 // the expression ++x is equivalent to x+=1
6903 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6904 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00006905 }
6906
6907 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
6908 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
6909 void VisitUnaryPostIncDec(UnaryOperator *UO) {
6910 Object O = getObject(UO->getSubExpr(), true);
6911 if (!O)
6912 return VisitExpr(UO);
6913
6914 notePreMod(O, UO);
6915 Visit(UO->getSubExpr());
6916 notePostMod(O, UO, UK_ModAsSideEffect);
6917 }
6918
6919 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
6920 void VisitBinLOr(BinaryOperator *BO) {
6921 // The side-effects of the LHS of an '&&' are sequenced before the
6922 // value computation of the RHS, and hence before the value computation
6923 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
6924 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00006925 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00006926 {
6927 SequencedSubexpression Sequenced(*this);
6928 Visit(BO->getLHS());
6929 }
6930
6931 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006932 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00006933 if (!Result)
6934 Visit(BO->getRHS());
6935 } else {
6936 // Check for unsequenced operations in the RHS, treating it as an
6937 // entirely separate evaluation.
6938 //
6939 // FIXME: If there are operations in the RHS which are unsequenced
6940 // with respect to operations outside the RHS, and those operations
6941 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00006942 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00006943 }
Richard Smithc406cb72013-01-17 01:17:56 +00006944 }
6945 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00006946 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00006947 {
6948 SequencedSubexpression Sequenced(*this);
6949 Visit(BO->getLHS());
6950 }
6951
6952 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006953 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00006954 if (Result)
6955 Visit(BO->getRHS());
6956 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00006957 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00006958 }
Richard Smithc406cb72013-01-17 01:17:56 +00006959 }
6960
6961 // Only visit the condition, unless we can be sure which subexpression will
6962 // be chosen.
6963 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00006964 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00006965 {
6966 SequencedSubexpression Sequenced(*this);
6967 Visit(CO->getCond());
6968 }
Richard Smithc406cb72013-01-17 01:17:56 +00006969
6970 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006971 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00006972 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00006973 else {
Richard Smithd33f5202013-01-17 23:18:09 +00006974 WorkList.push_back(CO->getTrueExpr());
6975 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00006976 }
Richard Smithc406cb72013-01-17 01:17:56 +00006977 }
6978
Richard Smithe3dbfe02013-06-30 10:40:20 +00006979 void VisitCallExpr(CallExpr *CE) {
6980 // C++11 [intro.execution]p15:
6981 // When calling a function [...], every value computation and side effect
6982 // associated with any argument expression, or with the postfix expression
6983 // designating the called function, is sequenced before execution of every
6984 // expression or statement in the body of the function [and thus before
6985 // the value computation of its result].
6986 SequencedSubexpression Sequenced(*this);
6987 Base::VisitCallExpr(CE);
6988
6989 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
6990 }
6991
Richard Smithc406cb72013-01-17 01:17:56 +00006992 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00006993 // This is a call, so all subexpressions are sequenced before the result.
6994 SequencedSubexpression Sequenced(*this);
6995
Richard Smithc406cb72013-01-17 01:17:56 +00006996 if (!CCE->isListInitialization())
6997 return VisitExpr(CCE);
6998
6999 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007000 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00007001 SequenceTree::Seq Parent = Region;
7002 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
7003 E = CCE->arg_end();
7004 I != E; ++I) {
7005 Region = Tree.allocate(Parent);
7006 Elts.push_back(Region);
7007 Visit(*I);
7008 }
7009
7010 // Forget that the initializers are sequenced.
7011 Region = Parent;
7012 for (unsigned I = 0; I < Elts.size(); ++I)
7013 Tree.merge(Elts[I]);
7014 }
7015
7016 void VisitInitListExpr(InitListExpr *ILE) {
7017 if (!SemaRef.getLangOpts().CPlusPlus11)
7018 return VisitExpr(ILE);
7019
7020 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007021 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00007022 SequenceTree::Seq Parent = Region;
7023 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
7024 Expr *E = ILE->getInit(I);
7025 if (!E) continue;
7026 Region = Tree.allocate(Parent);
7027 Elts.push_back(Region);
7028 Visit(E);
7029 }
7030
7031 // Forget that the initializers are sequenced.
7032 Region = Parent;
7033 for (unsigned I = 0; I < Elts.size(); ++I)
7034 Tree.merge(Elts[I]);
7035 }
7036};
7037}
7038
7039void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007040 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00007041 WorkList.push_back(E);
7042 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00007043 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00007044 SequenceChecker(*this, Item, WorkList);
7045 }
Richard Smithc406cb72013-01-17 01:17:56 +00007046}
7047
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007048void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
7049 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00007050 CheckImplicitConversions(E, CheckLoc);
7051 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007052 if (!IsConstexpr && !E->isValueDependent())
7053 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00007054}
7055
John McCall1f425642010-11-11 03:21:53 +00007056void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
7057 FieldDecl *BitField,
7058 Expr *Init) {
7059 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
7060}
7061
Mike Stump0c2ec772010-01-21 03:59:47 +00007062/// CheckParmsForFunctionDef - Check that the parameters of the given
7063/// function are appropriate for the definition of a function. This
7064/// takes care of any checks that cannot be performed on the
7065/// declaration itself, e.g., that the types of each of the function
7066/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00007067bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
7068 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00007069 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00007070 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00007071 for (; P != PEnd; ++P) {
7072 ParmVarDecl *Param = *P;
7073
Mike Stump0c2ec772010-01-21 03:59:47 +00007074 // C99 6.7.5.3p4: the parameters in a parameter type list in a
7075 // function declarator that is part of a function definition of
7076 // that function shall not have incomplete type.
7077 //
7078 // This is also C++ [dcl.fct]p6.
7079 if (!Param->isInvalidDecl() &&
7080 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00007081 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00007082 Param->setInvalidDecl();
7083 HasInvalidParm = true;
7084 }
7085
7086 // C99 6.9.1p5: If the declarator includes a parameter type list, the
7087 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00007088 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00007089 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00007090 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00007091 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00007092 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00007093
7094 // C99 6.7.5.3p12:
7095 // If the function declarator is not part of a definition of that
7096 // function, parameters may have incomplete type and may use the [*]
7097 // notation in their sequences of declarator specifiers to specify
7098 // variable length array types.
7099 QualType PType = Param->getOriginalType();
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007100 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigdeb55d52010-02-01 05:02:49 +00007101 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitb3318502013-03-01 21:41:22 +00007102 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigdeb55d52010-02-01 05:02:49 +00007103 // information is added for it.
7104 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007105 break;
Sam Weinigdeb55d52010-02-01 05:02:49 +00007106 }
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007107 PType= AT->getElementType();
Sam Weinigdeb55d52010-02-01 05:02:49 +00007108 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00007109
7110 // MSVC destroys objects passed by value in the callee. Therefore a
7111 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00007112 // object's destructor. However, we don't perform any direct access check
7113 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00007114 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
7115 .getCXXABI()
7116 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00007117 if (!Param->isInvalidDecl()) {
7118 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
7119 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
7120 if (!ClassDecl->isInvalidDecl() &&
7121 !ClassDecl->hasIrrelevantDestructor() &&
7122 !ClassDecl->isDependentContext()) {
7123 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
7124 MarkFunctionReferenced(Param->getLocation(), Destructor);
7125 DiagnoseUseOfDecl(Destructor, Param->getLocation());
7126 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00007127 }
7128 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00007129 }
Mike Stump0c2ec772010-01-21 03:59:47 +00007130 }
7131
7132 return HasInvalidParm;
7133}
John McCall2b5c1b22010-08-12 21:44:57 +00007134
7135/// CheckCastAlign - Implements -Wcast-align, which warns when a
7136/// pointer cast increases the alignment requirements.
7137void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
7138 // This is actually a lot of work to potentially be doing on every
7139 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007140 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00007141 return;
7142
7143 // Ignore dependent types.
7144 if (T->isDependentType() || Op->getType()->isDependentType())
7145 return;
7146
7147 // Require that the destination be a pointer type.
7148 const PointerType *DestPtr = T->getAs<PointerType>();
7149 if (!DestPtr) return;
7150
7151 // If the destination has alignment 1, we're done.
7152 QualType DestPointee = DestPtr->getPointeeType();
7153 if (DestPointee->isIncompleteType()) return;
7154 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
7155 if (DestAlign.isOne()) return;
7156
7157 // Require that the source be a pointer type.
7158 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
7159 if (!SrcPtr) return;
7160 QualType SrcPointee = SrcPtr->getPointeeType();
7161
7162 // Whitelist casts from cv void*. We already implicitly
7163 // whitelisted casts to cv void*, since they have alignment 1.
7164 // Also whitelist casts involving incomplete types, which implicitly
7165 // includes 'void'.
7166 if (SrcPointee->isIncompleteType()) return;
7167
7168 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
7169 if (SrcAlign >= DestAlign) return;
7170
7171 Diag(TRange.getBegin(), diag::warn_cast_align)
7172 << Op->getType() << T
7173 << static_cast<unsigned>(SrcAlign.getQuantity())
7174 << static_cast<unsigned>(DestAlign.getQuantity())
7175 << TRange << Op->getSourceRange();
7176}
7177
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007178static const Type* getElementType(const Expr *BaseExpr) {
7179 const Type* EltType = BaseExpr->getType().getTypePtr();
7180 if (EltType->isAnyPointerType())
7181 return EltType->getPointeeType().getTypePtr();
7182 else if (EltType->isArrayType())
7183 return EltType->getBaseElementTypeUnsafe();
7184 return EltType;
7185}
7186
Chandler Carruth28389f02011-08-05 09:10:50 +00007187/// \brief Check whether this array fits the idiom of a size-one tail padded
7188/// array member of a struct.
7189///
7190/// We avoid emitting out-of-bounds access warnings for such arrays as they are
7191/// commonly used to emulate flexible arrays in C89 code.
7192static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
7193 const NamedDecl *ND) {
7194 if (Size != 1 || !ND) return false;
7195
7196 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
7197 if (!FD) return false;
7198
7199 // Don't consider sizes resulting from macro expansions or template argument
7200 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00007201
7202 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007203 while (TInfo) {
7204 TypeLoc TL = TInfo->getTypeLoc();
7205 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00007206 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
7207 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007208 TInfo = TDL->getTypeSourceInfo();
7209 continue;
7210 }
David Blaikie6adc78e2013-02-18 22:06:02 +00007211 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
7212 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00007213 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
7214 return false;
7215 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007216 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00007217 }
Chandler Carruth28389f02011-08-05 09:10:50 +00007218
7219 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00007220 if (!RD) return false;
7221 if (RD->isUnion()) return false;
7222 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
7223 if (!CRD->isStandardLayout()) return false;
7224 }
Chandler Carruth28389f02011-08-05 09:10:50 +00007225
Benjamin Kramer8c543672011-08-06 03:04:42 +00007226 // See if this is the last field decl in the record.
7227 const Decl *D = FD;
7228 while ((D = D->getNextDeclInContext()))
7229 if (isa<FieldDecl>(D))
7230 return false;
7231 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00007232}
7233
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007234void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007235 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00007236 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007237 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007238 if (IndexExpr->isValueDependent())
7239 return;
7240
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00007241 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007242 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007243 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007244 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007245 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00007246 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00007247
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007248 llvm::APSInt index;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007249 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremenek64699be2011-02-16 01:57:07 +00007250 return;
Richard Smith13f67182011-12-16 19:31:14 +00007251 if (IndexNegated)
7252 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00007253
Craig Topperc3ec1492014-05-26 06:22:03 +00007254 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00007255 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7256 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00007257 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00007258 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00007259
Ted Kremeneke4b316c2011-02-23 23:06:04 +00007260 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007261 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00007262 if (!size.isStrictlyPositive())
7263 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007264
7265 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00007266 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007267 // Make sure we're comparing apples to apples when comparing index to size
7268 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
7269 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00007270 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00007271 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007272 if (ptrarith_typesize != array_typesize) {
7273 // There's a cast to a different size type involved
7274 uint64_t ratio = array_typesize / ptrarith_typesize;
7275 // TODO: Be smarter about handling cases where array_typesize is not a
7276 // multiple of ptrarith_typesize
7277 if (ptrarith_typesize * ratio == array_typesize)
7278 size *= llvm::APInt(size.getBitWidth(), ratio);
7279 }
7280 }
7281
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007282 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007283 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007284 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007285 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007286
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007287 // For array subscripting the index must be less than size, but for pointer
7288 // arithmetic also allow the index (offset) to be equal to size since
7289 // computing the next address after the end of the array is legal and
7290 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007291 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00007292 return;
7293
7294 // Also don't warn for arrays of size 1 which are members of some
7295 // structure. These are often used to approximate flexible arrays in C89
7296 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007297 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00007298 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007299
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007300 // Suppress the warning if the subscript expression (as identified by the
7301 // ']' location) and the index expression are both from macro expansions
7302 // within a system header.
7303 if (ASE) {
7304 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
7305 ASE->getRBracketLoc());
7306 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
7307 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
7308 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00007309 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007310 return;
7311 }
7312 }
7313
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007314 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007315 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007316 DiagID = diag::warn_array_index_exceeds_bounds;
7317
7318 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7319 PDiag(DiagID) << index.toString(10, true)
7320 << size.toString(10, true)
7321 << (unsigned)size.getLimitedValue(~0U)
7322 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007323 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007324 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007325 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007326 DiagID = diag::warn_ptr_arith_precedes_bounds;
7327 if (index.isNegative()) index = -index;
7328 }
7329
7330 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7331 PDiag(DiagID) << index.toString(10, true)
7332 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00007333 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00007334
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00007335 if (!ND) {
7336 // Try harder to find a NamedDecl to point at in the note.
7337 while (const ArraySubscriptExpr *ASE =
7338 dyn_cast<ArraySubscriptExpr>(BaseExpr))
7339 BaseExpr = ASE->getBase()->IgnoreParenCasts();
7340 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7341 ND = dyn_cast<NamedDecl>(DRE->getDecl());
7342 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
7343 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
7344 }
7345
Chandler Carruth1af88f12011-02-17 21:10:52 +00007346 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007347 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
7348 PDiag(diag::note_array_index_out_of_bounds)
7349 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00007350}
7351
Ted Kremenekdf26df72011-03-01 18:41:00 +00007352void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007353 int AllowOnePastEnd = 0;
7354 while (expr) {
7355 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00007356 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007357 case Stmt::ArraySubscriptExprClass: {
7358 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007359 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007360 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00007361 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007362 }
7363 case Stmt::UnaryOperatorClass: {
7364 // Only unwrap the * and & unary operators
7365 const UnaryOperator *UO = cast<UnaryOperator>(expr);
7366 expr = UO->getSubExpr();
7367 switch (UO->getOpcode()) {
7368 case UO_AddrOf:
7369 AllowOnePastEnd++;
7370 break;
7371 case UO_Deref:
7372 AllowOnePastEnd--;
7373 break;
7374 default:
7375 return;
7376 }
7377 break;
7378 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007379 case Stmt::ConditionalOperatorClass: {
7380 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
7381 if (const Expr *lhs = cond->getLHS())
7382 CheckArrayAccess(lhs);
7383 if (const Expr *rhs = cond->getRHS())
7384 CheckArrayAccess(rhs);
7385 return;
7386 }
7387 default:
7388 return;
7389 }
Peter Collingbourne91147592011-04-15 00:35:48 +00007390 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007391}
John McCall31168b02011-06-15 23:02:42 +00007392
7393//===--- CHECK: Objective-C retain cycles ----------------------------------//
7394
7395namespace {
7396 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00007397 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00007398 VarDecl *Variable;
7399 SourceRange Range;
7400 SourceLocation Loc;
7401 bool Indirect;
7402
7403 void setLocsFrom(Expr *e) {
7404 Loc = e->getExprLoc();
7405 Range = e->getSourceRange();
7406 }
7407 };
7408}
7409
7410/// Consider whether capturing the given variable can possibly lead to
7411/// a retain cycle.
7412static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00007413 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00007414 // lifetime. In MRR, it's captured strongly if the variable is
7415 // __block and has an appropriate type.
7416 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7417 return false;
7418
7419 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007420 if (ref)
7421 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00007422 return true;
7423}
7424
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007425static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00007426 while (true) {
7427 e = e->IgnoreParens();
7428 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
7429 switch (cast->getCastKind()) {
7430 case CK_BitCast:
7431 case CK_LValueBitCast:
7432 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00007433 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00007434 e = cast->getSubExpr();
7435 continue;
7436
John McCall31168b02011-06-15 23:02:42 +00007437 default:
7438 return false;
7439 }
7440 }
7441
7442 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
7443 ObjCIvarDecl *ivar = ref->getDecl();
7444 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7445 return false;
7446
7447 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007448 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00007449 return false;
7450
7451 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
7452 owner.Indirect = true;
7453 return true;
7454 }
7455
7456 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
7457 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
7458 if (!var) return false;
7459 return considerVariable(var, ref, owner);
7460 }
7461
John McCall31168b02011-06-15 23:02:42 +00007462 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
7463 if (member->isArrow()) return false;
7464
7465 // Don't count this as an indirect ownership.
7466 e = member->getBase();
7467 continue;
7468 }
7469
John McCallfe96e0b2011-11-06 09:01:30 +00007470 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
7471 // Only pay attention to pseudo-objects on property references.
7472 ObjCPropertyRefExpr *pre
7473 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
7474 ->IgnoreParens());
7475 if (!pre) return false;
7476 if (pre->isImplicitProperty()) return false;
7477 ObjCPropertyDecl *property = pre->getExplicitProperty();
7478 if (!property->isRetaining() &&
7479 !(property->getPropertyIvarDecl() &&
7480 property->getPropertyIvarDecl()->getType()
7481 .getObjCLifetime() == Qualifiers::OCL_Strong))
7482 return false;
7483
7484 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007485 if (pre->isSuperReceiver()) {
7486 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
7487 if (!owner.Variable)
7488 return false;
7489 owner.Loc = pre->getLocation();
7490 owner.Range = pre->getSourceRange();
7491 return true;
7492 }
John McCallfe96e0b2011-11-06 09:01:30 +00007493 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
7494 ->getSourceExpr());
7495 continue;
7496 }
7497
John McCall31168b02011-06-15 23:02:42 +00007498 // Array ivars?
7499
7500 return false;
7501 }
7502}
7503
7504namespace {
7505 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
7506 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
7507 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00007508 Context(Context), Variable(variable), Capturer(nullptr),
7509 VarWillBeReased(false) {}
7510 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +00007511 VarDecl *Variable;
7512 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00007513 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +00007514
7515 void VisitDeclRefExpr(DeclRefExpr *ref) {
7516 if (ref->getDecl() == Variable && !Capturer)
7517 Capturer = ref;
7518 }
7519
John McCall31168b02011-06-15 23:02:42 +00007520 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
7521 if (Capturer) return;
7522 Visit(ref->getBase());
7523 if (Capturer && ref->isFreeIvar())
7524 Capturer = ref;
7525 }
7526
7527 void VisitBlockExpr(BlockExpr *block) {
7528 // Look inside nested blocks
7529 if (block->getBlockDecl()->capturesVariable(Variable))
7530 Visit(block->getBlockDecl()->getBody());
7531 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00007532
7533 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
7534 if (Capturer) return;
7535 if (OVE->getSourceExpr())
7536 Visit(OVE->getSourceExpr());
7537 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00007538 void VisitBinaryOperator(BinaryOperator *BinOp) {
7539 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
7540 return;
7541 Expr *LHS = BinOp->getLHS();
7542 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
7543 if (DRE->getDecl() != Variable)
7544 return;
7545 if (Expr *RHS = BinOp->getRHS()) {
7546 RHS = RHS->IgnoreParenCasts();
7547 llvm::APSInt Value;
7548 VarWillBeReased =
7549 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
7550 }
7551 }
7552 }
John McCall31168b02011-06-15 23:02:42 +00007553 };
7554}
7555
7556/// Check whether the given argument is a block which captures a
7557/// variable.
7558static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
7559 assert(owner.Variable && owner.Loc.isValid());
7560
7561 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00007562
7563 // Look through [^{...} copy] and Block_copy(^{...}).
7564 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
7565 Selector Cmd = ME->getSelector();
7566 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
7567 e = ME->getInstanceReceiver();
7568 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +00007569 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +00007570 e = e->IgnoreParenCasts();
7571 }
7572 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
7573 if (CE->getNumArgs() == 1) {
7574 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00007575 if (Fn) {
7576 const IdentifierInfo *FnI = Fn->getIdentifier();
7577 if (FnI && FnI->isStr("_Block_copy")) {
7578 e = CE->getArg(0)->IgnoreParenCasts();
7579 }
7580 }
Jordan Rose67e887c2012-09-17 17:54:30 +00007581 }
7582 }
7583
John McCall31168b02011-06-15 23:02:42 +00007584 BlockExpr *block = dyn_cast<BlockExpr>(e);
7585 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +00007586 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00007587
7588 FindCaptureVisitor visitor(S.Context, owner.Variable);
7589 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00007590 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +00007591}
7592
7593static void diagnoseRetainCycle(Sema &S, Expr *capturer,
7594 RetainCycleOwner &owner) {
7595 assert(capturer);
7596 assert(owner.Variable && owner.Loc.isValid());
7597
7598 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
7599 << owner.Variable << capturer->getSourceRange();
7600 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
7601 << owner.Indirect << owner.Range;
7602}
7603
7604/// Check for a keyword selector that starts with the word 'add' or
7605/// 'set'.
7606static bool isSetterLikeSelector(Selector sel) {
7607 if (sel.isUnarySelector()) return false;
7608
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007609 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00007610 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00007611 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00007612 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00007613 else if (str.startswith("add")) {
7614 // Specially whitelist 'addOperationWithBlock:'.
7615 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
7616 return false;
7617 str = str.substr(3);
7618 }
John McCall31168b02011-06-15 23:02:42 +00007619 else
7620 return false;
7621
7622 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00007623 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00007624}
7625
7626/// Check a message send to see if it's likely to cause a retain cycle.
7627void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
7628 // Only check instance methods whose selector looks like a setter.
7629 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
7630 return;
7631
7632 // Try to find a variable that the receiver is strongly owned by.
7633 RetainCycleOwner owner;
7634 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007635 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00007636 return;
7637 } else {
7638 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
7639 owner.Variable = getCurMethodDecl()->getSelfDecl();
7640 owner.Loc = msg->getSuperLoc();
7641 owner.Range = msg->getSuperLoc();
7642 }
7643
7644 // Check whether the receiver is captured by any of the arguments.
7645 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
7646 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
7647 return diagnoseRetainCycle(*this, capturer, owner);
7648}
7649
7650/// Check a property assign to see if it's likely to cause a retain cycle.
7651void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
7652 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007653 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00007654 return;
7655
7656 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
7657 diagnoseRetainCycle(*this, capturer, owner);
7658}
7659
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007660void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
7661 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +00007662 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007663 return;
7664
7665 // Because we don't have an expression for the variable, we have to set the
7666 // location explicitly here.
7667 Owner.Loc = Var->getLocation();
7668 Owner.Range = Var->getSourceRange();
7669
7670 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
7671 diagnoseRetainCycle(*this, Capturer, Owner);
7672}
7673
Ted Kremenek9304da92012-12-21 08:04:28 +00007674static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
7675 Expr *RHS, bool isProperty) {
7676 // Check if RHS is an Objective-C object literal, which also can get
7677 // immediately zapped in a weak reference. Note that we explicitly
7678 // allow ObjCStringLiterals, since those are designed to never really die.
7679 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00007680
Ted Kremenek64873352012-12-21 22:46:35 +00007681 // This enum needs to match with the 'select' in
7682 // warn_objc_arc_literal_assign (off-by-1).
7683 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
7684 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
7685 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00007686
7687 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00007688 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00007689 << (isProperty ? 0 : 1)
7690 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00007691
7692 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00007693}
7694
Ted Kremenekc1f014a2012-12-21 19:45:30 +00007695static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
7696 Qualifiers::ObjCLifetime LT,
7697 Expr *RHS, bool isProperty) {
7698 // Strip off any implicit cast added to get to the one ARC-specific.
7699 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
7700 if (cast->getCastKind() == CK_ARCConsumeObject) {
7701 S.Diag(Loc, diag::warn_arc_retained_assign)
7702 << (LT == Qualifiers::OCL_ExplicitNone)
7703 << (isProperty ? 0 : 1)
7704 << RHS->getSourceRange();
7705 return true;
7706 }
7707 RHS = cast->getSubExpr();
7708 }
7709
7710 if (LT == Qualifiers::OCL_Weak &&
7711 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
7712 return true;
7713
7714 return false;
7715}
7716
Ted Kremenekb36234d2012-12-21 08:04:20 +00007717bool Sema::checkUnsafeAssigns(SourceLocation Loc,
7718 QualType LHS, Expr *RHS) {
7719 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
7720
7721 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
7722 return false;
7723
7724 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
7725 return true;
7726
7727 return false;
7728}
7729
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007730void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
7731 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007732 QualType LHSType;
7733 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00007734 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007735 ObjCPropertyRefExpr *PRE
7736 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
7737 if (PRE && !PRE->isImplicitProperty()) {
7738 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
7739 if (PD)
7740 LHSType = PD->getType();
7741 }
7742
7743 if (LHSType.isNull())
7744 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00007745
7746 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
7747
7748 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007749 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +00007750 getCurFunction()->markSafeWeakUse(LHS);
7751 }
7752
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007753 if (checkUnsafeAssigns(Loc, LHSType, RHS))
7754 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00007755
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007756 // FIXME. Check for other life times.
7757 if (LT != Qualifiers::OCL_None)
7758 return;
7759
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007760 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007761 if (PRE->isImplicitProperty())
7762 return;
7763 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
7764 if (!PD)
7765 return;
7766
Bill Wendling44426052012-12-20 19:22:21 +00007767 unsigned Attributes = PD->getPropertyAttributes();
7768 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007769 // when 'assign' attribute was not explicitly specified
7770 // by user, ignore it and rely on property type itself
7771 // for lifetime info.
7772 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
7773 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
7774 LHSType->isObjCRetainableType())
7775 return;
7776
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007777 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00007778 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007779 Diag(Loc, diag::warn_arc_retained_property_assign)
7780 << RHS->getSourceRange();
7781 return;
7782 }
7783 RHS = cast->getSubExpr();
7784 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007785 }
Bill Wendling44426052012-12-20 19:22:21 +00007786 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00007787 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
7788 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00007789 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007790 }
7791}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00007792
7793//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
7794
7795namespace {
7796bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
7797 SourceLocation StmtLoc,
7798 const NullStmt *Body) {
7799 // Do not warn if the body is a macro that expands to nothing, e.g:
7800 //
7801 // #define CALL(x)
7802 // if (condition)
7803 // CALL(0);
7804 //
7805 if (Body->hasLeadingEmptyMacro())
7806 return false;
7807
7808 // Get line numbers of statement and body.
7809 bool StmtLineInvalid;
7810 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
7811 &StmtLineInvalid);
7812 if (StmtLineInvalid)
7813 return false;
7814
7815 bool BodyLineInvalid;
7816 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
7817 &BodyLineInvalid);
7818 if (BodyLineInvalid)
7819 return false;
7820
7821 // Warn if null statement and body are on the same line.
7822 if (StmtLine != BodyLine)
7823 return false;
7824
7825 return true;
7826}
7827} // Unnamed namespace
7828
7829void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
7830 const Stmt *Body,
7831 unsigned DiagID) {
7832 // Since this is a syntactic check, don't emit diagnostic for template
7833 // instantiations, this just adds noise.
7834 if (CurrentInstantiationScope)
7835 return;
7836
7837 // The body should be a null statement.
7838 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
7839 if (!NBody)
7840 return;
7841
7842 // Do the usual checks.
7843 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
7844 return;
7845
7846 Diag(NBody->getSemiLoc(), DiagID);
7847 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
7848}
7849
7850void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
7851 const Stmt *PossibleBody) {
7852 assert(!CurrentInstantiationScope); // Ensured by caller
7853
7854 SourceLocation StmtLoc;
7855 const Stmt *Body;
7856 unsigned DiagID;
7857 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
7858 StmtLoc = FS->getRParenLoc();
7859 Body = FS->getBody();
7860 DiagID = diag::warn_empty_for_body;
7861 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
7862 StmtLoc = WS->getCond()->getSourceRange().getEnd();
7863 Body = WS->getBody();
7864 DiagID = diag::warn_empty_while_body;
7865 } else
7866 return; // Neither `for' nor `while'.
7867
7868 // The body should be a null statement.
7869 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
7870 if (!NBody)
7871 return;
7872
7873 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007874 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00007875 return;
7876
7877 // Do the usual checks.
7878 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
7879 return;
7880
7881 // `for(...);' and `while(...);' are popular idioms, so in order to keep
7882 // noise level low, emit diagnostics only if for/while is followed by a
7883 // CompoundStmt, e.g.:
7884 // for (int i = 0; i < n; i++);
7885 // {
7886 // a(i);
7887 // }
7888 // or if for/while is followed by a statement with more indentation
7889 // than for/while itself:
7890 // for (int i = 0; i < n; i++);
7891 // a(i);
7892 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
7893 if (!ProbableTypo) {
7894 bool BodyColInvalid;
7895 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
7896 PossibleBody->getLocStart(),
7897 &BodyColInvalid);
7898 if (BodyColInvalid)
7899 return;
7900
7901 bool StmtColInvalid;
7902 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
7903 S->getLocStart(),
7904 &StmtColInvalid);
7905 if (StmtColInvalid)
7906 return;
7907
7908 if (BodyCol > StmtCol)
7909 ProbableTypo = true;
7910 }
7911
7912 if (ProbableTypo) {
7913 Diag(NBody->getSemiLoc(), DiagID);
7914 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
7915 }
7916}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007917
7918//===--- Layout compatibility ----------------------------------------------//
7919
7920namespace {
7921
7922bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
7923
7924/// \brief Check if two enumeration types are layout-compatible.
7925bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
7926 // C++11 [dcl.enum] p8:
7927 // Two enumeration types are layout-compatible if they have the same
7928 // underlying type.
7929 return ED1->isComplete() && ED2->isComplete() &&
7930 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
7931}
7932
7933/// \brief Check if two fields are layout-compatible.
7934bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
7935 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
7936 return false;
7937
7938 if (Field1->isBitField() != Field2->isBitField())
7939 return false;
7940
7941 if (Field1->isBitField()) {
7942 // Make sure that the bit-fields are the same length.
7943 unsigned Bits1 = Field1->getBitWidthValue(C);
7944 unsigned Bits2 = Field2->getBitWidthValue(C);
7945
7946 if (Bits1 != Bits2)
7947 return false;
7948 }
7949
7950 return true;
7951}
7952
7953/// \brief Check if two standard-layout structs are layout-compatible.
7954/// (C++11 [class.mem] p17)
7955bool isLayoutCompatibleStruct(ASTContext &C,
7956 RecordDecl *RD1,
7957 RecordDecl *RD2) {
7958 // If both records are C++ classes, check that base classes match.
7959 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
7960 // If one of records is a CXXRecordDecl we are in C++ mode,
7961 // thus the other one is a CXXRecordDecl, too.
7962 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
7963 // Check number of base classes.
7964 if (D1CXX->getNumBases() != D2CXX->getNumBases())
7965 return false;
7966
7967 // Check the base classes.
7968 for (CXXRecordDecl::base_class_const_iterator
7969 Base1 = D1CXX->bases_begin(),
7970 BaseEnd1 = D1CXX->bases_end(),
7971 Base2 = D2CXX->bases_begin();
7972 Base1 != BaseEnd1;
7973 ++Base1, ++Base2) {
7974 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
7975 return false;
7976 }
7977 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
7978 // If only RD2 is a C++ class, it should have zero base classes.
7979 if (D2CXX->getNumBases() > 0)
7980 return false;
7981 }
7982
7983 // Check the fields.
7984 RecordDecl::field_iterator Field2 = RD2->field_begin(),
7985 Field2End = RD2->field_end(),
7986 Field1 = RD1->field_begin(),
7987 Field1End = RD1->field_end();
7988 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
7989 if (!isLayoutCompatible(C, *Field1, *Field2))
7990 return false;
7991 }
7992 if (Field1 != Field1End || Field2 != Field2End)
7993 return false;
7994
7995 return true;
7996}
7997
7998/// \brief Check if two standard-layout unions are layout-compatible.
7999/// (C++11 [class.mem] p18)
8000bool isLayoutCompatibleUnion(ASTContext &C,
8001 RecordDecl *RD1,
8002 RecordDecl *RD2) {
8003 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008004 for (auto *Field2 : RD2->fields())
8005 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008006
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008007 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008008 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
8009 I = UnmatchedFields.begin(),
8010 E = UnmatchedFields.end();
8011
8012 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008013 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008014 bool Result = UnmatchedFields.erase(*I);
8015 (void) Result;
8016 assert(Result);
8017 break;
8018 }
8019 }
8020 if (I == E)
8021 return false;
8022 }
8023
8024 return UnmatchedFields.empty();
8025}
8026
8027bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
8028 if (RD1->isUnion() != RD2->isUnion())
8029 return false;
8030
8031 if (RD1->isUnion())
8032 return isLayoutCompatibleUnion(C, RD1, RD2);
8033 else
8034 return isLayoutCompatibleStruct(C, RD1, RD2);
8035}
8036
8037/// \brief Check if two types are layout-compatible in C++11 sense.
8038bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
8039 if (T1.isNull() || T2.isNull())
8040 return false;
8041
8042 // C++11 [basic.types] p11:
8043 // If two types T1 and T2 are the same type, then T1 and T2 are
8044 // layout-compatible types.
8045 if (C.hasSameType(T1, T2))
8046 return true;
8047
8048 T1 = T1.getCanonicalType().getUnqualifiedType();
8049 T2 = T2.getCanonicalType().getUnqualifiedType();
8050
8051 const Type::TypeClass TC1 = T1->getTypeClass();
8052 const Type::TypeClass TC2 = T2->getTypeClass();
8053
8054 if (TC1 != TC2)
8055 return false;
8056
8057 if (TC1 == Type::Enum) {
8058 return isLayoutCompatible(C,
8059 cast<EnumType>(T1)->getDecl(),
8060 cast<EnumType>(T2)->getDecl());
8061 } else if (TC1 == Type::Record) {
8062 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
8063 return false;
8064
8065 return isLayoutCompatible(C,
8066 cast<RecordType>(T1)->getDecl(),
8067 cast<RecordType>(T2)->getDecl());
8068 }
8069
8070 return false;
8071}
8072}
8073
8074//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
8075
8076namespace {
8077/// \brief Given a type tag expression find the type tag itself.
8078///
8079/// \param TypeExpr Type tag expression, as it appears in user's code.
8080///
8081/// \param VD Declaration of an identifier that appears in a type tag.
8082///
8083/// \param MagicValue Type tag magic value.
8084bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
8085 const ValueDecl **VD, uint64_t *MagicValue) {
8086 while(true) {
8087 if (!TypeExpr)
8088 return false;
8089
8090 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
8091
8092 switch (TypeExpr->getStmtClass()) {
8093 case Stmt::UnaryOperatorClass: {
8094 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
8095 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
8096 TypeExpr = UO->getSubExpr();
8097 continue;
8098 }
8099 return false;
8100 }
8101
8102 case Stmt::DeclRefExprClass: {
8103 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
8104 *VD = DRE->getDecl();
8105 return true;
8106 }
8107
8108 case Stmt::IntegerLiteralClass: {
8109 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
8110 llvm::APInt MagicValueAPInt = IL->getValue();
8111 if (MagicValueAPInt.getActiveBits() <= 64) {
8112 *MagicValue = MagicValueAPInt.getZExtValue();
8113 return true;
8114 } else
8115 return false;
8116 }
8117
8118 case Stmt::BinaryConditionalOperatorClass:
8119 case Stmt::ConditionalOperatorClass: {
8120 const AbstractConditionalOperator *ACO =
8121 cast<AbstractConditionalOperator>(TypeExpr);
8122 bool Result;
8123 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
8124 if (Result)
8125 TypeExpr = ACO->getTrueExpr();
8126 else
8127 TypeExpr = ACO->getFalseExpr();
8128 continue;
8129 }
8130 return false;
8131 }
8132
8133 case Stmt::BinaryOperatorClass: {
8134 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
8135 if (BO->getOpcode() == BO_Comma) {
8136 TypeExpr = BO->getRHS();
8137 continue;
8138 }
8139 return false;
8140 }
8141
8142 default:
8143 return false;
8144 }
8145 }
8146}
8147
8148/// \brief Retrieve the C type corresponding to type tag TypeExpr.
8149///
8150/// \param TypeExpr Expression that specifies a type tag.
8151///
8152/// \param MagicValues Registered magic values.
8153///
8154/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
8155/// kind.
8156///
8157/// \param TypeInfo Information about the corresponding C type.
8158///
8159/// \returns true if the corresponding C type was found.
8160bool GetMatchingCType(
8161 const IdentifierInfo *ArgumentKind,
8162 const Expr *TypeExpr, const ASTContext &Ctx,
8163 const llvm::DenseMap<Sema::TypeTagMagicValue,
8164 Sema::TypeTagData> *MagicValues,
8165 bool &FoundWrongKind,
8166 Sema::TypeTagData &TypeInfo) {
8167 FoundWrongKind = false;
8168
8169 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +00008170 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008171
8172 uint64_t MagicValue;
8173
8174 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
8175 return false;
8176
8177 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +00008178 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008179 if (I->getArgumentKind() != ArgumentKind) {
8180 FoundWrongKind = true;
8181 return false;
8182 }
8183 TypeInfo.Type = I->getMatchingCType();
8184 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
8185 TypeInfo.MustBeNull = I->getMustBeNull();
8186 return true;
8187 }
8188 return false;
8189 }
8190
8191 if (!MagicValues)
8192 return false;
8193
8194 llvm::DenseMap<Sema::TypeTagMagicValue,
8195 Sema::TypeTagData>::const_iterator I =
8196 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
8197 if (I == MagicValues->end())
8198 return false;
8199
8200 TypeInfo = I->second;
8201 return true;
8202}
8203} // unnamed namespace
8204
8205void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
8206 uint64_t MagicValue, QualType Type,
8207 bool LayoutCompatible,
8208 bool MustBeNull) {
8209 if (!TypeTagForDatatypeMagicValues)
8210 TypeTagForDatatypeMagicValues.reset(
8211 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
8212
8213 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
8214 (*TypeTagForDatatypeMagicValues)[Magic] =
8215 TypeTagData(Type, LayoutCompatible, MustBeNull);
8216}
8217
8218namespace {
8219bool IsSameCharType(QualType T1, QualType T2) {
8220 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
8221 if (!BT1)
8222 return false;
8223
8224 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
8225 if (!BT2)
8226 return false;
8227
8228 BuiltinType::Kind T1Kind = BT1->getKind();
8229 BuiltinType::Kind T2Kind = BT2->getKind();
8230
8231 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
8232 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
8233 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
8234 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
8235}
8236} // unnamed namespace
8237
8238void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
8239 const Expr * const *ExprArgs) {
8240 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
8241 bool IsPointerAttr = Attr->getIsPointer();
8242
8243 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
8244 bool FoundWrongKind;
8245 TypeTagData TypeInfo;
8246 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
8247 TypeTagForDatatypeMagicValues.get(),
8248 FoundWrongKind, TypeInfo)) {
8249 if (FoundWrongKind)
8250 Diag(TypeTagExpr->getExprLoc(),
8251 diag::warn_type_tag_for_datatype_wrong_kind)
8252 << TypeTagExpr->getSourceRange();
8253 return;
8254 }
8255
8256 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
8257 if (IsPointerAttr) {
8258 // Skip implicit cast of pointer to `void *' (as a function argument).
8259 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +00008260 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +00008261 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008262 ArgumentExpr = ICE->getSubExpr();
8263 }
8264 QualType ArgumentType = ArgumentExpr->getType();
8265
8266 // Passing a `void*' pointer shouldn't trigger a warning.
8267 if (IsPointerAttr && ArgumentType->isVoidPointerType())
8268 return;
8269
8270 if (TypeInfo.MustBeNull) {
8271 // Type tag with matching void type requires a null pointer.
8272 if (!ArgumentExpr->isNullPointerConstant(Context,
8273 Expr::NPC_ValueDependentIsNotNull)) {
8274 Diag(ArgumentExpr->getExprLoc(),
8275 diag::warn_type_safety_null_pointer_required)
8276 << ArgumentKind->getName()
8277 << ArgumentExpr->getSourceRange()
8278 << TypeTagExpr->getSourceRange();
8279 }
8280 return;
8281 }
8282
8283 QualType RequiredType = TypeInfo.Type;
8284 if (IsPointerAttr)
8285 RequiredType = Context.getPointerType(RequiredType);
8286
8287 bool mismatch = false;
8288 if (!TypeInfo.LayoutCompatible) {
8289 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
8290
8291 // C++11 [basic.fundamental] p1:
8292 // Plain char, signed char, and unsigned char are three distinct types.
8293 //
8294 // But we treat plain `char' as equivalent to `signed char' or `unsigned
8295 // char' depending on the current char signedness mode.
8296 if (mismatch)
8297 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
8298 RequiredType->getPointeeType())) ||
8299 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
8300 mismatch = false;
8301 } else
8302 if (IsPointerAttr)
8303 mismatch = !isLayoutCompatible(Context,
8304 ArgumentType->getPointeeType(),
8305 RequiredType->getPointeeType());
8306 else
8307 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
8308
8309 if (mismatch)
8310 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +00008311 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008312 << TypeInfo.LayoutCompatible << RequiredType
8313 << ArgumentExpr->getSourceRange()
8314 << TypeTagExpr->getSourceRange();
8315}
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008316