blob: 66be962fcf3327022cc263b62ab21df3173583be [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 Northovera2ee4332014-03-29 15:09:45 +0000345 case llvm::Triple::arm64:
James Molloyfa403682014-04-30 10:11:40 +0000346 case llvm::Triple::arm64_be:
Tim Northover573cbee2014-05-24 12:52:07 +0000347 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +0000348 return ExprError();
349 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000350 case llvm::Triple::mips:
351 case llvm::Triple::mipsel:
352 case llvm::Triple::mips64:
353 case llvm::Triple::mips64el:
354 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
355 return ExprError();
356 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000357 case llvm::Triple::x86:
358 case llvm::Triple::x86_64:
359 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
360 return ExprError();
361 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000362 default:
363 break;
364 }
365 }
366
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000367 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +0000368}
369
Nate Begeman91e1fea2010-06-14 05:21:25 +0000370// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +0000371static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +0000372 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +0000373 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +0000374 switch (Type.getEltType()) {
375 case NeonTypeFlags::Int8:
376 case NeonTypeFlags::Poly8:
377 return shift ? 7 : (8 << IsQuad) - 1;
378 case NeonTypeFlags::Int16:
379 case NeonTypeFlags::Poly16:
380 return shift ? 15 : (4 << IsQuad) - 1;
381 case NeonTypeFlags::Int32:
382 return shift ? 31 : (2 << IsQuad) - 1;
383 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +0000384 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +0000385 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000386 case NeonTypeFlags::Poly128:
387 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +0000388 case NeonTypeFlags::Float16:
389 assert(!shift && "cannot shift float types!");
390 return (4 << IsQuad) - 1;
391 case NeonTypeFlags::Float32:
392 assert(!shift && "cannot shift float types!");
393 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000394 case NeonTypeFlags::Float64:
395 assert(!shift && "cannot shift float types!");
396 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000397 }
David Blaikie8a40f702012-01-17 06:56:22 +0000398 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +0000399}
400
Bob Wilsone4d77232011-11-08 05:04:11 +0000401/// getNeonEltType - Return the QualType corresponding to the elements of
402/// the vector type specified by the NeonTypeFlags. This is used to check
403/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +0000404static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +0000405 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +0000406 switch (Flags.getEltType()) {
407 case NeonTypeFlags::Int8:
408 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
409 case NeonTypeFlags::Int16:
410 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
411 case NeonTypeFlags::Int32:
412 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
413 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +0000414 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +0000415 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
416 else
417 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
418 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000419 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +0000420 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000421 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +0000422 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +0000423 case NeonTypeFlags::Poly64:
Kevin Qinad64f6d2014-02-24 02:45:03 +0000424 return Context.UnsignedLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000425 case NeonTypeFlags::Poly128:
426 break;
Bob Wilsone4d77232011-11-08 05:04:11 +0000427 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +0000428 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000429 case NeonTypeFlags::Float32:
430 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +0000431 case NeonTypeFlags::Float64:
432 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000433 }
David Blaikie8a40f702012-01-17 06:56:22 +0000434 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +0000435}
436
Tim Northover12670412014-02-19 10:37:05 +0000437bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +0000438 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +0000439 uint64_t mask = 0;
440 unsigned TV = 0;
441 int PtrArgNum = -1;
442 bool HasConstPtr = false;
443 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +0000444#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000445#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000446#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000447 }
448
449 // For NEON intrinsics which are overloaded on vector element type, validate
450 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +0000451 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000452 if (mask) {
453 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
454 return true;
455
456 TV = Result.getLimitedValue(64);
457 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
458 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +0000459 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +0000460 }
461
462 if (PtrArgNum >= 0) {
463 // Check that pointer arguments have the specified type.
464 Expr *Arg = TheCall->getArg(PtrArgNum);
465 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
466 Arg = ICE->getSubExpr();
467 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
468 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +0000469
Tim Northovera2ee4332014-03-29 15:09:45 +0000470 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
471 bool IsPolyUnsigned =
472 Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::arm64;
473 bool IsInt64Long =
474 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
475 QualType EltTy =
476 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +0000477 if (HasConstPtr)
478 EltTy = EltTy.withConst();
479 QualType LHSTy = Context.getPointerType(EltTy);
480 AssignConvertType ConvTy;
481 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
482 if (RHS.isInvalid())
483 return true;
484 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
485 RHS.get(), AA_Assigning))
486 return true;
487 }
488
489 // For NEON intrinsics which take an immediate value as part of the
490 // instruction, range check them here.
491 unsigned i = 0, l = 0, u = 0;
492 switch (BuiltinID) {
493 default:
494 return false;
Tim Northover12670412014-02-19 10:37:05 +0000495#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000496#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000497#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000498 }
Tim Northover2fe823a2013-08-01 09:23:19 +0000499
Richard Sandiford28940af2014-04-16 08:47:51 +0000500 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +0000501}
502
Tim Northovera2ee4332014-03-29 15:09:45 +0000503bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
504 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +0000505 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000506 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +0000507 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000508 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +0000509 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000510 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
511 BuiltinID == AArch64::BI__builtin_arm_strex ||
512 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +0000513 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +0000514 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000515 BuiltinID == ARM::BI__builtin_arm_ldaex ||
516 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
517 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +0000518
519 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
520
521 // Ensure that we have the proper number of arguments.
522 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
523 return true;
524
525 // Inspect the pointer argument of the atomic builtin. This should always be
526 // a pointer type, whose element is an integral scalar or pointer type.
527 // Because it is a pointer type, we don't have to worry about any implicit
528 // casts here.
529 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
530 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
531 if (PointerArgRes.isInvalid())
532 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000533 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000534
535 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
536 if (!pointerType) {
537 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
538 << PointerArg->getType() << PointerArg->getSourceRange();
539 return true;
540 }
541
542 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
543 // task is to insert the appropriate casts into the AST. First work out just
544 // what the appropriate type is.
545 QualType ValType = pointerType->getPointeeType();
546 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
547 if (IsLdrex)
548 AddrType.addConst();
549
550 // Issue a warning if the cast is dodgy.
551 CastKind CastNeeded = CK_NoOp;
552 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
553 CastNeeded = CK_BitCast;
554 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
555 << PointerArg->getType()
556 << Context.getPointerType(AddrType)
557 << AA_Passing << PointerArg->getSourceRange();
558 }
559
560 // Finally, do the cast and replace the argument with the corrected version.
561 AddrType = Context.getPointerType(AddrType);
562 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
563 if (PointerArgRes.isInvalid())
564 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000565 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000566
567 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
568
569 // In general, we allow ints, floats and pointers to be loaded and stored.
570 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
571 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
572 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
573 << PointerArg->getType() << PointerArg->getSourceRange();
574 return true;
575 }
576
577 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +0000578 if (Context.getTypeSize(ValType) > MaxWidth) {
579 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +0000580 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
581 << PointerArg->getType() << PointerArg->getSourceRange();
582 return true;
583 }
584
585 switch (ValType.getObjCLifetime()) {
586 case Qualifiers::OCL_None:
587 case Qualifiers::OCL_ExplicitNone:
588 // okay
589 break;
590
591 case Qualifiers::OCL_Weak:
592 case Qualifiers::OCL_Strong:
593 case Qualifiers::OCL_Autoreleasing:
594 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
595 << ValType << PointerArg->getSourceRange();
596 return true;
597 }
598
599
600 if (IsLdrex) {
601 TheCall->setType(ValType);
602 return false;
603 }
604
605 // Initialize the argument to be stored.
606 ExprResult ValArg = TheCall->getArg(0);
607 InitializedEntity Entity = InitializedEntity::InitializeParameter(
608 Context, ValType, /*consume*/ false);
609 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
610 if (ValArg.isInvalid())
611 return true;
Tim Northover6aacd492013-07-16 09:47:53 +0000612 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +0000613
614 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
615 // but the custom checker bypasses all default analysis.
616 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +0000617 return false;
618}
619
Nate Begeman4904e322010-06-08 02:47:44 +0000620bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +0000621 llvm::APSInt Result;
622
Tim Northover6aacd492013-07-16 09:47:53 +0000623 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000624 BuiltinID == ARM::BI__builtin_arm_ldaex ||
625 BuiltinID == ARM::BI__builtin_arm_strex ||
626 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000627 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +0000628 }
629
Tim Northover12670412014-02-19 10:37:05 +0000630 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
631 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +0000632
Yi Kong4efadfb2014-07-03 16:01:25 +0000633 // For intrinsics which take an immediate value as part of the instruction,
634 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +0000635 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +0000636 switch (BuiltinID) {
637 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +0000638 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
639 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +0000640 case ARM::BI__builtin_arm_vcvtr_f:
641 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +0000642 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +0000643 case ARM::BI__builtin_arm_dsb:
644 case ARM::BI__builtin_arm_isb: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +0000645 }
Nate Begemand773fe62010-06-13 04:47:52 +0000646
Nate Begemanf568b072010-08-03 21:32:34 +0000647 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +0000648 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000649}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000650
Tim Northover573cbee2014-05-24 12:52:07 +0000651bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +0000652 CallExpr *TheCall) {
653 llvm::APSInt Result;
654
Tim Northover573cbee2014-05-24 12:52:07 +0000655 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000656 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
657 BuiltinID == AArch64::BI__builtin_arm_strex ||
658 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000659 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
660 }
661
662 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
663 return true;
664
Yi Kong19a29ac2014-07-17 10:52:06 +0000665 // For intrinsics which take an immediate value as part of the instruction,
666 // range check them here.
667 unsigned i = 0, l = 0, u = 0;
668 switch (BuiltinID) {
669 default: return false;
670 case AArch64::BI__builtin_arm_dmb:
671 case AArch64::BI__builtin_arm_dsb:
672 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
673 }
674
675 // FIXME: VFP Intrinsics should error if VFP not present.
676 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +0000677}
678
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000679bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
680 unsigned i = 0, l = 0, u = 0;
681 switch (BuiltinID) {
682 default: return false;
683 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
684 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +0000685 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
686 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
687 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
688 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
689 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Richard Sandiford28940af2014-04-16 08:47:51 +0000690 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000691
Richard Sandiford28940af2014-04-16 08:47:51 +0000692 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000693}
694
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000695bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
696 switch (BuiltinID) {
697 case X86::BI_mm_prefetch:
Richard Sandiford28940af2014-04-16 08:47:51 +0000698 // This is declared to take (const char*, int)
699 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000700 }
701 return false;
702}
703
Richard Smith55ce3522012-06-25 20:30:08 +0000704/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
705/// parameter with the FormatAttr's correct format_idx and firstDataArg.
706/// Returns true when the format fits the function and the FormatStringInfo has
707/// been populated.
708bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
709 FormatStringInfo *FSI) {
710 FSI->HasVAListArg = Format->getFirstArg() == 0;
711 FSI->FormatIdx = Format->getFormatIdx() - 1;
712 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000713
Richard Smith55ce3522012-06-25 20:30:08 +0000714 // The way the format attribute works in GCC, the implicit this argument
715 // of member functions is counted. However, it doesn't appear in our own
716 // lists, so decrement format_idx in that case.
717 if (IsCXXMember) {
718 if(FSI->FormatIdx == 0)
719 return false;
720 --FSI->FormatIdx;
721 if (FSI->FirstDataArg != 0)
722 --FSI->FirstDataArg;
723 }
724 return true;
725}
Mike Stump11289f42009-09-09 15:08:12 +0000726
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000727/// Checks if a the given expression evaluates to null.
728///
729/// \brief Returns true if the value evaluates to null.
730static bool CheckNonNullExpr(Sema &S,
731 const Expr *Expr) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000732 // As a special case, transparent unions initialized with zero are
733 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000734 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000735 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
736 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000737 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000738 if (const InitListExpr *ILE =
739 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000740 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +0000741 }
742
743 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +0000744 return (!Expr->isValueDependent() &&
745 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
746 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000747}
748
749static void CheckNonNullArgument(Sema &S,
750 const Expr *ArgExpr,
751 SourceLocation CallSiteLoc) {
752 if (CheckNonNullExpr(S, ArgExpr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000753 S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
754}
755
Ted Kremenek2bc73332014-01-17 06:24:43 +0000756static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +0000757 const NamedDecl *FDecl,
Ted Kremenek2bc73332014-01-17 06:24:43 +0000758 const Expr * const *ExprArgs,
759 SourceLocation CallSiteLoc) {
Ted Kremenek9aedc152014-01-17 06:24:56 +0000760 // Check the attributes attached to the method/function itself.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000761 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000762 for (const auto &Val : NonNull->args())
763 CheckNonNullArgument(S, ExprArgs[Val], CallSiteLoc);
Ted Kremenek2bc73332014-01-17 06:24:43 +0000764 }
Ted Kremenek9aedc152014-01-17 06:24:56 +0000765
766 // Check the attributes on the parameters.
767 ArrayRef<ParmVarDecl*> parms;
768 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
769 parms = FD->parameters();
770 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(FDecl))
771 parms = MD->parameters();
772
773 unsigned argIndex = 0;
774 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
775 I != E; ++I, ++argIndex) {
776 const ParmVarDecl *PVD = *I;
777 if (PVD->hasAttr<NonNullAttr>())
778 CheckNonNullArgument(S, ExprArgs[argIndex], CallSiteLoc);
779 }
Ted Kremenek2bc73332014-01-17 06:24:43 +0000780}
781
Richard Smith55ce3522012-06-25 20:30:08 +0000782/// Handles the checks for format strings, non-POD arguments to vararg
783/// functions, and NULL arguments passed to non-NULL parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +0000784void Sema::checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
785 unsigned NumParams, bool IsMemberFunction,
786 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +0000787 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +0000788 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +0000789 if (CurContext->isDependentContext())
790 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000791
Ted Kremenekb8176da2010-09-09 04:33:05 +0000792 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +0000793 llvm::SmallBitVector CheckedVarArgs;
794 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000795 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +0000796 // Only create vector if there are format attributes.
797 CheckedVarArgs.resize(Args.size());
798
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000799 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +0000800 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +0000801 }
Richard Smithd7293d72013-08-05 18:49:43 +0000802 }
Richard Smith55ce3522012-06-25 20:30:08 +0000803
804 // Refuse POD arguments that weren't caught by the format string
805 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +0000806 if (CallType != VariadicDoesNotApply) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000807 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +0000808 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +0000809 if (const Expr *Arg = Args[ArgIdx]) {
810 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
811 checkVariadicArgument(Arg, CallType);
812 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +0000813 }
Richard Smithd7293d72013-08-05 18:49:43 +0000814 }
Mike Stump11289f42009-09-09 15:08:12 +0000815
Richard Trieu41bc0992013-06-22 00:20:41 +0000816 if (FDecl) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000817 CheckNonNullArguments(*this, FDecl, Args.data(), Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000818
Richard Trieu41bc0992013-06-22 00:20:41 +0000819 // Type safety checking.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000820 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
821 CheckArgumentWithTypeTag(I, Args.data());
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000822 }
Richard Smith55ce3522012-06-25 20:30:08 +0000823}
824
825/// CheckConstructorCall - Check a constructor call for correctness and safety
826/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +0000827void Sema::CheckConstructorCall(FunctionDecl *FDecl,
828 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +0000829 const FunctionProtoType *Proto,
830 SourceLocation Loc) {
831 VariadicCallType CallType =
832 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Alp Toker9cacbab2014-01-20 20:26:09 +0000833 checkCall(FDecl, Args, Proto->getNumParams(),
Richard Smith55ce3522012-06-25 20:30:08 +0000834 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
835}
836
837/// CheckFunctionCall - Check a direct function call for various correctness
838/// and safety properties not strictly enforced by the C type system.
839bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
840 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +0000841 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
842 isa<CXXMethodDecl>(FDecl);
843 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
844 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +0000845 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
846 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +0000847 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Eli Friedman726d11c2012-10-11 00:30:58 +0000848 Expr** Args = TheCall->getArgs();
849 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +0000850 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +0000851 // If this is a call to a member operator, hide the first argument
852 // from checkCall.
853 // FIXME: Our choice of AST representation here is less than ideal.
854 ++Args;
855 --NumArgs;
856 }
Alp Toker9cacbab2014-01-20 20:26:09 +0000857 checkCall(FDecl, llvm::makeArrayRef<const Expr *>(Args, NumArgs), NumParams,
Richard Smith55ce3522012-06-25 20:30:08 +0000858 IsMemberFunction, TheCall->getRParenLoc(),
859 TheCall->getCallee()->getSourceRange(), CallType);
860
861 IdentifierInfo *FnInfo = FDecl->getIdentifier();
862 // None of the checks below are needed for functions that don't have
863 // simple names (e.g., C++ conversion functions).
864 if (!FnInfo)
865 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000866
Richard Trieu7eb0b2c2014-02-26 01:17:28 +0000867 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
868
Anna Zaks22122702012-01-17 00:37:07 +0000869 unsigned CMId = FDecl->getMemoryFunctionKind();
870 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +0000871 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +0000872
Anna Zaks201d4892012-01-13 21:52:01 +0000873 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +0000874 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +0000875 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +0000876 else if (CMId == Builtin::BIstrncat)
877 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +0000878 else
Anna Zaks22122702012-01-17 00:37:07 +0000879 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +0000880
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000881 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +0000882}
883
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000884bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +0000885 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +0000886 VariadicCallType CallType =
887 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000888
Dmitri Gribenko1debc462013-05-05 19:42:09 +0000889 checkCall(Method, Args, Method->param_size(),
Richard Smith55ce3522012-06-25 20:30:08 +0000890 /*IsMemberFunction=*/false,
891 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000892
893 return false;
894}
895
Richard Trieu664c4c62013-06-20 21:03:13 +0000896bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
897 const FunctionProtoType *Proto) {
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000898 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
899 if (!V)
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000900 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000901
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000902 QualType Ty = V->getType();
Richard Trieu664c4c62013-06-20 21:03:13 +0000903 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000904 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000905
Richard Trieu664c4c62013-06-20 21:03:13 +0000906 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +0000907 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +0000908 CallType = VariadicDoesNotApply;
909 } else if (Ty->isBlockPointerType()) {
910 CallType = VariadicBlock;
911 } else { // Ty->isFunctionPointerType()
912 CallType = VariadicFunction;
913 }
Alp Toker9cacbab2014-01-20 20:26:09 +0000914 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000915
Alp Toker9cacbab2014-01-20 20:26:09 +0000916 checkCall(NDecl, llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
917 TheCall->getNumArgs()),
918 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +0000919 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +0000920
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000921 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000922}
923
Richard Trieu41bc0992013-06-22 00:20:41 +0000924/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
925/// such as function pointers returned from functions.
926bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000927 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +0000928 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +0000929 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Richard Trieu41bc0992013-06-22 00:20:41 +0000930
Craig Topperc3ec1492014-05-26 06:22:03 +0000931 checkCall(/*FDecl=*/nullptr,
932 llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
933 TheCall->getNumArgs()),
Alp Toker9cacbab2014-01-20 20:26:09 +0000934 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +0000935 TheCall->getCallee()->getSourceRange(), CallType);
936
937 return false;
938}
939
Tim Northovere94a34c2014-03-11 10:49:14 +0000940static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
941 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
942 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
943 return false;
944
945 switch (Op) {
946 case AtomicExpr::AO__c11_atomic_init:
947 llvm_unreachable("There is no ordering argument for an init");
948
949 case AtomicExpr::AO__c11_atomic_load:
950 case AtomicExpr::AO__atomic_load_n:
951 case AtomicExpr::AO__atomic_load:
952 return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
953 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
954
955 case AtomicExpr::AO__c11_atomic_store:
956 case AtomicExpr::AO__atomic_store:
957 case AtomicExpr::AO__atomic_store_n:
958 return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
959 Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
960 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
961
962 default:
963 return true;
964 }
965}
966
Richard Smithfeea8832012-04-12 05:08:17 +0000967ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
968 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000969 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
970 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000971
Richard Smithfeea8832012-04-12 05:08:17 +0000972 // All these operations take one of the following forms:
973 enum {
974 // C __c11_atomic_init(A *, C)
975 Init,
976 // C __c11_atomic_load(A *, int)
977 Load,
978 // void __atomic_load(A *, CP, int)
979 Copy,
980 // C __c11_atomic_add(A *, M, int)
981 Arithmetic,
982 // C __atomic_exchange_n(A *, CP, int)
983 Xchg,
984 // void __atomic_exchange(A *, C *, CP, int)
985 GNUXchg,
986 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
987 C11CmpXchg,
988 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
989 GNUCmpXchg
990 } Form = Init;
991 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
992 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
993 // where:
994 // C is an appropriate type,
995 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
996 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
997 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
998 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000999
Richard Smithfeea8832012-04-12 05:08:17 +00001000 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
1001 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
1002 && "need to update code for modified C11 atomics");
1003 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
1004 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
1005 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
1006 Op == AtomicExpr::AO__atomic_store_n ||
1007 Op == AtomicExpr::AO__atomic_exchange_n ||
1008 Op == AtomicExpr::AO__atomic_compare_exchange_n;
1009 bool IsAddSub = false;
1010
1011 switch (Op) {
1012 case AtomicExpr::AO__c11_atomic_init:
1013 Form = Init;
1014 break;
1015
1016 case AtomicExpr::AO__c11_atomic_load:
1017 case AtomicExpr::AO__atomic_load_n:
1018 Form = Load;
1019 break;
1020
1021 case AtomicExpr::AO__c11_atomic_store:
1022 case AtomicExpr::AO__atomic_load:
1023 case AtomicExpr::AO__atomic_store:
1024 case AtomicExpr::AO__atomic_store_n:
1025 Form = Copy;
1026 break;
1027
1028 case AtomicExpr::AO__c11_atomic_fetch_add:
1029 case AtomicExpr::AO__c11_atomic_fetch_sub:
1030 case AtomicExpr::AO__atomic_fetch_add:
1031 case AtomicExpr::AO__atomic_fetch_sub:
1032 case AtomicExpr::AO__atomic_add_fetch:
1033 case AtomicExpr::AO__atomic_sub_fetch:
1034 IsAddSub = true;
1035 // Fall through.
1036 case AtomicExpr::AO__c11_atomic_fetch_and:
1037 case AtomicExpr::AO__c11_atomic_fetch_or:
1038 case AtomicExpr::AO__c11_atomic_fetch_xor:
1039 case AtomicExpr::AO__atomic_fetch_and:
1040 case AtomicExpr::AO__atomic_fetch_or:
1041 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00001042 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00001043 case AtomicExpr::AO__atomic_and_fetch:
1044 case AtomicExpr::AO__atomic_or_fetch:
1045 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00001046 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00001047 Form = Arithmetic;
1048 break;
1049
1050 case AtomicExpr::AO__c11_atomic_exchange:
1051 case AtomicExpr::AO__atomic_exchange_n:
1052 Form = Xchg;
1053 break;
1054
1055 case AtomicExpr::AO__atomic_exchange:
1056 Form = GNUXchg;
1057 break;
1058
1059 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1060 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1061 Form = C11CmpXchg;
1062 break;
1063
1064 case AtomicExpr::AO__atomic_compare_exchange:
1065 case AtomicExpr::AO__atomic_compare_exchange_n:
1066 Form = GNUCmpXchg;
1067 break;
1068 }
1069
1070 // Check we have the right number of arguments.
1071 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001072 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001073 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001074 << TheCall->getCallee()->getSourceRange();
1075 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00001076 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1077 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001078 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001079 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001080 << TheCall->getCallee()->getSourceRange();
1081 return ExprError();
1082 }
1083
Richard Smithfeea8832012-04-12 05:08:17 +00001084 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001085 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001086 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1087 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1088 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00001089 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001090 << Ptr->getType() << Ptr->getSourceRange();
1091 return ExprError();
1092 }
1093
Richard Smithfeea8832012-04-12 05:08:17 +00001094 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1095 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1096 QualType ValType = AtomTy; // 'C'
1097 if (IsC11) {
1098 if (!AtomTy->isAtomicType()) {
1099 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1100 << Ptr->getType() << Ptr->getSourceRange();
1101 return ExprError();
1102 }
Richard Smithe00921a2012-09-15 06:09:58 +00001103 if (AtomTy.isConstQualified()) {
1104 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1105 << Ptr->getType() << Ptr->getSourceRange();
1106 return ExprError();
1107 }
Richard Smithfeea8832012-04-12 05:08:17 +00001108 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001109 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001110
Richard Smithfeea8832012-04-12 05:08:17 +00001111 // For an arithmetic operation, the implied arithmetic must be well-formed.
1112 if (Form == Arithmetic) {
1113 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1114 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1115 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1116 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1117 return ExprError();
1118 }
1119 if (!IsAddSub && !ValType->isIntegerType()) {
1120 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1121 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1122 return ExprError();
1123 }
1124 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1125 // For __atomic_*_n operations, the value type must be a scalar integral or
1126 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001127 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00001128 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1129 return ExprError();
1130 }
1131
Eli Friedmanaa769812013-09-11 03:49:34 +00001132 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1133 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00001134 // For GNU atomics, require a trivially-copyable type. This is not part of
1135 // the GNU atomics specification, but we enforce it for sanity.
1136 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001137 << Ptr->getType() << Ptr->getSourceRange();
1138 return ExprError();
1139 }
1140
Richard Smithfeea8832012-04-12 05:08:17 +00001141 // FIXME: For any builtin other than a load, the ValType must not be
1142 // const-qualified.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001143
1144 switch (ValType.getObjCLifetime()) {
1145 case Qualifiers::OCL_None:
1146 case Qualifiers::OCL_ExplicitNone:
1147 // okay
1148 break;
1149
1150 case Qualifiers::OCL_Weak:
1151 case Qualifiers::OCL_Strong:
1152 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00001153 // FIXME: Can this happen? By this point, ValType should be known
1154 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001155 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1156 << ValType << Ptr->getSourceRange();
1157 return ExprError();
1158 }
1159
1160 QualType ResultType = ValType;
Richard Smithfeea8832012-04-12 05:08:17 +00001161 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001162 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00001163 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001164 ResultType = Context.BoolTy;
1165
Richard Smithfeea8832012-04-12 05:08:17 +00001166 // The type of a parameter passed 'by value'. In the GNU atomics, such
1167 // arguments are actually passed as pointers.
1168 QualType ByValType = ValType; // 'CP'
1169 if (!IsC11 && !IsN)
1170 ByValType = Ptr->getType();
1171
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001172 // The first argument --- the pointer --- has a fixed type; we
1173 // deduce the types of the rest of the arguments accordingly. Walk
1174 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00001175 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001176 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00001177 if (i < NumVals[Form] + 1) {
1178 switch (i) {
1179 case 1:
1180 // The second argument is the non-atomic operand. For arithmetic, this
1181 // is always passed by value, and for a compare_exchange it is always
1182 // passed by address. For the rest, GNU uses by-address and C11 uses
1183 // by-value.
1184 assert(Form != Load);
1185 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1186 Ty = ValType;
1187 else if (Form == Copy || Form == Xchg)
1188 Ty = ByValType;
1189 else if (Form == Arithmetic)
1190 Ty = Context.getPointerDiffType();
1191 else
1192 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1193 break;
1194 case 2:
1195 // The third argument to compare_exchange / GNU exchange is a
1196 // (pointer to a) desired value.
1197 Ty = ByValType;
1198 break;
1199 case 3:
1200 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1201 Ty = Context.BoolTy;
1202 break;
1203 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001204 } else {
1205 // The order(s) are always converted to int.
1206 Ty = Context.IntTy;
1207 }
Richard Smithfeea8832012-04-12 05:08:17 +00001208
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001209 InitializedEntity Entity =
1210 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00001211 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001212 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1213 if (Arg.isInvalid())
1214 return true;
1215 TheCall->setArg(i, Arg.get());
1216 }
1217
Richard Smithfeea8832012-04-12 05:08:17 +00001218 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001219 SmallVector<Expr*, 5> SubExprs;
1220 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00001221 switch (Form) {
1222 case Init:
1223 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00001224 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001225 break;
1226 case Load:
1227 SubExprs.push_back(TheCall->getArg(1)); // Order
1228 break;
1229 case Copy:
1230 case Arithmetic:
1231 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001232 SubExprs.push_back(TheCall->getArg(2)); // Order
1233 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001234 break;
1235 case GNUXchg:
1236 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1237 SubExprs.push_back(TheCall->getArg(3)); // Order
1238 SubExprs.push_back(TheCall->getArg(1)); // Val1
1239 SubExprs.push_back(TheCall->getArg(2)); // Val2
1240 break;
1241 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001242 SubExprs.push_back(TheCall->getArg(3)); // Order
1243 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001244 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00001245 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00001246 break;
1247 case GNUCmpXchg:
1248 SubExprs.push_back(TheCall->getArg(4)); // Order
1249 SubExprs.push_back(TheCall->getArg(1)); // Val1
1250 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1251 SubExprs.push_back(TheCall->getArg(2)); // Val2
1252 SubExprs.push_back(TheCall->getArg(3)); // Weak
1253 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001254 }
Tim Northovere94a34c2014-03-11 10:49:14 +00001255
1256 if (SubExprs.size() >= 2 && Form != Init) {
1257 llvm::APSInt Result(32);
1258 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
1259 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00001260 Diag(SubExprs[1]->getLocStart(),
1261 diag::warn_atomic_op_has_invalid_memory_order)
1262 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00001263 }
1264
Fariborz Jahanian615de762013-05-28 17:37:39 +00001265 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1266 SubExprs, ResultType, Op,
1267 TheCall->getRParenLoc());
1268
1269 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1270 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1271 Context.AtomicUsesUnsupportedLibcall(AE))
1272 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1273 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001274
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001275 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001276}
1277
1278
John McCall29ad95b2011-08-27 01:09:30 +00001279/// checkBuiltinArgument - Given a call to a builtin function, perform
1280/// normal type-checking on the given argument, updating the call in
1281/// place. This is useful when a builtin function requires custom
1282/// type-checking for some of its arguments but not necessarily all of
1283/// them.
1284///
1285/// Returns true on error.
1286static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1287 FunctionDecl *Fn = E->getDirectCallee();
1288 assert(Fn && "builtin call without direct callee!");
1289
1290 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1291 InitializedEntity Entity =
1292 InitializedEntity::InitializeParameter(S.Context, Param);
1293
1294 ExprResult Arg = E->getArg(0);
1295 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1296 if (Arg.isInvalid())
1297 return true;
1298
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001299 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00001300 return false;
1301}
1302
Chris Lattnerdc046542009-05-08 06:58:22 +00001303/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1304/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1305/// type of its first argument. The main ActOnCallExpr routines have already
1306/// promoted the types of arguments because all of these calls are prototyped as
1307/// void(...).
1308///
1309/// This function goes through and does final semantic checking for these
1310/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00001311ExprResult
1312Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001313 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00001314 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1315 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1316
1317 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001318 if (TheCall->getNumArgs() < 1) {
1319 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1320 << 0 << 1 << TheCall->getNumArgs()
1321 << TheCall->getCallee()->getSourceRange();
1322 return ExprError();
1323 }
Mike Stump11289f42009-09-09 15:08:12 +00001324
Chris Lattnerdc046542009-05-08 06:58:22 +00001325 // Inspect the first argument of the atomic builtin. This should always be
1326 // a pointer type, whose element is an integral scalar or pointer type.
1327 // Because it is a pointer type, we don't have to worry about any implicit
1328 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001329 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00001330 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00001331 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1332 if (FirstArgResult.isInvalid())
1333 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001334 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00001335 TheCall->setArg(0, FirstArg);
1336
John McCall31168b02011-06-15 23:02:42 +00001337 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1338 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001339 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1340 << FirstArg->getType() << FirstArg->getSourceRange();
1341 return ExprError();
1342 }
Mike Stump11289f42009-09-09 15:08:12 +00001343
John McCall31168b02011-06-15 23:02:42 +00001344 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00001345 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001346 !ValType->isBlockPointerType()) {
1347 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1348 << FirstArg->getType() << FirstArg->getSourceRange();
1349 return ExprError();
1350 }
Chris Lattnerdc046542009-05-08 06:58:22 +00001351
John McCall31168b02011-06-15 23:02:42 +00001352 switch (ValType.getObjCLifetime()) {
1353 case Qualifiers::OCL_None:
1354 case Qualifiers::OCL_ExplicitNone:
1355 // okay
1356 break;
1357
1358 case Qualifiers::OCL_Weak:
1359 case Qualifiers::OCL_Strong:
1360 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00001361 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00001362 << ValType << FirstArg->getSourceRange();
1363 return ExprError();
1364 }
1365
John McCallb50451a2011-10-05 07:41:44 +00001366 // Strip any qualifiers off ValType.
1367 ValType = ValType.getUnqualifiedType();
1368
Chandler Carruth3973af72010-07-18 20:54:12 +00001369 // The majority of builtins return a value, but a few have special return
1370 // types, so allow them to override appropriately below.
1371 QualType ResultType = ValType;
1372
Chris Lattnerdc046542009-05-08 06:58:22 +00001373 // We need to figure out which concrete builtin this maps onto. For example,
1374 // __sync_fetch_and_add with a 2 byte object turns into
1375 // __sync_fetch_and_add_2.
1376#define BUILTIN_ROW(x) \
1377 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1378 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00001379
Chris Lattnerdc046542009-05-08 06:58:22 +00001380 static const unsigned BuiltinIndices[][5] = {
1381 BUILTIN_ROW(__sync_fetch_and_add),
1382 BUILTIN_ROW(__sync_fetch_and_sub),
1383 BUILTIN_ROW(__sync_fetch_and_or),
1384 BUILTIN_ROW(__sync_fetch_and_and),
1385 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump11289f42009-09-09 15:08:12 +00001386
Chris Lattnerdc046542009-05-08 06:58:22 +00001387 BUILTIN_ROW(__sync_add_and_fetch),
1388 BUILTIN_ROW(__sync_sub_and_fetch),
1389 BUILTIN_ROW(__sync_and_and_fetch),
1390 BUILTIN_ROW(__sync_or_and_fetch),
1391 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00001392
Chris Lattnerdc046542009-05-08 06:58:22 +00001393 BUILTIN_ROW(__sync_val_compare_and_swap),
1394 BUILTIN_ROW(__sync_bool_compare_and_swap),
1395 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00001396 BUILTIN_ROW(__sync_lock_release),
1397 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00001398 };
Mike Stump11289f42009-09-09 15:08:12 +00001399#undef BUILTIN_ROW
1400
Chris Lattnerdc046542009-05-08 06:58:22 +00001401 // Determine the index of the size.
1402 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00001403 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00001404 case 1: SizeIndex = 0; break;
1405 case 2: SizeIndex = 1; break;
1406 case 4: SizeIndex = 2; break;
1407 case 8: SizeIndex = 3; break;
1408 case 16: SizeIndex = 4; break;
1409 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001410 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1411 << FirstArg->getType() << FirstArg->getSourceRange();
1412 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00001413 }
Mike Stump11289f42009-09-09 15:08:12 +00001414
Chris Lattnerdc046542009-05-08 06:58:22 +00001415 // Each of these builtins has one pointer argument, followed by some number of
1416 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1417 // that we ignore. Find out which row of BuiltinIndices to read from as well
1418 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00001419 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00001420 unsigned BuiltinIndex, NumFixed = 1;
1421 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00001422 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00001423 case Builtin::BI__sync_fetch_and_add:
1424 case Builtin::BI__sync_fetch_and_add_1:
1425 case Builtin::BI__sync_fetch_and_add_2:
1426 case Builtin::BI__sync_fetch_and_add_4:
1427 case Builtin::BI__sync_fetch_and_add_8:
1428 case Builtin::BI__sync_fetch_and_add_16:
1429 BuiltinIndex = 0;
1430 break;
1431
1432 case Builtin::BI__sync_fetch_and_sub:
1433 case Builtin::BI__sync_fetch_and_sub_1:
1434 case Builtin::BI__sync_fetch_and_sub_2:
1435 case Builtin::BI__sync_fetch_and_sub_4:
1436 case Builtin::BI__sync_fetch_and_sub_8:
1437 case Builtin::BI__sync_fetch_and_sub_16:
1438 BuiltinIndex = 1;
1439 break;
1440
1441 case Builtin::BI__sync_fetch_and_or:
1442 case Builtin::BI__sync_fetch_and_or_1:
1443 case Builtin::BI__sync_fetch_and_or_2:
1444 case Builtin::BI__sync_fetch_and_or_4:
1445 case Builtin::BI__sync_fetch_and_or_8:
1446 case Builtin::BI__sync_fetch_and_or_16:
1447 BuiltinIndex = 2;
1448 break;
1449
1450 case Builtin::BI__sync_fetch_and_and:
1451 case Builtin::BI__sync_fetch_and_and_1:
1452 case Builtin::BI__sync_fetch_and_and_2:
1453 case Builtin::BI__sync_fetch_and_and_4:
1454 case Builtin::BI__sync_fetch_and_and_8:
1455 case Builtin::BI__sync_fetch_and_and_16:
1456 BuiltinIndex = 3;
1457 break;
Mike Stump11289f42009-09-09 15:08:12 +00001458
Douglas Gregor73722482011-11-28 16:30:08 +00001459 case Builtin::BI__sync_fetch_and_xor:
1460 case Builtin::BI__sync_fetch_and_xor_1:
1461 case Builtin::BI__sync_fetch_and_xor_2:
1462 case Builtin::BI__sync_fetch_and_xor_4:
1463 case Builtin::BI__sync_fetch_and_xor_8:
1464 case Builtin::BI__sync_fetch_and_xor_16:
1465 BuiltinIndex = 4;
1466 break;
1467
1468 case Builtin::BI__sync_add_and_fetch:
1469 case Builtin::BI__sync_add_and_fetch_1:
1470 case Builtin::BI__sync_add_and_fetch_2:
1471 case Builtin::BI__sync_add_and_fetch_4:
1472 case Builtin::BI__sync_add_and_fetch_8:
1473 case Builtin::BI__sync_add_and_fetch_16:
1474 BuiltinIndex = 5;
1475 break;
1476
1477 case Builtin::BI__sync_sub_and_fetch:
1478 case Builtin::BI__sync_sub_and_fetch_1:
1479 case Builtin::BI__sync_sub_and_fetch_2:
1480 case Builtin::BI__sync_sub_and_fetch_4:
1481 case Builtin::BI__sync_sub_and_fetch_8:
1482 case Builtin::BI__sync_sub_and_fetch_16:
1483 BuiltinIndex = 6;
1484 break;
1485
1486 case Builtin::BI__sync_and_and_fetch:
1487 case Builtin::BI__sync_and_and_fetch_1:
1488 case Builtin::BI__sync_and_and_fetch_2:
1489 case Builtin::BI__sync_and_and_fetch_4:
1490 case Builtin::BI__sync_and_and_fetch_8:
1491 case Builtin::BI__sync_and_and_fetch_16:
1492 BuiltinIndex = 7;
1493 break;
1494
1495 case Builtin::BI__sync_or_and_fetch:
1496 case Builtin::BI__sync_or_and_fetch_1:
1497 case Builtin::BI__sync_or_and_fetch_2:
1498 case Builtin::BI__sync_or_and_fetch_4:
1499 case Builtin::BI__sync_or_and_fetch_8:
1500 case Builtin::BI__sync_or_and_fetch_16:
1501 BuiltinIndex = 8;
1502 break;
1503
1504 case Builtin::BI__sync_xor_and_fetch:
1505 case Builtin::BI__sync_xor_and_fetch_1:
1506 case Builtin::BI__sync_xor_and_fetch_2:
1507 case Builtin::BI__sync_xor_and_fetch_4:
1508 case Builtin::BI__sync_xor_and_fetch_8:
1509 case Builtin::BI__sync_xor_and_fetch_16:
1510 BuiltinIndex = 9;
1511 break;
Mike Stump11289f42009-09-09 15:08:12 +00001512
Chris Lattnerdc046542009-05-08 06:58:22 +00001513 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001514 case Builtin::BI__sync_val_compare_and_swap_1:
1515 case Builtin::BI__sync_val_compare_and_swap_2:
1516 case Builtin::BI__sync_val_compare_and_swap_4:
1517 case Builtin::BI__sync_val_compare_and_swap_8:
1518 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001519 BuiltinIndex = 10;
Chris Lattnerdc046542009-05-08 06:58:22 +00001520 NumFixed = 2;
1521 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001522
Chris Lattnerdc046542009-05-08 06:58:22 +00001523 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001524 case Builtin::BI__sync_bool_compare_and_swap_1:
1525 case Builtin::BI__sync_bool_compare_and_swap_2:
1526 case Builtin::BI__sync_bool_compare_and_swap_4:
1527 case Builtin::BI__sync_bool_compare_and_swap_8:
1528 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001529 BuiltinIndex = 11;
Chris Lattnerdc046542009-05-08 06:58:22 +00001530 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00001531 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001532 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001533
1534 case Builtin::BI__sync_lock_test_and_set:
1535 case Builtin::BI__sync_lock_test_and_set_1:
1536 case Builtin::BI__sync_lock_test_and_set_2:
1537 case Builtin::BI__sync_lock_test_and_set_4:
1538 case Builtin::BI__sync_lock_test_and_set_8:
1539 case Builtin::BI__sync_lock_test_and_set_16:
1540 BuiltinIndex = 12;
1541 break;
1542
Chris Lattnerdc046542009-05-08 06:58:22 +00001543 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00001544 case Builtin::BI__sync_lock_release_1:
1545 case Builtin::BI__sync_lock_release_2:
1546 case Builtin::BI__sync_lock_release_4:
1547 case Builtin::BI__sync_lock_release_8:
1548 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001549 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00001550 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00001551 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001552 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001553
1554 case Builtin::BI__sync_swap:
1555 case Builtin::BI__sync_swap_1:
1556 case Builtin::BI__sync_swap_2:
1557 case Builtin::BI__sync_swap_4:
1558 case Builtin::BI__sync_swap_8:
1559 case Builtin::BI__sync_swap_16:
1560 BuiltinIndex = 14;
1561 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00001562 }
Mike Stump11289f42009-09-09 15:08:12 +00001563
Chris Lattnerdc046542009-05-08 06:58:22 +00001564 // Now that we know how many fixed arguments we expect, first check that we
1565 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001566 if (TheCall->getNumArgs() < 1+NumFixed) {
1567 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1568 << 0 << 1+NumFixed << TheCall->getNumArgs()
1569 << TheCall->getCallee()->getSourceRange();
1570 return ExprError();
1571 }
Mike Stump11289f42009-09-09 15:08:12 +00001572
Chris Lattner5b9241b2009-05-08 15:36:58 +00001573 // Get the decl for the concrete builtin from this, we can tell what the
1574 // concrete integer type we should convert to is.
1575 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1576 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001577 FunctionDecl *NewBuiltinDecl;
1578 if (NewBuiltinID == BuiltinID)
1579 NewBuiltinDecl = FDecl;
1580 else {
1581 // Perform builtin lookup to avoid redeclaring it.
1582 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1583 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1584 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1585 assert(Res.getFoundDecl());
1586 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00001587 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001588 return ExprError();
1589 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001590
John McCallcf142162010-08-07 06:22:56 +00001591 // The first argument --- the pointer --- has a fixed type; we
1592 // deduce the types of the rest of the arguments accordingly. Walk
1593 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00001594 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00001595 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00001596
Chris Lattnerdc046542009-05-08 06:58:22 +00001597 // GCC does an implicit conversion to the pointer or integer ValType. This
1598 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00001599 // Initialize the argument.
1600 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1601 ValType, /*consume*/ false);
1602 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00001603 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001604 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001605
Chris Lattnerdc046542009-05-08 06:58:22 +00001606 // Okay, we have something that *can* be converted to the right type. Check
1607 // to see if there is a potentially weird extension going on here. This can
1608 // happen when you do an atomic operation on something like an char* and
1609 // pass in 42. The 42 gets converted to char. This is even more strange
1610 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00001611 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001612 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00001613 }
Mike Stump11289f42009-09-09 15:08:12 +00001614
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001615 ASTContext& Context = this->getASTContext();
1616
1617 // Create a new DeclRefExpr to refer to the new decl.
1618 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1619 Context,
1620 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001621 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001622 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00001623 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001624 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00001625 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001626 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00001627
Chris Lattnerdc046542009-05-08 06:58:22 +00001628 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00001629 // FIXME: This loses syntactic information.
1630 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1631 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1632 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001633 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00001634
Chandler Carruthbc8cab12010-07-18 07:23:17 +00001635 // Change the result type of the call to match the original value type. This
1636 // is arbitrary, but the codegen for these builtins ins design to handle it
1637 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00001638 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001639
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001640 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00001641}
1642
Chris Lattner6436fb62009-02-18 06:01:06 +00001643/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00001644/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00001645/// Note: It might also make sense to do the UTF-16 conversion here (would
1646/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00001647bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00001648 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00001649 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1650
Douglas Gregorfb65e592011-07-27 05:40:30 +00001651 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00001652 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1653 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00001654 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00001655 }
Mike Stump11289f42009-09-09 15:08:12 +00001656
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001657 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001658 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001659 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001660 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00001661 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001662 UTF16 *ToPtr = &ToBuf[0];
1663
1664 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1665 &ToPtr, ToPtr + NumBytes,
1666 strictConversion);
1667 // Check for conversion failure.
1668 if (Result != conversionOK)
1669 Diag(Arg->getLocStart(),
1670 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1671 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00001672 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001673}
1674
Chris Lattnere202e6a2007-12-20 00:05:45 +00001675/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1676/// Emit an error and return true on failure, return false on success.
Chris Lattner08464942007-12-28 05:29:59 +00001677bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1678 Expr *Fn = TheCall->getCallee();
1679 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00001680 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001681 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001682 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1683 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00001684 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001685 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00001686 return true;
1687 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00001688
1689 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00001690 return Diag(TheCall->getLocEnd(),
1691 diag::err_typecheck_call_too_few_args_at_least)
1692 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00001693 }
1694
John McCall29ad95b2011-08-27 01:09:30 +00001695 // Type-check the first argument normally.
1696 if (checkBuiltinArgument(*this, TheCall, 0))
1697 return true;
1698
Chris Lattnere202e6a2007-12-20 00:05:45 +00001699 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00001700 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00001701 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00001702 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00001703 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00001704 else if (FunctionDecl *FD = getCurFunctionDecl())
1705 isVariadic = FD->isVariadic();
1706 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001707 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00001708
Chris Lattnere202e6a2007-12-20 00:05:45 +00001709 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00001710 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1711 return true;
1712 }
Mike Stump11289f42009-09-09 15:08:12 +00001713
Chris Lattner43be2e62007-12-19 23:59:04 +00001714 // Verify that the second argument to the builtin is the last argument of the
1715 // current function or method.
1716 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00001717 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00001718
Nico Weber9eea7642013-05-24 23:31:57 +00001719 // These are valid if SecondArgIsLastNamedArgument is false after the next
1720 // block.
1721 QualType Type;
1722 SourceLocation ParamLoc;
1723
Anders Carlsson6a8350b2008-02-11 04:20:54 +00001724 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1725 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00001726 // FIXME: This isn't correct for methods (results in bogus warning).
1727 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00001728 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00001729 if (CurBlock)
1730 LastArg = *(CurBlock->TheDecl->param_end()-1);
1731 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00001732 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00001733 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001734 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00001735 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00001736
1737 Type = PV->getType();
1738 ParamLoc = PV->getLocation();
Chris Lattner43be2e62007-12-19 23:59:04 +00001739 }
1740 }
Mike Stump11289f42009-09-09 15:08:12 +00001741
Chris Lattner43be2e62007-12-19 23:59:04 +00001742 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001743 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +00001744 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weber9eea7642013-05-24 23:31:57 +00001745 else if (Type->isReferenceType()) {
1746 Diag(Arg->getLocStart(),
1747 diag::warn_va_start_of_reference_type_is_undefined);
1748 Diag(ParamLoc, diag::note_parameter_type) << Type;
1749 }
1750
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00001751 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00001752 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00001753}
Chris Lattner43be2e62007-12-19 23:59:04 +00001754
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00001755bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
1756 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
1757 // const char *named_addr);
1758
1759 Expr *Func = Call->getCallee();
1760
1761 if (Call->getNumArgs() < 3)
1762 return Diag(Call->getLocEnd(),
1763 diag::err_typecheck_call_too_few_args_at_least)
1764 << 0 /*function call*/ << 3 << Call->getNumArgs();
1765
1766 // Determine whether the current function is variadic or not.
1767 bool IsVariadic;
1768 if (BlockScopeInfo *CurBlock = getCurBlock())
1769 IsVariadic = CurBlock->TheDecl->isVariadic();
1770 else if (FunctionDecl *FD = getCurFunctionDecl())
1771 IsVariadic = FD->isVariadic();
1772 else if (ObjCMethodDecl *MD = getCurMethodDecl())
1773 IsVariadic = MD->isVariadic();
1774 else
1775 llvm_unreachable("unexpected statement type");
1776
1777 if (!IsVariadic) {
1778 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1779 return true;
1780 }
1781
1782 // Type-check the first argument normally.
1783 if (checkBuiltinArgument(*this, Call, 0))
1784 return true;
1785
1786 static const struct {
1787 unsigned ArgNo;
1788 QualType Type;
1789 } ArgumentTypes[] = {
1790 { 1, Context.getPointerType(Context.CharTy.withConst()) },
1791 { 2, Context.getSizeType() },
1792 };
1793
1794 for (const auto &AT : ArgumentTypes) {
1795 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
1796 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
1797 continue;
1798 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
1799 << Arg->getType() << AT.Type << 1 /* different class */
1800 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
1801 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
1802 }
1803
1804 return false;
1805}
1806
Chris Lattner2da14fb2007-12-20 00:26:33 +00001807/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1808/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00001809bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1810 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00001811 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00001812 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00001813 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00001814 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001815 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001816 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00001817 << SourceRange(TheCall->getArg(2)->getLocStart(),
1818 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00001819
John Wiegley01296292011-04-08 18:41:53 +00001820 ExprResult OrigArg0 = TheCall->getArg(0);
1821 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00001822
Chris Lattner2da14fb2007-12-20 00:26:33 +00001823 // Do standard promotions between the two arguments, returning their common
1824 // type.
Chris Lattner08464942007-12-28 05:29:59 +00001825 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00001826 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1827 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00001828
1829 // Make sure any conversions are pushed back into the call; this is
1830 // type safe since unordered compare builtins are declared as "_Bool
1831 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00001832 TheCall->setArg(0, OrigArg0.get());
1833 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00001834
John Wiegley01296292011-04-08 18:41:53 +00001835 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00001836 return false;
1837
Chris Lattner2da14fb2007-12-20 00:26:33 +00001838 // If the common type isn't a real floating type, then the arguments were
1839 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00001840 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00001841 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001842 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00001843 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1844 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00001845
Chris Lattner2da14fb2007-12-20 00:26:33 +00001846 return false;
1847}
1848
Benjamin Kramer634fc102010-02-15 22:42:31 +00001849/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1850/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00001851/// to check everything. We expect the last argument to be a floating point
1852/// value.
1853bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1854 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00001855 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00001856 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00001857 if (TheCall->getNumArgs() > NumArgs)
1858 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001859 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001860 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00001861 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001862 (*(TheCall->arg_end()-1))->getLocEnd());
1863
Benjamin Kramer64aae502010-02-16 10:07:31 +00001864 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00001865
Eli Friedman7e4faac2009-08-31 20:06:00 +00001866 if (OrigArg->isTypeDependent())
1867 return false;
1868
Chris Lattner68784ef2010-05-06 05:50:07 +00001869 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00001870 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00001871 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001872 diag::err_typecheck_call_invalid_unary_fp)
1873 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001874
Chris Lattner68784ef2010-05-06 05:50:07 +00001875 // If this is an implicit conversion from float -> double, remove it.
1876 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1877 Expr *CastArg = Cast->getSubExpr();
1878 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1879 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1880 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00001881 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00001882 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00001883 }
1884 }
1885
Eli Friedman7e4faac2009-08-31 20:06:00 +00001886 return false;
1887}
1888
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001889/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1890// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00001891ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00001892 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001893 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00001894 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00001895 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1896 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001897
Nate Begemana0110022010-06-08 00:16:34 +00001898 // Determine which of the following types of shufflevector we're checking:
1899 // 1) unary, vector mask: (lhs, mask)
1900 // 2) binary, vector mask: (lhs, rhs, mask)
1901 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1902 QualType resType = TheCall->getArg(0)->getType();
1903 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00001904
Douglas Gregorc25f7662009-05-19 22:10:17 +00001905 if (!TheCall->getArg(0)->isTypeDependent() &&
1906 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00001907 QualType LHSType = TheCall->getArg(0)->getType();
1908 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00001909
Craig Topperbaca3892013-07-29 06:47:04 +00001910 if (!LHSType->isVectorType() || !RHSType->isVectorType())
1911 return ExprError(Diag(TheCall->getLocStart(),
1912 diag::err_shufflevector_non_vector)
1913 << SourceRange(TheCall->getArg(0)->getLocStart(),
1914 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00001915
Nate Begemana0110022010-06-08 00:16:34 +00001916 numElements = LHSType->getAs<VectorType>()->getNumElements();
1917 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00001918
Nate Begemana0110022010-06-08 00:16:34 +00001919 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1920 // with mask. If so, verify that RHS is an integer vector type with the
1921 // same number of elts as lhs.
1922 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00001923 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00001924 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00001925 return ExprError(Diag(TheCall->getLocStart(),
1926 diag::err_shufflevector_incompatible_vector)
1927 << SourceRange(TheCall->getArg(1)->getLocStart(),
1928 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00001929 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00001930 return ExprError(Diag(TheCall->getLocStart(),
1931 diag::err_shufflevector_incompatible_vector)
1932 << SourceRange(TheCall->getArg(0)->getLocStart(),
1933 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00001934 } else if (numElements != numResElements) {
1935 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00001936 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001937 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00001938 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001939 }
1940
1941 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00001942 if (TheCall->getArg(i)->isTypeDependent() ||
1943 TheCall->getArg(i)->isValueDependent())
1944 continue;
1945
Nate Begemana0110022010-06-08 00:16:34 +00001946 llvm::APSInt Result(32);
1947 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1948 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00001949 diag::err_shufflevector_nonconstant_argument)
1950 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001951
Craig Topper50ad5b72013-08-03 17:40:38 +00001952 // Allow -1 which will be translated to undef in the IR.
1953 if (Result.isSigned() && Result.isAllOnesValue())
1954 continue;
1955
Chris Lattner7ab824e2008-08-10 02:05:13 +00001956 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001957 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00001958 diag::err_shufflevector_argument_too_large)
1959 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001960 }
1961
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001962 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001963
Chris Lattner7ab824e2008-08-10 02:05:13 +00001964 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001965 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00001966 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001967 }
1968
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001969 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
1970 TheCall->getCallee()->getLocStart(),
1971 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001972}
Chris Lattner43be2e62007-12-19 23:59:04 +00001973
Hal Finkelc4d7c822013-09-18 03:29:45 +00001974/// SemaConvertVectorExpr - Handle __builtin_convertvector
1975ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
1976 SourceLocation BuiltinLoc,
1977 SourceLocation RParenLoc) {
1978 ExprValueKind VK = VK_RValue;
1979 ExprObjectKind OK = OK_Ordinary;
1980 QualType DstTy = TInfo->getType();
1981 QualType SrcTy = E->getType();
1982
1983 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
1984 return ExprError(Diag(BuiltinLoc,
1985 diag::err_convertvector_non_vector)
1986 << E->getSourceRange());
1987 if (!DstTy->isVectorType() && !DstTy->isDependentType())
1988 return ExprError(Diag(BuiltinLoc,
1989 diag::err_convertvector_non_vector_type));
1990
1991 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
1992 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
1993 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
1994 if (SrcElts != DstElts)
1995 return ExprError(Diag(BuiltinLoc,
1996 diag::err_convertvector_incompatible_vector)
1997 << E->getSourceRange());
1998 }
1999
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002000 return new (Context)
2001 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00002002}
2003
Daniel Dunbarb7257262008-07-21 22:59:13 +00002004/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
2005// This is declared to take (const void*, ...) and can take two
2006// optional constant int args.
2007bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00002008 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002009
Chris Lattner3b054132008-11-19 05:08:23 +00002010 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002011 return Diag(TheCall->getLocEnd(),
2012 diag::err_typecheck_call_too_many_args_at_most)
2013 << 0 /*function call*/ << 3 << NumArgs
2014 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002015
2016 // Argument 0 is checked for us and the remaining arguments must be
2017 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00002018 for (unsigned i = 1; i != NumArgs; ++i)
2019 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002020 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002021
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002022 return false;
2023}
2024
Hal Finkelf0417332014-07-17 14:25:55 +00002025/// SemaBuiltinAssume - Handle __assume (MS Extension).
2026// __assume does not evaluate its arguments, and should warn if its argument
2027// has side effects.
2028bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
2029 Expr *Arg = TheCall->getArg(0);
2030 if (Arg->isInstantiationDependent()) return false;
2031
2032 if (Arg->HasSideEffects(Context))
2033 return Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
2034 << Arg->getSourceRange();
2035
2036 return false;
2037}
2038
Eric Christopher8d0c6212010-04-17 02:26:23 +00002039/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2040/// TheCall is a constant expression.
2041bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
2042 llvm::APSInt &Result) {
2043 Expr *Arg = TheCall->getArg(ArgNum);
2044 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2045 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2046
2047 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
2048
2049 if (!Arg->isIntegerConstantExpr(Result, Context))
2050 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00002051 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00002052
Chris Lattnerd545ad12009-09-23 06:06:36 +00002053 return false;
2054}
2055
Richard Sandiford28940af2014-04-16 08:47:51 +00002056/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
2057/// TheCall is a constant expression in the range [Low, High].
2058bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
2059 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00002060 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002061
2062 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00002063 Expr *Arg = TheCall->getArg(ArgNum);
2064 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002065 return false;
2066
Eric Christopher8d0c6212010-04-17 02:26:23 +00002067 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00002068 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002069 return true;
2070
Richard Sandiford28940af2014-04-16 08:47:51 +00002071 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00002072 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00002073 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00002074
2075 return false;
2076}
2077
Eli Friedmanc97d0142009-05-03 06:04:26 +00002078/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002079/// This checks that val is a constant 1.
2080bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
2081 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00002082 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00002083
Eric Christopher8d0c6212010-04-17 02:26:23 +00002084 // TODO: This is less than ideal. Overload this to take a value.
2085 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2086 return true;
2087
2088 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002089 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
2090 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
2091
2092 return false;
2093}
2094
Richard Smithd7293d72013-08-05 18:49:43 +00002095namespace {
2096enum StringLiteralCheckType {
2097 SLCT_NotALiteral,
2098 SLCT_UncheckedLiteral,
2099 SLCT_CheckedLiteral
2100};
2101}
2102
Richard Smith55ce3522012-06-25 20:30:08 +00002103// Determine if an expression is a string literal or constant string.
2104// If this function returns false on the arguments to a function expecting a
2105// format string, we will usually need to emit a warning.
2106// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00002107static StringLiteralCheckType
2108checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
2109 bool HasVAListArg, unsigned format_idx,
2110 unsigned firstDataArg, Sema::FormatStringType Type,
2111 Sema::VariadicCallType CallType, bool InFunctionCall,
2112 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek808829352010-09-09 03:51:39 +00002113 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00002114 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00002115 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002116
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002117 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00002118
Richard Smithd7293d72013-08-05 18:49:43 +00002119 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00002120 // Technically -Wformat-nonliteral does not warn about this case.
2121 // The behavior of printf and friends in this case is implementation
2122 // dependent. Ideally if the format string cannot be null then
2123 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00002124 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00002125
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002126 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00002127 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002128 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00002129 // The expression is a literal if both sub-expressions were, and it was
2130 // completely checked only if both sub-expressions were checked.
2131 const AbstractConditionalOperator *C =
2132 cast<AbstractConditionalOperator>(E);
2133 StringLiteralCheckType Left =
Richard Smithd7293d72013-08-05 18:49:43 +00002134 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002135 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002136 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002137 if (Left == SLCT_NotALiteral)
2138 return SLCT_NotALiteral;
2139 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00002140 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002141 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002142 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002143 return Left < Right ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002144 }
2145
2146 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00002147 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2148 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002149 }
2150
John McCallc07a0c72011-02-17 10:25:35 +00002151 case Stmt::OpaqueValueExprClass:
2152 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2153 E = src;
2154 goto tryAgain;
2155 }
Richard Smith55ce3522012-06-25 20:30:08 +00002156 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00002157
Ted Kremeneka8890832011-02-24 23:03:04 +00002158 case Stmt::PredefinedExprClass:
2159 // While __func__, etc., are technically not string literals, they
2160 // cannot contain format specifiers and thus are not a security
2161 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00002162 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00002163
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002164 case Stmt::DeclRefExprClass: {
2165 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002166
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002167 // As an exception, do not flag errors for variables binding to
2168 // const string literals.
2169 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2170 bool isConstant = false;
2171 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002172
Richard Smithd7293d72013-08-05 18:49:43 +00002173 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2174 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00002175 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00002176 isConstant = T.isConstant(S.Context) &&
2177 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00002178 } else if (T->isObjCObjectPointerType()) {
2179 // In ObjC, there is usually no "const ObjectPointer" type,
2180 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00002181 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002182 }
Mike Stump11289f42009-09-09 15:08:12 +00002183
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002184 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002185 if (const Expr *Init = VD->getAnyInitializer()) {
2186 // Look through initializers like const char c[] = { "foo" }
2187 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2188 if (InitList->isStringLiteralInit())
2189 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2190 }
Richard Smithd7293d72013-08-05 18:49:43 +00002191 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002192 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002193 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002194 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002195 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002196 }
Mike Stump11289f42009-09-09 15:08:12 +00002197
Anders Carlssonb012ca92009-06-28 19:55:58 +00002198 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2199 // special check to see if the format string is a function parameter
2200 // of the function calling the printf function. If the function
2201 // has an attribute indicating it is a printf-like function, then we
2202 // should suppress warnings concerning non-literals being used in a call
2203 // to a vprintf function. For example:
2204 //
2205 // void
2206 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2207 // va_list ap;
2208 // va_start(ap, fmt);
2209 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2210 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00002211 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002212 if (HasVAListArg) {
2213 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2214 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2215 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002216 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002217 // adjust for implicit parameter
2218 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2219 if (MD->isInstance())
2220 ++PVIndex;
2221 // We also check if the formats are compatible.
2222 // We can't pass a 'scanf' string to a 'printf' function.
2223 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00002224 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00002225 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002226 }
2227 }
2228 }
2229 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002230 }
Mike Stump11289f42009-09-09 15:08:12 +00002231
Richard Smith55ce3522012-06-25 20:30:08 +00002232 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002233 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002234
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002235 case Stmt::CallExprClass:
2236 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002237 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002238 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2239 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2240 unsigned ArgIndex = FA->getFormatIdx();
2241 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2242 if (MD->isInstance())
2243 --ArgIndex;
2244 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00002245
Richard Smithd7293d72013-08-05 18:49:43 +00002246 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002247 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002248 Type, CallType, InFunctionCall,
2249 CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002250 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2251 unsigned BuiltinID = FD->getBuiltinID();
2252 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2253 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2254 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00002255 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002256 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002257 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002258 InFunctionCall, CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002259 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002260 }
2261 }
Mike Stump11289f42009-09-09 15:08:12 +00002262
Richard Smith55ce3522012-06-25 20:30:08 +00002263 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002264 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002265 case Stmt::ObjCStringLiteralClass:
2266 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00002267 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002268
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002269 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002270 StrE = ObjCFExpr->getString();
2271 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002272 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002273
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002274 if (StrE) {
Richard Smithd7293d72013-08-05 18:49:43 +00002275 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2276 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002277 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002278 }
Mike Stump11289f42009-09-09 15:08:12 +00002279
Richard Smith55ce3522012-06-25 20:30:08 +00002280 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002281 }
Mike Stump11289f42009-09-09 15:08:12 +00002282
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002283 default:
Richard Smith55ce3522012-06-25 20:30:08 +00002284 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002285 }
2286}
2287
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002288Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00002289 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002290 .Case("scanf", FST_Scanf)
2291 .Cases("printf", "printf0", FST_Printf)
2292 .Cases("NSString", "CFString", FST_NSString)
2293 .Case("strftime", FST_Strftime)
2294 .Case("strfmon", FST_Strfmon)
2295 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
2296 .Default(FST_Unknown);
2297}
2298
Jordan Rose3e0ec582012-07-19 18:10:23 +00002299/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00002300/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002301/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002302bool Sema::CheckFormatArguments(const FormatAttr *Format,
2303 ArrayRef<const Expr *> Args,
2304 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002305 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002306 SourceLocation Loc, SourceRange Range,
2307 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00002308 FormatStringInfo FSI;
2309 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002310 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00002311 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00002312 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002313 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002314}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00002315
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002316bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002317 bool HasVAListArg, unsigned format_idx,
2318 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002319 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002320 SourceLocation Loc, SourceRange Range,
2321 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00002322 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002323 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002324 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00002325 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002326 }
Mike Stump11289f42009-09-09 15:08:12 +00002327
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002328 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002329
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002330 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00002331 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002332 // Dynamically generated format strings are difficult to
2333 // automatically vet at compile time. Requiring that format strings
2334 // are string literals: (1) permits the checking of format strings by
2335 // the compiler and thereby (2) can practically remove the source of
2336 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00002337
Mike Stump11289f42009-09-09 15:08:12 +00002338 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00002339 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00002340 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00002341 // the same format string checking logic for both ObjC and C strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002342 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00002343 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2344 format_idx, firstDataArg, Type, CallType,
2345 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002346 if (CT != SLCT_NotALiteral)
2347 // Literal format string found, check done!
2348 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00002349
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002350 // Strftime is particular as it always uses a single 'time' argument,
2351 // so it is safe to pass a non-literal string.
2352 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00002353 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002354
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002355 // Do not emit diag when the string param is a macro expansion and the
2356 // format is either NSString or CFString. This is a hack to prevent
2357 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2358 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupas2b7da832012-05-04 21:08:08 +00002359 if (Type == FST_NSString &&
2360 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith55ce3522012-06-25 20:30:08 +00002361 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002362
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002363 // If there are no arguments specified, warn with -Wformat-security, otherwise
2364 // warn only with -Wformat-nonliteral.
Eli Friedman0e5d6772013-06-18 18:10:01 +00002365 if (Args.size() == firstDataArg)
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002366 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002367 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002368 << OrigFormatExpr->getSourceRange();
2369 else
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002370 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002371 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002372 << OrigFormatExpr->getSourceRange();
Richard Smith55ce3522012-06-25 20:30:08 +00002373 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002374}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002375
Ted Kremenekab278de2010-01-28 23:39:18 +00002376namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00002377class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2378protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00002379 Sema &S;
2380 const StringLiteral *FExpr;
2381 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002382 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00002383 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00002384 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00002385 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002386 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00002387 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00002388 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00002389 bool usesPositionalArgs;
2390 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00002391 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00002392 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00002393 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002394public:
Ted Kremenek02087932010-07-16 02:11:22 +00002395 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002396 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002397 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002398 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002399 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002400 Sema::VariadicCallType callType,
2401 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremenekab278de2010-01-28 23:39:18 +00002402 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002403 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2404 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002405 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00002406 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00002407 inFunctionCall(inFunctionCall), CallType(callType),
2408 CheckedVarArgs(CheckedVarArgs) {
2409 CoveredArgs.resize(numDataArgs);
2410 CoveredArgs.reset();
2411 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002412
Ted Kremenek019d2242010-01-29 01:50:07 +00002413 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002414
Ted Kremenek02087932010-07-16 02:11:22 +00002415 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002416 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002417
Jordan Rose92303592012-09-08 04:00:03 +00002418 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002419 const analyze_format_string::FormatSpecifier &FS,
2420 const analyze_format_string::ConversionSpecifier &CS,
2421 const char *startSpecifier, unsigned specifierLen,
2422 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00002423
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002424 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002425 const analyze_format_string::FormatSpecifier &FS,
2426 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002427
2428 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002429 const analyze_format_string::ConversionSpecifier &CS,
2430 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002431
Craig Toppere14c0f82014-03-12 04:55:44 +00002432 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002433
Craig Toppere14c0f82014-03-12 04:55:44 +00002434 void HandleInvalidPosition(const char *startSpecifier,
2435 unsigned specifierLen,
2436 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002437
Craig Toppere14c0f82014-03-12 04:55:44 +00002438 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002439
Craig Toppere14c0f82014-03-12 04:55:44 +00002440 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002441
Richard Trieu03cf7b72011-10-28 00:41:25 +00002442 template <typename Range>
2443 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2444 const Expr *ArgumentExpr,
2445 PartialDiagnostic PDiag,
2446 SourceLocation StringLoc,
2447 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002448 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002449
Ted Kremenek02087932010-07-16 02:11:22 +00002450protected:
Ted Kremenekce815422010-07-19 21:25:57 +00002451 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2452 const char *startSpec,
2453 unsigned specifierLen,
2454 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002455
2456 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2457 const char *startSpec,
2458 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00002459
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002460 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00002461 CharSourceRange getSpecifierRange(const char *startSpecifier,
2462 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00002463 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002464
Ted Kremenek5739de72010-01-29 01:06:55 +00002465 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002466
2467 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2468 const analyze_format_string::ConversionSpecifier &CS,
2469 const char *startSpecifier, unsigned specifierLen,
2470 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002471
2472 template <typename Range>
2473 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2474 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002475 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00002476};
2477}
2478
Ted Kremenek02087932010-07-16 02:11:22 +00002479SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00002480 return OrigFormatExpr->getSourceRange();
2481}
2482
Ted Kremenek02087932010-07-16 02:11:22 +00002483CharSourceRange CheckFormatHandler::
2484getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00002485 SourceLocation Start = getLocationOfByte(startSpecifier);
2486 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2487
2488 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002489 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00002490
2491 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002492}
2493
Ted Kremenek02087932010-07-16 02:11:22 +00002494SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002495 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00002496}
2497
Ted Kremenek02087932010-07-16 02:11:22 +00002498void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2499 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00002500 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2501 getLocationOfByte(startSpecifier),
2502 /*IsStringLocation*/true,
2503 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00002504}
2505
Jordan Rose92303592012-09-08 04:00:03 +00002506void CheckFormatHandler::HandleInvalidLengthModifier(
2507 const analyze_format_string::FormatSpecifier &FS,
2508 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00002509 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00002510 using namespace analyze_format_string;
2511
2512 const LengthModifier &LM = FS.getLengthModifier();
2513 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2514
2515 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002516 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00002517 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002518 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002519 getLocationOfByte(LM.getStart()),
2520 /*IsStringLocation*/true,
2521 getSpecifierRange(startSpecifier, specifierLen));
2522
2523 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2524 << FixedLM->toString()
2525 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2526
2527 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002528 FixItHint Hint;
2529 if (DiagID == diag::warn_format_nonsensical_length)
2530 Hint = FixItHint::CreateRemoval(LMRange);
2531
2532 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002533 getLocationOfByte(LM.getStart()),
2534 /*IsStringLocation*/true,
2535 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00002536 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00002537 }
2538}
2539
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002540void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00002541 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002542 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002543 using namespace analyze_format_string;
2544
2545 const LengthModifier &LM = FS.getLengthModifier();
2546 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2547
2548 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002549 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00002550 if (FixedLM) {
2551 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2552 << LM.toString() << 0,
2553 getLocationOfByte(LM.getStart()),
2554 /*IsStringLocation*/true,
2555 getSpecifierRange(startSpecifier, specifierLen));
2556
2557 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2558 << FixedLM->toString()
2559 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2560
2561 } else {
2562 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2563 << LM.toString() << 0,
2564 getLocationOfByte(LM.getStart()),
2565 /*IsStringLocation*/true,
2566 getSpecifierRange(startSpecifier, specifierLen));
2567 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002568}
2569
2570void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2571 const analyze_format_string::ConversionSpecifier &CS,
2572 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00002573 using namespace analyze_format_string;
2574
2575 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00002576 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00002577 if (FixedCS) {
2578 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2579 << CS.toString() << /*conversion specifier*/1,
2580 getLocationOfByte(CS.getStart()),
2581 /*IsStringLocation*/true,
2582 getSpecifierRange(startSpecifier, specifierLen));
2583
2584 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2585 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2586 << FixedCS->toString()
2587 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2588 } else {
2589 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2590 << CS.toString() << /*conversion specifier*/1,
2591 getLocationOfByte(CS.getStart()),
2592 /*IsStringLocation*/true,
2593 getSpecifierRange(startSpecifier, specifierLen));
2594 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002595}
2596
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002597void CheckFormatHandler::HandlePosition(const char *startPos,
2598 unsigned posLen) {
2599 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2600 getLocationOfByte(startPos),
2601 /*IsStringLocation*/true,
2602 getSpecifierRange(startPos, posLen));
2603}
2604
Ted Kremenekd1668192010-02-27 01:41:03 +00002605void
Ted Kremenek02087932010-07-16 02:11:22 +00002606CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2607 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002608 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2609 << (unsigned) p,
2610 getLocationOfByte(startPos), /*IsStringLocation*/true,
2611 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00002612}
2613
Ted Kremenek02087932010-07-16 02:11:22 +00002614void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00002615 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002616 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2617 getLocationOfByte(startPos),
2618 /*IsStringLocation*/true,
2619 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00002620}
2621
Ted Kremenek02087932010-07-16 02:11:22 +00002622void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002623 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00002624 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002625 EmitFormatDiagnostic(
2626 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2627 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2628 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00002629 }
Ted Kremenek02087932010-07-16 02:11:22 +00002630}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002631
Jordan Rose58bbe422012-07-19 18:10:08 +00002632// Note that this may return NULL if there was an error parsing or building
2633// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00002634const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002635 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00002636}
2637
2638void CheckFormatHandler::DoneProcessing() {
2639 // Does the number of data arguments exceed the number of
2640 // format conversions in the format string?
2641 if (!HasVAListArg) {
2642 // Find any arguments that weren't covered.
2643 CoveredArgs.flip();
2644 signed notCoveredArg = CoveredArgs.find_first();
2645 if (notCoveredArg >= 0) {
2646 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose58bbe422012-07-19 18:10:08 +00002647 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2648 SourceLocation Loc = E->getLocStart();
2649 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2650 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2651 Loc, /*IsStringLocation*/false,
2652 getFormatStringRange());
2653 }
Bob Wilson23cd4342012-05-03 19:47:19 +00002654 }
Ted Kremenek02087932010-07-16 02:11:22 +00002655 }
2656 }
2657}
2658
Ted Kremenekce815422010-07-19 21:25:57 +00002659bool
2660CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2661 SourceLocation Loc,
2662 const char *startSpec,
2663 unsigned specifierLen,
2664 const char *csStart,
2665 unsigned csLen) {
2666
2667 bool keepGoing = true;
2668 if (argIndex < NumDataArgs) {
2669 // Consider the argument coverered, even though the specifier doesn't
2670 // make sense.
2671 CoveredArgs.set(argIndex);
2672 }
2673 else {
2674 // If argIndex exceeds the number of data arguments we
2675 // don't issue a warning because that is just a cascade of warnings (and
2676 // they may have intended '%%' anyway). We don't want to continue processing
2677 // the format string after this point, however, as we will like just get
2678 // gibberish when trying to match arguments.
2679 keepGoing = false;
2680 }
2681
Richard Trieu03cf7b72011-10-28 00:41:25 +00002682 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2683 << StringRef(csStart, csLen),
2684 Loc, /*IsStringLocation*/true,
2685 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekce815422010-07-19 21:25:57 +00002686
2687 return keepGoing;
2688}
2689
Richard Trieu03cf7b72011-10-28 00:41:25 +00002690void
2691CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2692 const char *startSpec,
2693 unsigned specifierLen) {
2694 EmitFormatDiagnostic(
2695 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2696 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2697}
2698
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002699bool
2700CheckFormatHandler::CheckNumArgs(
2701 const analyze_format_string::FormatSpecifier &FS,
2702 const analyze_format_string::ConversionSpecifier &CS,
2703 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2704
2705 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002706 PartialDiagnostic PDiag = FS.usesPositionalArg()
2707 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2708 << (argIndex+1) << NumDataArgs)
2709 : S.PDiag(diag::warn_printf_insufficient_data_args);
2710 EmitFormatDiagnostic(
2711 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2712 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002713 return false;
2714 }
2715 return true;
2716}
2717
Richard Trieu03cf7b72011-10-28 00:41:25 +00002718template<typename Range>
2719void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2720 SourceLocation Loc,
2721 bool IsStringLocation,
2722 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00002723 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002724 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00002725 Loc, IsStringLocation, StringRange, FixIt);
2726}
2727
2728/// \brief If the format string is not within the funcion call, emit a note
2729/// so that the function call and string are in diagnostic messages.
2730///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002731/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00002732/// call and only one diagnostic message will be produced. Otherwise, an
2733/// extra note will be emitted pointing to location of the format string.
2734///
2735/// \param ArgumentExpr the expression that is passed as the format string
2736/// argument in the function call. Used for getting locations when two
2737/// diagnostics are emitted.
2738///
2739/// \param PDiag the callee should already have provided any strings for the
2740/// diagnostic message. This function only adds locations and fixits
2741/// to diagnostics.
2742///
2743/// \param Loc primary location for diagnostic. If two diagnostics are
2744/// required, one will be at Loc and a new SourceLocation will be created for
2745/// the other one.
2746///
2747/// \param IsStringLocation if true, Loc points to the format string should be
2748/// used for the note. Otherwise, Loc points to the argument list and will
2749/// be used with PDiag.
2750///
2751/// \param StringRange some or all of the string to highlight. This is
2752/// templated so it can accept either a CharSourceRange or a SourceRange.
2753///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002754/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002755template<typename Range>
2756void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2757 const Expr *ArgumentExpr,
2758 PartialDiagnostic PDiag,
2759 SourceLocation Loc,
2760 bool IsStringLocation,
2761 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00002762 ArrayRef<FixItHint> FixIt) {
2763 if (InFunctionCall) {
2764 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2765 D << StringRange;
2766 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2767 I != E; ++I) {
2768 D << *I;
2769 }
2770 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002771 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2772 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00002773
2774 const Sema::SemaDiagnosticBuilder &Note =
2775 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2776 diag::note_format_string_defined);
2777
2778 Note << StringRange;
2779 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2780 I != E; ++I) {
2781 Note << *I;
2782 }
Richard Trieu03cf7b72011-10-28 00:41:25 +00002783 }
2784}
2785
Ted Kremenek02087932010-07-16 02:11:22 +00002786//===--- CHECK: Printf format string checking ------------------------------===//
2787
2788namespace {
2789class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002790 bool ObjCContext;
Ted Kremenek02087932010-07-16 02:11:22 +00002791public:
2792 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2793 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002794 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00002795 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002796 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002797 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002798 Sema::VariadicCallType CallType,
2799 llvm::SmallBitVector &CheckedVarArgs)
2800 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2801 numDataArgs, beg, hasVAListArg, Args,
2802 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
2803 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00002804 {}
2805
Craig Toppere14c0f82014-03-12 04:55:44 +00002806
Ted Kremenek02087932010-07-16 02:11:22 +00002807 bool HandleInvalidPrintfConversionSpecifier(
2808 const analyze_printf::PrintfSpecifier &FS,
2809 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002810 unsigned specifierLen) override;
2811
Ted Kremenek02087932010-07-16 02:11:22 +00002812 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2813 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002814 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00002815 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2816 const char *StartSpecifier,
2817 unsigned SpecifierLen,
2818 const Expr *E);
2819
Ted Kremenek02087932010-07-16 02:11:22 +00002820 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2821 const char *startSpecifier, unsigned specifierLen);
2822 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2823 const analyze_printf::OptionalAmount &Amt,
2824 unsigned type,
2825 const char *startSpecifier, unsigned specifierLen);
2826 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2827 const analyze_printf::OptionalFlag &flag,
2828 const char *startSpecifier, unsigned specifierLen);
2829 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2830 const analyze_printf::OptionalFlag &ignoredFlag,
2831 const analyze_printf::OptionalFlag &flag,
2832 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002833 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00002834 const Expr *E);
Richard Smith55ce3522012-06-25 20:30:08 +00002835
Ted Kremenek02087932010-07-16 02:11:22 +00002836};
2837}
2838
2839bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2840 const analyze_printf::PrintfSpecifier &FS,
2841 const char *startSpecifier,
2842 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002843 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00002844 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00002845
Ted Kremenekce815422010-07-19 21:25:57 +00002846 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2847 getLocationOfByte(CS.getStart()),
2848 startSpecifier, specifierLen,
2849 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00002850}
2851
Ted Kremenek02087932010-07-16 02:11:22 +00002852bool CheckPrintfHandler::HandleAmount(
2853 const analyze_format_string::OptionalAmount &Amt,
2854 unsigned k, const char *startSpecifier,
2855 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00002856
2857 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00002858 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00002859 unsigned argIndex = Amt.getArgIndex();
2860 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002861 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2862 << k,
2863 getLocationOfByte(Amt.getStart()),
2864 /*IsStringLocation*/true,
2865 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00002866 // Don't do any more checking. We will just emit
2867 // spurious errors.
2868 return false;
2869 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002870
Ted Kremenek5739de72010-01-29 01:06:55 +00002871 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00002872 // Although not in conformance with C99, we also allow the argument to be
2873 // an 'unsigned int' as that is a reasonably safe case. GCC also
2874 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00002875 CoveredArgs.set(argIndex);
2876 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00002877 if (!Arg)
2878 return false;
2879
Ted Kremenek5739de72010-01-29 01:06:55 +00002880 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002881
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002882 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
2883 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002884
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002885 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002886 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002887 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00002888 << T << Arg->getSourceRange(),
2889 getLocationOfByte(Amt.getStart()),
2890 /*IsStringLocation*/true,
2891 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00002892 // Don't do any more checking. We will just emit
2893 // spurious errors.
2894 return false;
2895 }
2896 }
2897 }
2898 return true;
2899}
Ted Kremenek5739de72010-01-29 01:06:55 +00002900
Tom Careb49ec692010-06-17 19:00:27 +00002901void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00002902 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002903 const analyze_printf::OptionalAmount &Amt,
2904 unsigned type,
2905 const char *startSpecifier,
2906 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002907 const analyze_printf::PrintfConversionSpecifier &CS =
2908 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00002909
Richard Trieu03cf7b72011-10-28 00:41:25 +00002910 FixItHint fixit =
2911 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2912 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2913 Amt.getConstantLength()))
2914 : FixItHint();
2915
2916 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2917 << type << CS.toString(),
2918 getLocationOfByte(Amt.getStart()),
2919 /*IsStringLocation*/true,
2920 getSpecifierRange(startSpecifier, specifierLen),
2921 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00002922}
2923
Ted Kremenek02087932010-07-16 02:11:22 +00002924void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002925 const analyze_printf::OptionalFlag &flag,
2926 const char *startSpecifier,
2927 unsigned specifierLen) {
2928 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002929 const analyze_printf::PrintfConversionSpecifier &CS =
2930 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00002931 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2932 << flag.toString() << CS.toString(),
2933 getLocationOfByte(flag.getPosition()),
2934 /*IsStringLocation*/true,
2935 getSpecifierRange(startSpecifier, specifierLen),
2936 FixItHint::CreateRemoval(
2937 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00002938}
2939
2940void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00002941 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002942 const analyze_printf::OptionalFlag &ignoredFlag,
2943 const analyze_printf::OptionalFlag &flag,
2944 const char *startSpecifier,
2945 unsigned specifierLen) {
2946 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002947 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2948 << ignoredFlag.toString() << flag.toString(),
2949 getLocationOfByte(ignoredFlag.getPosition()),
2950 /*IsStringLocation*/true,
2951 getSpecifierRange(startSpecifier, specifierLen),
2952 FixItHint::CreateRemoval(
2953 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00002954}
2955
Richard Smith55ce3522012-06-25 20:30:08 +00002956// Determines if the specified is a C++ class or struct containing
2957// a member with the specified name and kind (e.g. a CXXMethodDecl named
2958// "c_str()").
2959template<typename MemberKind>
2960static llvm::SmallPtrSet<MemberKind*, 1>
2961CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2962 const RecordType *RT = Ty->getAs<RecordType>();
2963 llvm::SmallPtrSet<MemberKind*, 1> Results;
2964
2965 if (!RT)
2966 return Results;
2967 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00002968 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00002969 return Results;
2970
Alp Tokerb6cc5922014-05-03 03:45:55 +00002971 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00002972 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00002973 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00002974
2975 // We just need to include all members of the right kind turned up by the
2976 // filter, at this point.
2977 if (S.LookupQualifiedName(R, RT->getDecl()))
2978 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2979 NamedDecl *decl = (*I)->getUnderlyingDecl();
2980 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
2981 Results.insert(FK);
2982 }
2983 return Results;
2984}
2985
Richard Smith2868a732014-02-28 01:36:39 +00002986/// Check if we could call '.c_str()' on an object.
2987///
2988/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
2989/// allow the call, or if it would be ambiguous).
2990bool Sema::hasCStrMethod(const Expr *E) {
2991 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2992 MethodSet Results =
2993 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
2994 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2995 MI != ME; ++MI)
2996 if ((*MI)->getMinRequiredArguments() == 0)
2997 return true;
2998 return false;
2999}
3000
Richard Smith55ce3522012-06-25 20:30:08 +00003001// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003002// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00003003// Returns true when a c_str() conversion method is found.
3004bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00003005 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00003006 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3007
3008 MethodSet Results =
3009 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
3010
3011 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3012 MI != ME; ++MI) {
3013 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00003014 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00003015 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00003016 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00003017 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00003018 S.Diag(E->getLocStart(), diag::note_printf_c_str)
3019 << "c_str()"
3020 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
3021 return true;
3022 }
3023 }
3024
3025 return false;
3026}
3027
Ted Kremenekab278de2010-01-28 23:39:18 +00003028bool
Ted Kremenek02087932010-07-16 02:11:22 +00003029CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00003030 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00003031 const char *startSpecifier,
3032 unsigned specifierLen) {
3033
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003034 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00003035 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003036 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00003037
Ted Kremenek6cd69422010-07-19 22:01:06 +00003038 if (FS.consumesDataArgument()) {
3039 if (atFirstArg) {
3040 atFirstArg = false;
3041 usesPositionalArgs = FS.usesPositionalArg();
3042 }
3043 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003044 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3045 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003046 return false;
3047 }
Ted Kremenek5739de72010-01-29 01:06:55 +00003048 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003049
Ted Kremenekd1668192010-02-27 01:41:03 +00003050 // First check if the field width, precision, and conversion specifier
3051 // have matching data arguments.
3052 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
3053 startSpecifier, specifierLen)) {
3054 return false;
3055 }
3056
3057 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
3058 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003059 return false;
3060 }
3061
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003062 if (!CS.consumesDataArgument()) {
3063 // FIXME: Technically specifying a precision or field width here
3064 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00003065 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003066 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003067
Ted Kremenek4a49d982010-02-26 19:18:41 +00003068 // Consume the argument.
3069 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00003070 if (argIndex < NumDataArgs) {
3071 // The check to see if the argIndex is valid will come later.
3072 // We set the bit here because we may exit early from this
3073 // function if we encounter some other error.
3074 CoveredArgs.set(argIndex);
3075 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00003076
3077 // Check for using an Objective-C specific conversion specifier
3078 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003079 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00003080 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
3081 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00003082 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003083
Tom Careb49ec692010-06-17 19:00:27 +00003084 // Check for invalid use of field width
3085 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00003086 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00003087 startSpecifier, specifierLen);
3088 }
3089
3090 // Check for invalid use of precision
3091 if (!FS.hasValidPrecision()) {
3092 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
3093 startSpecifier, specifierLen);
3094 }
3095
3096 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00003097 if (!FS.hasValidThousandsGroupingPrefix())
3098 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003099 if (!FS.hasValidLeadingZeros())
3100 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
3101 if (!FS.hasValidPlusPrefix())
3102 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00003103 if (!FS.hasValidSpacePrefix())
3104 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003105 if (!FS.hasValidAlternativeForm())
3106 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3107 if (!FS.hasValidLeftJustified())
3108 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3109
3110 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00003111 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3112 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3113 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003114 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3115 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3116 startSpecifier, specifierLen);
3117
3118 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003119 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003120 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3121 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003122 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003123 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003124 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003125 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3126 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00003127
Jordan Rose92303592012-09-08 04:00:03 +00003128 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3129 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3130
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003131 // The remaining checks depend on the data arguments.
3132 if (HasVAListArg)
3133 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003134
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003135 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003136 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003137
Jordan Rose58bbe422012-07-19 18:10:08 +00003138 const Expr *Arg = getDataArg(argIndex);
3139 if (!Arg)
3140 return true;
3141
3142 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00003143}
3144
Jordan Roseaee34382012-09-05 22:56:26 +00003145static bool requiresParensToAddCast(const Expr *E) {
3146 // FIXME: We should have a general way to reason about operator
3147 // precedence and whether parens are actually needed here.
3148 // Take care of a few common cases where they aren't.
3149 const Expr *Inside = E->IgnoreImpCasts();
3150 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3151 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3152
3153 switch (Inside->getStmtClass()) {
3154 case Stmt::ArraySubscriptExprClass:
3155 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003156 case Stmt::CharacterLiteralClass:
3157 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003158 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003159 case Stmt::FloatingLiteralClass:
3160 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003161 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003162 case Stmt::ObjCArrayLiteralClass:
3163 case Stmt::ObjCBoolLiteralExprClass:
3164 case Stmt::ObjCBoxedExprClass:
3165 case Stmt::ObjCDictionaryLiteralClass:
3166 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003167 case Stmt::ObjCIvarRefExprClass:
3168 case Stmt::ObjCMessageExprClass:
3169 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003170 case Stmt::ObjCStringLiteralClass:
3171 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003172 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003173 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003174 case Stmt::UnaryOperatorClass:
3175 return false;
3176 default:
3177 return true;
3178 }
3179}
3180
Richard Smith55ce3522012-06-25 20:30:08 +00003181bool
3182CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3183 const char *StartSpecifier,
3184 unsigned SpecifierLen,
3185 const Expr *E) {
3186 using namespace analyze_format_string;
3187 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003188 // Now type check the data expression that matches the
3189 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003190 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3191 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00003192 if (!AT.isValid())
3193 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00003194
Jordan Rose598ec092012-12-05 18:44:40 +00003195 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00003196 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3197 ExprTy = TET->getUnderlyingExpr()->getType();
3198 }
3199
Jordan Rose598ec092012-12-05 18:44:40 +00003200 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003201 return true;
Jordan Rose98709982012-06-04 22:48:57 +00003202
Jordan Rose22b74712012-09-05 22:56:19 +00003203 // Look through argument promotions for our error message's reported type.
3204 // This includes the integral and floating promotions, but excludes array
3205 // and function pointer decay; seeing that an argument intended to be a
3206 // string has type 'char [6]' is probably more confusing than 'char *'.
3207 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3208 if (ICE->getCastKind() == CK_IntegralCast ||
3209 ICE->getCastKind() == CK_FloatingCast) {
3210 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00003211 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00003212
3213 // Check if we didn't match because of an implicit cast from a 'char'
3214 // or 'short' to an 'int'. This is done because printf is a varargs
3215 // function.
3216 if (ICE->getType() == S.Context.IntTy ||
3217 ICE->getType() == S.Context.UnsignedIntTy) {
3218 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00003219 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003220 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00003221 }
Jordan Rose98709982012-06-04 22:48:57 +00003222 }
Jordan Rose598ec092012-12-05 18:44:40 +00003223 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3224 // Special case for 'a', which has type 'int' in C.
3225 // Note, however, that we do /not/ want to treat multibyte constants like
3226 // 'MooV' as characters! This form is deprecated but still exists.
3227 if (ExprTy == S.Context.IntTy)
3228 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3229 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00003230 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003231
Jordan Rosebc53ed12014-05-31 04:12:14 +00003232 // Look through enums to their underlying type.
3233 bool IsEnum = false;
3234 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
3235 ExprTy = EnumTy->getDecl()->getIntegerType();
3236 IsEnum = true;
3237 }
3238
Jordan Rose0e5badd2012-12-05 18:44:49 +00003239 // %C in an Objective-C context prints a unichar, not a wchar_t.
3240 // If the argument is an integer of some kind, believe the %C and suggest
3241 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00003242 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003243 if (ObjCContext &&
3244 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3245 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3246 !ExprTy->isCharType()) {
3247 // 'unichar' is defined as a typedef of unsigned short, but we should
3248 // prefer using the typedef if it is visible.
3249 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00003250
3251 // While we are here, check if the value is an IntegerLiteral that happens
3252 // to be within the valid range.
3253 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3254 const llvm::APInt &V = IL->getValue();
3255 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3256 return true;
3257 }
3258
Jordan Rose0e5badd2012-12-05 18:44:49 +00003259 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3260 Sema::LookupOrdinaryName);
3261 if (S.LookupName(Result, S.getCurScope())) {
3262 NamedDecl *ND = Result.getFoundDecl();
3263 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3264 if (TD->getUnderlyingType() == IntendedTy)
3265 IntendedTy = S.Context.getTypedefType(TD);
3266 }
3267 }
3268 }
3269
3270 // Special-case some of Darwin's platform-independence types by suggesting
3271 // casts to primitive types that are known to be large enough.
3272 bool ShouldNotPrintDirectly = false;
Jordan Roseaee34382012-09-05 22:56:26 +00003273 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003274 // Use a 'while' to peel off layers of typedefs.
3275 QualType TyTy = IntendedTy;
3276 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
Jordan Roseaee34382012-09-05 22:56:26 +00003277 StringRef Name = UserTy->getDecl()->getName();
Jordan Rose0e5badd2012-12-05 18:44:49 +00003278 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Jordan Roseaee34382012-09-05 22:56:26 +00003279 .Case("NSInteger", S.Context.LongTy)
3280 .Case("NSUInteger", S.Context.UnsignedLongTy)
3281 .Case("SInt32", S.Context.IntTy)
3282 .Case("UInt32", S.Context.UnsignedIntTy)
Jordan Rose0e5badd2012-12-05 18:44:49 +00003283 .Default(QualType());
3284
3285 if (!CastTy.isNull()) {
3286 ShouldNotPrintDirectly = true;
3287 IntendedTy = CastTy;
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003288 break;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003289 }
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003290 TyTy = UserTy->desugar();
Jordan Roseaee34382012-09-05 22:56:26 +00003291 }
3292 }
3293
Jordan Rose22b74712012-09-05 22:56:19 +00003294 // We may be able to offer a FixItHint if it is a supported type.
3295 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00003296 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00003297 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003298
Jordan Rose22b74712012-09-05 22:56:19 +00003299 if (success) {
3300 // Get the fix string from the fixed format specifier
3301 SmallString<16> buf;
3302 llvm::raw_svector_ostream os(buf);
3303 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003304
Jordan Roseaee34382012-09-05 22:56:26 +00003305 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3306
Jordan Rose0e5badd2012-12-05 18:44:49 +00003307 if (IntendedTy == ExprTy) {
3308 // In this case, the specifier is wrong and should be changed to match
3309 // the argument.
3310 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003311 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3312 << AT.getRepresentativeTypeName(S.Context) << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003313 << E->getSourceRange(),
3314 E->getLocStart(),
3315 /*IsStringLocation*/false,
3316 SpecRange,
3317 FixItHint::CreateReplacement(SpecRange, os.str()));
3318
3319 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00003320 // The canonical type for formatting this value is different from the
3321 // actual type of the expression. (This occurs, for example, with Darwin's
3322 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3323 // should be printed as 'long' for 64-bit compatibility.)
3324 // Rather than emitting a normal format/argument mismatch, we want to
3325 // add a cast to the recommended type (and correct the format string
3326 // if necessary).
3327 SmallString<16> CastBuf;
3328 llvm::raw_svector_ostream CastFix(CastBuf);
3329 CastFix << "(";
3330 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3331 CastFix << ")";
3332
3333 SmallVector<FixItHint,4> Hints;
3334 if (!AT.matchesType(S.Context, IntendedTy))
3335 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3336
3337 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3338 // If there's already a cast present, just replace it.
3339 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3340 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3341
3342 } else if (!requiresParensToAddCast(E)) {
3343 // If the expression has high enough precedence,
3344 // just write the C-style cast.
3345 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3346 CastFix.str()));
3347 } else {
3348 // Otherwise, add parens around the expression as well as the cast.
3349 CastFix << "(";
3350 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3351 CastFix.str()));
3352
Alp Tokerb6cc5922014-05-03 03:45:55 +00003353 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00003354 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3355 }
3356
Jordan Rose0e5badd2012-12-05 18:44:49 +00003357 if (ShouldNotPrintDirectly) {
3358 // The expression has a type that should not be printed directly.
3359 // We extract the name from the typedef because we don't want to show
3360 // the underlying type in the diagnostic.
3361 StringRef Name = cast<TypedefType>(ExprTy)->getDecl()->getName();
Jordan Roseaee34382012-09-05 22:56:26 +00003362
Jordan Rose0e5badd2012-12-05 18:44:49 +00003363 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00003364 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003365 << E->getSourceRange(),
3366 E->getLocStart(), /*IsStringLocation=*/false,
3367 SpecRange, Hints);
3368 } else {
3369 // In this case, the expression could be printed using a different
3370 // specifier, but we've decided that the specifier is probably correct
3371 // and we should cast instead. Just use the normal warning message.
3372 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003373 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3374 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003375 << E->getSourceRange(),
3376 E->getLocStart(), /*IsStringLocation*/false,
3377 SpecRange, Hints);
3378 }
Jordan Roseaee34382012-09-05 22:56:26 +00003379 }
Jordan Rose22b74712012-09-05 22:56:19 +00003380 } else {
3381 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3382 SpecifierLen);
3383 // Since the warning for passing non-POD types to variadic functions
3384 // was deferred until now, we emit a warning for non-POD
3385 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00003386 switch (S.isValidVarArgType(ExprTy)) {
3387 case Sema::VAK_Valid:
3388 case Sema::VAK_ValidInCXX11:
Jordan Rose22b74712012-09-05 22:56:19 +00003389 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003390 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3391 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Richard Smithd7293d72013-08-05 18:49:43 +00003392 << CSR
3393 << E->getSourceRange(),
3394 E->getLocStart(), /*IsStringLocation*/false, CSR);
3395 break;
3396
3397 case Sema::VAK_Undefined:
3398 EmitFormatDiagnostic(
3399 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003400 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00003401 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00003402 << CallType
3403 << AT.getRepresentativeTypeName(S.Context)
3404 << CSR
3405 << E->getSourceRange(),
3406 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00003407 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00003408 break;
3409
3410 case Sema::VAK_Invalid:
3411 if (ExprTy->isObjCObjectType())
3412 EmitFormatDiagnostic(
3413 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3414 << S.getLangOpts().CPlusPlus11
3415 << ExprTy
3416 << CallType
3417 << AT.getRepresentativeTypeName(S.Context)
3418 << CSR
3419 << E->getSourceRange(),
3420 E->getLocStart(), /*IsStringLocation*/false, CSR);
3421 else
3422 // FIXME: If this is an initializer list, suggest removing the braces
3423 // or inserting a cast to the target type.
3424 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3425 << isa<InitListExpr>(E) << ExprTy << CallType
3426 << AT.getRepresentativeTypeName(S.Context)
3427 << E->getSourceRange();
3428 break;
3429 }
3430
3431 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3432 "format string specifier index out of range");
3433 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003434 }
3435
Ted Kremenekab278de2010-01-28 23:39:18 +00003436 return true;
3437}
3438
Ted Kremenek02087932010-07-16 02:11:22 +00003439//===--- CHECK: Scanf format string checking ------------------------------===//
3440
3441namespace {
3442class CheckScanfHandler : public CheckFormatHandler {
3443public:
3444 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3445 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003446 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003447 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003448 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003449 Sema::VariadicCallType CallType,
3450 llvm::SmallBitVector &CheckedVarArgs)
3451 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3452 numDataArgs, beg, hasVAListArg,
3453 Args, formatIdx, inFunctionCall, CallType,
3454 CheckedVarArgs)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003455 {}
Ted Kremenek02087932010-07-16 02:11:22 +00003456
3457 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3458 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003459 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00003460
3461 bool HandleInvalidScanfConversionSpecifier(
3462 const analyze_scanf::ScanfSpecifier &FS,
3463 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003464 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003465
Craig Toppere14c0f82014-03-12 04:55:44 +00003466 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00003467};
Ted Kremenek019d2242010-01-29 01:50:07 +00003468}
Ted Kremenekab278de2010-01-28 23:39:18 +00003469
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003470void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3471 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003472 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3473 getLocationOfByte(end), /*IsStringLocation*/true,
3474 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003475}
3476
Ted Kremenekce815422010-07-19 21:25:57 +00003477bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3478 const analyze_scanf::ScanfSpecifier &FS,
3479 const char *startSpecifier,
3480 unsigned specifierLen) {
3481
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003482 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003483 FS.getConversionSpecifier();
3484
3485 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3486 getLocationOfByte(CS.getStart()),
3487 startSpecifier, specifierLen,
3488 CS.getStart(), CS.getLength());
3489}
3490
Ted Kremenek02087932010-07-16 02:11:22 +00003491bool CheckScanfHandler::HandleScanfSpecifier(
3492 const analyze_scanf::ScanfSpecifier &FS,
3493 const char *startSpecifier,
3494 unsigned specifierLen) {
3495
3496 using namespace analyze_scanf;
3497 using namespace analyze_format_string;
3498
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003499 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003500
Ted Kremenek6cd69422010-07-19 22:01:06 +00003501 // Handle case where '%' and '*' don't consume an argument. These shouldn't
3502 // be used to decide if we are using positional arguments consistently.
3503 if (FS.consumesDataArgument()) {
3504 if (atFirstArg) {
3505 atFirstArg = false;
3506 usesPositionalArgs = FS.usesPositionalArg();
3507 }
3508 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003509 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3510 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003511 return false;
3512 }
Ted Kremenek02087932010-07-16 02:11:22 +00003513 }
3514
3515 // Check if the field with is non-zero.
3516 const OptionalAmount &Amt = FS.getFieldWidth();
3517 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3518 if (Amt.getConstantAmount() == 0) {
3519 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3520 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00003521 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3522 getLocationOfByte(Amt.getStart()),
3523 /*IsStringLocation*/true, R,
3524 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00003525 }
3526 }
3527
3528 if (!FS.consumesDataArgument()) {
3529 // FIXME: Technically specifying a precision or field width here
3530 // makes no sense. Worth issuing a warning at some point.
3531 return true;
3532 }
3533
3534 // Consume the argument.
3535 unsigned argIndex = FS.getArgIndex();
3536 if (argIndex < NumDataArgs) {
3537 // The check to see if the argIndex is valid will come later.
3538 // We set the bit here because we may exit early from this
3539 // function if we encounter some other error.
3540 CoveredArgs.set(argIndex);
3541 }
3542
Ted Kremenek4407ea42010-07-20 20:04:47 +00003543 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003544 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003545 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3546 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003547 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003548 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003549 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003550 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3551 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003552
Jordan Rose92303592012-09-08 04:00:03 +00003553 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3554 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3555
Ted Kremenek02087932010-07-16 02:11:22 +00003556 // The remaining checks depend on the data arguments.
3557 if (HasVAListArg)
3558 return true;
3559
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003560 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00003561 return false;
Ted Kremenek02087932010-07-16 02:11:22 +00003562
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003563 // Check that the argument type matches the format specifier.
3564 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00003565 if (!Ex)
3566 return true;
3567
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00003568 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3569 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003570 ScanfSpecifier fixedFS = FS;
Jordan Rose177b0a32014-03-20 03:32:39 +00003571 bool success = fixedFS.fixType(Ex->getType(),
3572 Ex->IgnoreImpCasts()->getType(),
3573 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003574
3575 if (success) {
3576 // Get the fix string from the fixed format specifier.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003577 SmallString<128> buf;
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003578 llvm::raw_svector_ostream os(buf);
3579 fixedFS.toString(os);
3580
3581 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003582 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3583 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() << false
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003584 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00003585 Ex->getLocStart(),
3586 /*IsStringLocation*/false,
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003587 getSpecifierRange(startSpecifier, specifierLen),
3588 FixItHint::CreateReplacement(
3589 getSpecifierRange(startSpecifier, specifierLen),
3590 os.str()));
3591 } else {
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003592 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003593 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3594 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() << false
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003595 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00003596 Ex->getLocStart(),
3597 /*IsStringLocation*/false,
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003598 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003599 }
3600 }
3601
Ted Kremenek02087932010-07-16 02:11:22 +00003602 return true;
3603}
3604
3605void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00003606 const Expr *OrigFormatExpr,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003607 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003608 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003609 unsigned firstDataArg, FormatStringType Type,
Richard Smithd7293d72013-08-05 18:49:43 +00003610 bool inFunctionCall, VariadicCallType CallType,
3611 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00003612
Ted Kremenekab278de2010-01-28 23:39:18 +00003613 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00003614 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003615 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003616 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00003617 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3618 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00003619 return;
3620 }
Ted Kremenek02087932010-07-16 02:11:22 +00003621
Ted Kremenekab278de2010-01-28 23:39:18 +00003622 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003623 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00003624 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00003625 // Account for cases where the string literal is truncated in a declaration.
3626 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
3627 assert(T && "String literal not of constant array type!");
3628 size_t TypeSize = T->getSize().getZExtValue();
3629 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003630 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00003631
3632 // Emit a warning if the string literal is truncated and does not contain an
3633 // embedded null character.
3634 if (TypeSize <= StrRef.size() &&
3635 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
3636 CheckFormatHandler::EmitFormatDiagnostic(
3637 *this, inFunctionCall, Args[format_idx],
3638 PDiag(diag::warn_printf_format_string_not_null_terminated),
3639 FExpr->getLocStart(),
3640 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
3641 return;
3642 }
3643
Ted Kremenekab278de2010-01-28 23:39:18 +00003644 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00003645 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003646 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003647 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00003648 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3649 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00003650 return;
3651 }
Ted Kremenek02087932010-07-16 02:11:22 +00003652
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003653 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek02087932010-07-16 02:11:22 +00003654 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003655 numDataArgs, (Type == FST_NSString),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003656 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00003657 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00003658
Hans Wennborg23926bd2011-12-15 10:25:47 +00003659 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00003660 getLangOpts(),
3661 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00003662 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003663 } else if (Type == FST_Scanf) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003664 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003665 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00003666 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00003667
Hans Wennborg23926bd2011-12-15 10:25:47 +00003668 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00003669 getLangOpts(),
3670 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00003671 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003672 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00003673}
3674
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003675//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
3676
3677// Returns the related absolute value function that is larger, of 0 if one
3678// does not exist.
3679static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
3680 switch (AbsFunction) {
3681 default:
3682 return 0;
3683
3684 case Builtin::BI__builtin_abs:
3685 return Builtin::BI__builtin_labs;
3686 case Builtin::BI__builtin_labs:
3687 return Builtin::BI__builtin_llabs;
3688 case Builtin::BI__builtin_llabs:
3689 return 0;
3690
3691 case Builtin::BI__builtin_fabsf:
3692 return Builtin::BI__builtin_fabs;
3693 case Builtin::BI__builtin_fabs:
3694 return Builtin::BI__builtin_fabsl;
3695 case Builtin::BI__builtin_fabsl:
3696 return 0;
3697
3698 case Builtin::BI__builtin_cabsf:
3699 return Builtin::BI__builtin_cabs;
3700 case Builtin::BI__builtin_cabs:
3701 return Builtin::BI__builtin_cabsl;
3702 case Builtin::BI__builtin_cabsl:
3703 return 0;
3704
3705 case Builtin::BIabs:
3706 return Builtin::BIlabs;
3707 case Builtin::BIlabs:
3708 return Builtin::BIllabs;
3709 case Builtin::BIllabs:
3710 return 0;
3711
3712 case Builtin::BIfabsf:
3713 return Builtin::BIfabs;
3714 case Builtin::BIfabs:
3715 return Builtin::BIfabsl;
3716 case Builtin::BIfabsl:
3717 return 0;
3718
3719 case Builtin::BIcabsf:
3720 return Builtin::BIcabs;
3721 case Builtin::BIcabs:
3722 return Builtin::BIcabsl;
3723 case Builtin::BIcabsl:
3724 return 0;
3725 }
3726}
3727
3728// Returns the argument type of the absolute value function.
3729static QualType getAbsoluteValueArgumentType(ASTContext &Context,
3730 unsigned AbsType) {
3731 if (AbsType == 0)
3732 return QualType();
3733
3734 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3735 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
3736 if (Error != ASTContext::GE_None)
3737 return QualType();
3738
3739 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
3740 if (!FT)
3741 return QualType();
3742
3743 if (FT->getNumParams() != 1)
3744 return QualType();
3745
3746 return FT->getParamType(0);
3747}
3748
3749// Returns the best absolute value function, or zero, based on type and
3750// current absolute value function.
3751static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
3752 unsigned AbsFunctionKind) {
3753 unsigned BestKind = 0;
3754 uint64_t ArgSize = Context.getTypeSize(ArgType);
3755 for (unsigned Kind = AbsFunctionKind; Kind != 0;
3756 Kind = getLargerAbsoluteValueFunction(Kind)) {
3757 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
3758 if (Context.getTypeSize(ParamType) >= ArgSize) {
3759 if (BestKind == 0)
3760 BestKind = Kind;
3761 else if (Context.hasSameType(ParamType, ArgType)) {
3762 BestKind = Kind;
3763 break;
3764 }
3765 }
3766 }
3767 return BestKind;
3768}
3769
3770enum AbsoluteValueKind {
3771 AVK_Integer,
3772 AVK_Floating,
3773 AVK_Complex
3774};
3775
3776static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
3777 if (T->isIntegralOrEnumerationType())
3778 return AVK_Integer;
3779 if (T->isRealFloatingType())
3780 return AVK_Floating;
3781 if (T->isAnyComplexType())
3782 return AVK_Complex;
3783
3784 llvm_unreachable("Type not integer, floating, or complex");
3785}
3786
3787// Changes the absolute value function to a different type. Preserves whether
3788// the function is a builtin.
3789static unsigned changeAbsFunction(unsigned AbsKind,
3790 AbsoluteValueKind ValueKind) {
3791 switch (ValueKind) {
3792 case AVK_Integer:
3793 switch (AbsKind) {
3794 default:
3795 return 0;
3796 case Builtin::BI__builtin_fabsf:
3797 case Builtin::BI__builtin_fabs:
3798 case Builtin::BI__builtin_fabsl:
3799 case Builtin::BI__builtin_cabsf:
3800 case Builtin::BI__builtin_cabs:
3801 case Builtin::BI__builtin_cabsl:
3802 return Builtin::BI__builtin_abs;
3803 case Builtin::BIfabsf:
3804 case Builtin::BIfabs:
3805 case Builtin::BIfabsl:
3806 case Builtin::BIcabsf:
3807 case Builtin::BIcabs:
3808 case Builtin::BIcabsl:
3809 return Builtin::BIabs;
3810 }
3811 case AVK_Floating:
3812 switch (AbsKind) {
3813 default:
3814 return 0;
3815 case Builtin::BI__builtin_abs:
3816 case Builtin::BI__builtin_labs:
3817 case Builtin::BI__builtin_llabs:
3818 case Builtin::BI__builtin_cabsf:
3819 case Builtin::BI__builtin_cabs:
3820 case Builtin::BI__builtin_cabsl:
3821 return Builtin::BI__builtin_fabsf;
3822 case Builtin::BIabs:
3823 case Builtin::BIlabs:
3824 case Builtin::BIllabs:
3825 case Builtin::BIcabsf:
3826 case Builtin::BIcabs:
3827 case Builtin::BIcabsl:
3828 return Builtin::BIfabsf;
3829 }
3830 case AVK_Complex:
3831 switch (AbsKind) {
3832 default:
3833 return 0;
3834 case Builtin::BI__builtin_abs:
3835 case Builtin::BI__builtin_labs:
3836 case Builtin::BI__builtin_llabs:
3837 case Builtin::BI__builtin_fabsf:
3838 case Builtin::BI__builtin_fabs:
3839 case Builtin::BI__builtin_fabsl:
3840 return Builtin::BI__builtin_cabsf;
3841 case Builtin::BIabs:
3842 case Builtin::BIlabs:
3843 case Builtin::BIllabs:
3844 case Builtin::BIfabsf:
3845 case Builtin::BIfabs:
3846 case Builtin::BIfabsl:
3847 return Builtin::BIcabsf;
3848 }
3849 }
3850 llvm_unreachable("Unable to convert function");
3851}
3852
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00003853static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003854 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
3855 if (!FnInfo)
3856 return 0;
3857
3858 switch (FDecl->getBuiltinID()) {
3859 default:
3860 return 0;
3861 case Builtin::BI__builtin_abs:
3862 case Builtin::BI__builtin_fabs:
3863 case Builtin::BI__builtin_fabsf:
3864 case Builtin::BI__builtin_fabsl:
3865 case Builtin::BI__builtin_labs:
3866 case Builtin::BI__builtin_llabs:
3867 case Builtin::BI__builtin_cabs:
3868 case Builtin::BI__builtin_cabsf:
3869 case Builtin::BI__builtin_cabsl:
3870 case Builtin::BIabs:
3871 case Builtin::BIlabs:
3872 case Builtin::BIllabs:
3873 case Builtin::BIfabs:
3874 case Builtin::BIfabsf:
3875 case Builtin::BIfabsl:
3876 case Builtin::BIcabs:
3877 case Builtin::BIcabsf:
3878 case Builtin::BIcabsl:
3879 return FDecl->getBuiltinID();
3880 }
3881 llvm_unreachable("Unknown Builtin type");
3882}
3883
3884// If the replacement is valid, emit a note with replacement function.
3885// Additionally, suggest including the proper header if not already included.
3886static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00003887 unsigned AbsKind, QualType ArgType) {
3888 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00003889 const char *HeaderName = nullptr;
3890 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00003891 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
3892 FunctionName = "std::abs";
3893 if (ArgType->isIntegralOrEnumerationType()) {
3894 HeaderName = "cstdlib";
3895 } else if (ArgType->isRealFloatingType()) {
3896 HeaderName = "cmath";
3897 } else {
3898 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003899 }
Richard Trieubeffb832014-04-15 23:47:53 +00003900
3901 // Lookup all std::abs
3902 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00003903 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00003904 R.suppressDiagnostics();
3905 S.LookupQualifiedName(R, Std);
3906
3907 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003908 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00003909 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
3910 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
3911 } else {
3912 FDecl = dyn_cast<FunctionDecl>(I);
3913 }
3914 if (!FDecl)
3915 continue;
3916
3917 // Found std::abs(), check that they are the right ones.
3918 if (FDecl->getNumParams() != 1)
3919 continue;
3920
3921 // Check that the parameter type can handle the argument.
3922 QualType ParamType = FDecl->getParamDecl(0)->getType();
3923 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
3924 S.Context.getTypeSize(ArgType) <=
3925 S.Context.getTypeSize(ParamType)) {
3926 // Found a function, don't need the header hint.
3927 EmitHeaderHint = false;
3928 break;
3929 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003930 }
Richard Trieubeffb832014-04-15 23:47:53 +00003931 }
3932 } else {
3933 FunctionName = S.Context.BuiltinInfo.GetName(AbsKind);
3934 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
3935
3936 if (HeaderName) {
3937 DeclarationName DN(&S.Context.Idents.get(FunctionName));
3938 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
3939 R.suppressDiagnostics();
3940 S.LookupName(R, S.getCurScope());
3941
3942 if (R.isSingleResult()) {
3943 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3944 if (FD && FD->getBuiltinID() == AbsKind) {
3945 EmitHeaderHint = false;
3946 } else {
3947 return;
3948 }
3949 } else if (!R.empty()) {
3950 return;
3951 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003952 }
3953 }
3954
3955 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00003956 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003957
Richard Trieubeffb832014-04-15 23:47:53 +00003958 if (!HeaderName)
3959 return;
3960
3961 if (!EmitHeaderHint)
3962 return;
3963
Alp Toker5d96e0a2014-07-11 20:53:51 +00003964 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
3965 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00003966}
3967
3968static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
3969 if (!FDecl)
3970 return false;
3971
3972 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
3973 return false;
3974
3975 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
3976
3977 while (ND && ND->isInlineNamespace()) {
3978 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003979 }
Richard Trieubeffb832014-04-15 23:47:53 +00003980
3981 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
3982 return false;
3983
3984 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
3985 return false;
3986
3987 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003988}
3989
3990// Warn when using the wrong abs() function.
3991void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
3992 const FunctionDecl *FDecl,
3993 IdentifierInfo *FnInfo) {
3994 if (Call->getNumArgs() != 1)
3995 return;
3996
3997 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00003998 bool IsStdAbs = IsFunctionStdAbs(FDecl);
3999 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004000 return;
4001
4002 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
4003 QualType ParamType = Call->getArg(0)->getType();
4004
Alp Toker5d96e0a2014-07-11 20:53:51 +00004005 // Unsigned types cannot be negative. Suggest removing the absolute value
4006 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004007 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00004008 const char *FunctionName =
4009 IsStdAbs ? "std::abs" : Context.BuiltinInfo.GetName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004010 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
4011 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00004012 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004013 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
4014 return;
4015 }
4016
Richard Trieubeffb832014-04-15 23:47:53 +00004017 // std::abs has overloads which prevent most of the absolute value problems
4018 // from occurring.
4019 if (IsStdAbs)
4020 return;
4021
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004022 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
4023 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
4024
4025 // The argument and parameter are the same kind. Check if they are the right
4026 // size.
4027 if (ArgValueKind == ParamValueKind) {
4028 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
4029 return;
4030
4031 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
4032 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
4033 << FDecl << ArgType << ParamType;
4034
4035 if (NewAbsKind == 0)
4036 return;
4037
4038 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00004039 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004040 return;
4041 }
4042
4043 // ArgValueKind != ParamValueKind
4044 // The wrong type of absolute value function was used. Attempt to find the
4045 // proper one.
4046 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
4047 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
4048 if (NewAbsKind == 0)
4049 return;
4050
4051 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
4052 << FDecl << ParamValueKind << ArgValueKind;
4053
4054 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00004055 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004056 return;
4057}
4058
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004059//===--- CHECK: Standard memory functions ---------------------------------===//
4060
Nico Weber0e6daef2013-12-26 23:38:39 +00004061/// \brief Takes the expression passed to the size_t parameter of functions
4062/// such as memcmp, strncat, etc and warns if it's a comparison.
4063///
4064/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
4065static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
4066 IdentifierInfo *FnName,
4067 SourceLocation FnLoc,
4068 SourceLocation RParenLoc) {
4069 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
4070 if (!Size)
4071 return false;
4072
4073 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
4074 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
4075 return false;
4076
Nico Weber0e6daef2013-12-26 23:38:39 +00004077 SourceRange SizeRange = Size->getSourceRange();
4078 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
4079 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00004080 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00004081 << FnName << FixItHint::CreateInsertion(
4082 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00004083 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00004084 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00004085 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00004086 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
4087 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00004088
4089 return true;
4090}
4091
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004092/// \brief Determine whether the given type is or contains a dynamic class type
4093/// (e.g., whether it has a vtable).
4094static const CXXRecordDecl *getContainedDynamicClass(QualType T,
4095 bool &IsContained) {
4096 // Look through array types while ignoring qualifiers.
4097 const Type *Ty = T->getBaseElementTypeUnsafe();
4098 IsContained = false;
4099
4100 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
4101 RD = RD ? RD->getDefinition() : nullptr;
4102 if (!RD)
4103 return nullptr;
4104
4105 if (RD->isDynamicClass())
4106 return RD;
4107
4108 // Check all the fields. If any bases were dynamic, the class is dynamic.
4109 // It's impossible for a class to transitively contain itself by value, so
4110 // infinite recursion is impossible.
4111 for (auto *FD : RD->fields()) {
4112 bool SubContained;
4113 if (const CXXRecordDecl *ContainedRD =
4114 getContainedDynamicClass(FD->getType(), SubContained)) {
4115 IsContained = true;
4116 return ContainedRD;
4117 }
4118 }
4119
4120 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00004121}
4122
Chandler Carruth889ed862011-06-21 23:04:20 +00004123/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004124/// otherwise returns NULL.
4125static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Weberc5e73862011-06-14 16:14:58 +00004126 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004127 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4128 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
4129 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004130
Craig Topperc3ec1492014-05-26 06:22:03 +00004131 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004132}
4133
Chandler Carruth889ed862011-06-21 23:04:20 +00004134/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004135static QualType getSizeOfArgType(const Expr* E) {
4136 if (const UnaryExprOrTypeTraitExpr *SizeOf =
4137 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4138 if (SizeOf->getKind() == clang::UETT_SizeOf)
4139 return SizeOf->getTypeOfArgument();
4140
4141 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00004142}
4143
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004144/// \brief Check for dangerous or invalid arguments to memset().
4145///
Chandler Carruthac687262011-06-03 06:23:57 +00004146/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004147/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
4148/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004149///
4150/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004151void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00004152 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004153 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00004154 assert(BId != 0);
4155
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004156 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00004157 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00004158 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00004159 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004160 return;
4161
Anna Zaks22122702012-01-17 00:37:07 +00004162 unsigned LastArg = (BId == Builtin::BImemset ||
4163 BId == Builtin::BIstrndup ? 1 : 2);
4164 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00004165 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004166
Nico Weber0e6daef2013-12-26 23:38:39 +00004167 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
4168 Call->getLocStart(), Call->getRParenLoc()))
4169 return;
4170
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004171 // We have special checking when the length is a sizeof expression.
4172 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
4173 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
4174 llvm::FoldingSetNodeID SizeOfArgID;
4175
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004176 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
4177 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004178 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004179
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004180 QualType DestTy = Dest->getType();
4181 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
4182 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00004183
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004184 // Never warn about void type pointers. This can be used to suppress
4185 // false positives.
4186 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004187 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004188
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004189 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
4190 // actually comparing the expressions for equality. Because computing the
4191 // expression IDs can be expensive, we only do this if the diagnostic is
4192 // enabled.
4193 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004194 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
4195 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004196 // We only compute IDs for expressions if the warning is enabled, and
4197 // cache the sizeof arg's ID.
4198 if (SizeOfArgID == llvm::FoldingSetNodeID())
4199 SizeOfArg->Profile(SizeOfArgID, Context, true);
4200 llvm::FoldingSetNodeID DestID;
4201 Dest->Profile(DestID, Context, true);
4202 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00004203 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
4204 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004205 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00004206 StringRef ReadableName = FnName->getName();
4207
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004208 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00004209 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004210 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00004211 if (!PointeeTy->isIncompleteType() &&
4212 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004213 ActionIdx = 2; // If the pointee's size is sizeof(char),
4214 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00004215
4216 // If the function is defined as a builtin macro, do not show macro
4217 // expansion.
4218 SourceLocation SL = SizeOfArg->getExprLoc();
4219 SourceRange DSR = Dest->getSourceRange();
4220 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00004221 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00004222
4223 if (SM.isMacroArgExpansion(SL)) {
4224 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
4225 SL = SM.getSpellingLoc(SL);
4226 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
4227 SM.getSpellingLoc(DSR.getEnd()));
4228 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
4229 SM.getSpellingLoc(SSR.getEnd()));
4230 }
4231
Anna Zaksd08d9152012-05-30 23:14:52 +00004232 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004233 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00004234 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00004235 << PointeeTy
4236 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00004237 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00004238 << SSR);
4239 DiagRuntimeBehavior(SL, SizeOfArg,
4240 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
4241 << ActionIdx
4242 << SSR);
4243
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004244 break;
4245 }
4246 }
4247
4248 // Also check for cases where the sizeof argument is the exact same
4249 // type as the memory argument, and where it points to a user-defined
4250 // record type.
4251 if (SizeOfArgTy != QualType()) {
4252 if (PointeeTy->isRecordType() &&
4253 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
4254 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
4255 PDiag(diag::warn_sizeof_pointer_type_memaccess)
4256 << FnName << SizeOfArgTy << ArgIdx
4257 << PointeeTy << Dest->getSourceRange()
4258 << LenExpr->getSourceRange());
4259 break;
4260 }
Nico Weberc5e73862011-06-14 16:14:58 +00004261 }
4262
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004263 // Always complain about dynamic classes.
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004264 bool IsContained;
4265 if (const CXXRecordDecl *ContainedRD =
4266 getContainedDynamicClass(PointeeTy, IsContained)) {
Anna Zaks22122702012-01-17 00:37:07 +00004267
4268 unsigned OperationType = 0;
4269 // "overwritten" if we're warning about the destination for any call
4270 // but memcmp; otherwise a verb appropriate to the call.
4271 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
4272 if (BId == Builtin::BImemcpy)
4273 OperationType = 1;
4274 else if(BId == Builtin::BImemmove)
4275 OperationType = 2;
4276 else if (BId == Builtin::BImemcmp)
4277 OperationType = 3;
4278 }
4279
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004280 DiagRuntimeBehavior(
4281 Dest->getExprLoc(), Dest,
4282 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks22122702012-01-17 00:37:07 +00004283 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004284 << FnName << IsContained << ContainedRD << OperationType
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004285 << Call->getCallee()->getSourceRange());
Anna Zaks22122702012-01-17 00:37:07 +00004286 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
4287 BId != Builtin::BImemset)
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004288 DiagRuntimeBehavior(
4289 Dest->getExprLoc(), Dest,
4290 PDiag(diag::warn_arc_object_memaccess)
4291 << ArgIdx << FnName << PointeeTy
4292 << Call->getCallee()->getSourceRange());
John McCall31168b02011-06-15 23:02:42 +00004293 else
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004294 continue;
John McCall31168b02011-06-15 23:02:42 +00004295
4296 DiagRuntimeBehavior(
4297 Dest->getExprLoc(), Dest,
Chandler Carruthac687262011-06-03 06:23:57 +00004298 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004299 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
4300 break;
4301 }
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004302 }
4303}
4304
Ted Kremenek6865f772011-08-18 20:55:45 +00004305// A little helper routine: ignore addition and subtraction of integer literals.
4306// This intentionally does not ignore all integer constant expressions because
4307// we don't want to remove sizeof().
4308static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
4309 Ex = Ex->IgnoreParenCasts();
4310
4311 for (;;) {
4312 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
4313 if (!BO || !BO->isAdditiveOp())
4314 break;
4315
4316 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
4317 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
4318
4319 if (isa<IntegerLiteral>(RHS))
4320 Ex = LHS;
4321 else if (isa<IntegerLiteral>(LHS))
4322 Ex = RHS;
4323 else
4324 break;
4325 }
4326
4327 return Ex;
4328}
4329
Anna Zaks13b08572012-08-08 21:42:23 +00004330static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
4331 ASTContext &Context) {
4332 // Only handle constant-sized or VLAs, but not flexible members.
4333 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
4334 // Only issue the FIXIT for arrays of size > 1.
4335 if (CAT->getSize().getSExtValue() <= 1)
4336 return false;
4337 } else if (!Ty->isVariableArrayType()) {
4338 return false;
4339 }
4340 return true;
4341}
4342
Ted Kremenek6865f772011-08-18 20:55:45 +00004343// Warn if the user has made the 'size' argument to strlcpy or strlcat
4344// be the size of the source, instead of the destination.
4345void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
4346 IdentifierInfo *FnName) {
4347
4348 // Don't crash if the user has the wrong number of arguments
4349 if (Call->getNumArgs() != 3)
4350 return;
4351
4352 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
4353 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00004354 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00004355
4356 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
4357 Call->getLocStart(), Call->getRParenLoc()))
4358 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00004359
4360 // Look for 'strlcpy(dst, x, sizeof(x))'
4361 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
4362 CompareWithSrc = Ex;
4363 else {
4364 // Look for 'strlcpy(dst, x, strlen(x))'
4365 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00004366 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
4367 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00004368 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
4369 }
4370 }
4371
4372 if (!CompareWithSrc)
4373 return;
4374
4375 // Determine if the argument to sizeof/strlen is equal to the source
4376 // argument. In principle there's all kinds of things you could do
4377 // here, for instance creating an == expression and evaluating it with
4378 // EvaluateAsBooleanCondition, but this uses a more direct technique:
4379 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
4380 if (!SrcArgDRE)
4381 return;
4382
4383 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
4384 if (!CompareWithSrcDRE ||
4385 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
4386 return;
4387
4388 const Expr *OriginalSizeArg = Call->getArg(2);
4389 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
4390 << OriginalSizeArg->getSourceRange() << FnName;
4391
4392 // Output a FIXIT hint if the destination is an array (rather than a
4393 // pointer to an array). This could be enhanced to handle some
4394 // pointers if we know the actual size, like if DstArg is 'array+2'
4395 // we could say 'sizeof(array)-2'.
4396 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00004397 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00004398 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004399
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004400 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004401 llvm::raw_svector_ostream OS(sizeString);
4402 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004403 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00004404 OS << ")";
4405
4406 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
4407 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
4408 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00004409}
4410
Anna Zaks314cd092012-02-01 19:08:57 +00004411/// Check if two expressions refer to the same declaration.
4412static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
4413 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
4414 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
4415 return D1->getDecl() == D2->getDecl();
4416 return false;
4417}
4418
4419static const Expr *getStrlenExprArg(const Expr *E) {
4420 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
4421 const FunctionDecl *FD = CE->getDirectCallee();
4422 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00004423 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00004424 return CE->getArg(0)->IgnoreParenCasts();
4425 }
Craig Topperc3ec1492014-05-26 06:22:03 +00004426 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00004427}
4428
4429// Warn on anti-patterns as the 'size' argument to strncat.
4430// The correct size argument should look like following:
4431// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
4432void Sema::CheckStrncatArguments(const CallExpr *CE,
4433 IdentifierInfo *FnName) {
4434 // Don't crash if the user has the wrong number of arguments.
4435 if (CE->getNumArgs() < 3)
4436 return;
4437 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
4438 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
4439 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
4440
Nico Weber0e6daef2013-12-26 23:38:39 +00004441 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
4442 CE->getRParenLoc()))
4443 return;
4444
Anna Zaks314cd092012-02-01 19:08:57 +00004445 // Identify common expressions, which are wrongly used as the size argument
4446 // to strncat and may lead to buffer overflows.
4447 unsigned PatternType = 0;
4448 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
4449 // - sizeof(dst)
4450 if (referToTheSameDecl(SizeOfArg, DstArg))
4451 PatternType = 1;
4452 // - sizeof(src)
4453 else if (referToTheSameDecl(SizeOfArg, SrcArg))
4454 PatternType = 2;
4455 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
4456 if (BE->getOpcode() == BO_Sub) {
4457 const Expr *L = BE->getLHS()->IgnoreParenCasts();
4458 const Expr *R = BE->getRHS()->IgnoreParenCasts();
4459 // - sizeof(dst) - strlen(dst)
4460 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
4461 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
4462 PatternType = 1;
4463 // - sizeof(src) - (anything)
4464 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
4465 PatternType = 2;
4466 }
4467 }
4468
4469 if (PatternType == 0)
4470 return;
4471
Anna Zaks5069aa32012-02-03 01:27:37 +00004472 // Generate the diagnostic.
4473 SourceLocation SL = LenArg->getLocStart();
4474 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00004475 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00004476
4477 // If the function is defined as a builtin macro, do not show macro expansion.
4478 if (SM.isMacroArgExpansion(SL)) {
4479 SL = SM.getSpellingLoc(SL);
4480 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
4481 SM.getSpellingLoc(SR.getEnd()));
4482 }
4483
Anna Zaks13b08572012-08-08 21:42:23 +00004484 // Check if the destination is an array (rather than a pointer to an array).
4485 QualType DstTy = DstArg->getType();
4486 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
4487 Context);
4488 if (!isKnownSizeArray) {
4489 if (PatternType == 1)
4490 Diag(SL, diag::warn_strncat_wrong_size) << SR;
4491 else
4492 Diag(SL, diag::warn_strncat_src_size) << SR;
4493 return;
4494 }
4495
Anna Zaks314cd092012-02-01 19:08:57 +00004496 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00004497 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004498 else
Anna Zaks5069aa32012-02-03 01:27:37 +00004499 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004500
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004501 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00004502 llvm::raw_svector_ostream OS(sizeString);
4503 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004504 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00004505 OS << ") - ";
4506 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004507 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00004508 OS << ") - 1";
4509
Anna Zaks5069aa32012-02-03 01:27:37 +00004510 Diag(SL, diag::note_strncat_wrong_size)
4511 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00004512}
4513
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004514//===--- CHECK: Return Address of Stack Variable --------------------------===//
4515
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004516static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4517 Decl *ParentDecl);
4518static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
4519 Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004520
4521/// CheckReturnStackAddr - Check if a return statement returns the address
4522/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004523static void
4524CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
4525 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00004526
Craig Topperc3ec1492014-05-26 06:22:03 +00004527 Expr *stackE = nullptr;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004528 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004529
4530 // Perform checking for returned stack addresses, local blocks,
4531 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00004532 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004533 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004534 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00004535 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004536 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004537 }
4538
Craig Topperc3ec1492014-05-26 06:22:03 +00004539 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004540 return; // Nothing suspicious was found.
4541
4542 SourceLocation diagLoc;
4543 SourceRange diagRange;
4544 if (refVars.empty()) {
4545 diagLoc = stackE->getLocStart();
4546 diagRange = stackE->getSourceRange();
4547 } else {
4548 // We followed through a reference variable. 'stackE' contains the
4549 // problematic expression but we will warn at the return statement pointing
4550 // at the reference variable. We will later display the "trail" of
4551 // reference variables using notes.
4552 diagLoc = refVars[0]->getLocStart();
4553 diagRange = refVars[0]->getSourceRange();
4554 }
4555
4556 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004557 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004558 : diag::warn_ret_stack_addr)
4559 << DR->getDecl()->getDeclName() << diagRange;
4560 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004561 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004562 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004563 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004564 } else { // local temporary.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004565 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
4566 : diag::warn_ret_local_temp_addr)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004567 << diagRange;
4568 }
4569
4570 // Display the "trail" of reference variables that we followed until we
4571 // found the problematic expression using notes.
4572 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
4573 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
4574 // If this var binds to another reference var, show the range of the next
4575 // var, otherwise the var binds to the problematic expression, in which case
4576 // show the range of the expression.
4577 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
4578 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004579 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
4580 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004581 }
4582}
4583
4584/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
4585/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004586/// to a location on the stack, a local block, an address of a label, or a
4587/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004588/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004589/// encounter a subexpression that (1) clearly does not lead to one of the
4590/// above problematic expressions (2) is something we cannot determine leads to
4591/// a problematic expression based on such local checking.
4592///
4593/// Both EvalAddr and EvalVal follow through reference variables to evaluate
4594/// the expression that they point to. Such variables are added to the
4595/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004596///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00004597/// EvalAddr processes expressions that are pointers that are used as
4598/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004599/// At the base case of the recursion is a check for the above problematic
4600/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004601///
4602/// This implementation handles:
4603///
4604/// * pointer-to-pointer casts
4605/// * implicit conversions from array references to pointers
4606/// * taking the address of fields
4607/// * arbitrary interplay between "&" and "*" operators
4608/// * pointer arithmetic from an address of a stack variable
4609/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004610static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4611 Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004612 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00004613 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004614
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004615 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00004616 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004617 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004618 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00004619 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00004620
Peter Collingbourne91147592011-04-15 00:35:48 +00004621 E = E->IgnoreParens();
4622
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004623 // Our "symbolic interpreter" is just a dispatch off the currently
4624 // viewed AST node. We then recursively traverse the AST by calling
4625 // EvalAddr and EvalVal appropriately.
4626 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004627 case Stmt::DeclRefExprClass: {
4628 DeclRefExpr *DR = cast<DeclRefExpr>(E);
4629
Richard Smith40f08eb2014-01-30 22:05:38 +00004630 // If we leave the immediate function, the lifetime isn't about to end.
4631 if (DR->refersToEnclosingLocal())
Craig Topperc3ec1492014-05-26 06:22:03 +00004632 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00004633
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004634 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
4635 // If this is a reference variable, follow through to the expression that
4636 // it points to.
4637 if (V->hasLocalStorage() &&
4638 V->getType()->isReferenceType() && V->hasInit()) {
4639 // Add the reference variable to the "trail".
4640 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004641 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004642 }
4643
Craig Topperc3ec1492014-05-26 06:22:03 +00004644 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004645 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004646
Chris Lattner934edb22007-12-28 05:31:15 +00004647 case Stmt::UnaryOperatorClass: {
4648 // The only unary operator that make sense to handle here
4649 // is AddrOf. All others don't make sense as pointers.
4650 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004651
John McCalle3027922010-08-25 11:45:40 +00004652 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004653 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004654 else
Craig Topperc3ec1492014-05-26 06:22:03 +00004655 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004656 }
Mike Stump11289f42009-09-09 15:08:12 +00004657
Chris Lattner934edb22007-12-28 05:31:15 +00004658 case Stmt::BinaryOperatorClass: {
4659 // Handle pointer arithmetic. All other binary operators are not valid
4660 // in this context.
4661 BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00004662 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00004663
John McCalle3027922010-08-25 11:45:40 +00004664 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00004665 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004666
Chris Lattner934edb22007-12-28 05:31:15 +00004667 Expr *Base = B->getLHS();
4668
4669 // Determine which argument is the real pointer base. It could be
4670 // the RHS argument instead of the LHS.
4671 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00004672
Chris Lattner934edb22007-12-28 05:31:15 +00004673 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004674 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004675 }
Steve Naroff2752a172008-09-10 19:17:48 +00004676
Chris Lattner934edb22007-12-28 05:31:15 +00004677 // For conditional operators we need to see if either the LHS or RHS are
4678 // valid DeclRefExpr*s. If one of them is valid, we return it.
4679 case Stmt::ConditionalOperatorClass: {
4680 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004681
Chris Lattner934edb22007-12-28 05:31:15 +00004682 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004683 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
4684 if (Expr *LHSExpr = C->getLHS()) {
4685 // In C++, we can have a throw-expression, which has 'void' type.
4686 if (!LHSExpr->getType()->isVoidType())
4687 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004688 return LHS;
4689 }
Chris Lattner934edb22007-12-28 05:31:15 +00004690
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004691 // In C++, we can have a throw-expression, which has 'void' type.
4692 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00004693 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004694
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004695 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004696 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004697
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004698 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00004699 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004700 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00004701 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004702
4703 case Stmt::AddrLabelExprClass:
4704 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00004705
John McCall28fc7092011-11-10 05:35:25 +00004706 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004707 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
4708 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00004709
Ted Kremenekc3b4c522008-08-07 00:49:01 +00004710 // For casts, we need to handle conversions from arrays to
4711 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00004712 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00004713 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00004714 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00004715 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00004716 case Stmt::CXXStaticCastExprClass:
4717 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00004718 case Stmt::CXXConstCastExprClass:
4719 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8195ad72012-02-23 23:04:32 +00004720 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
4721 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00004722 case CK_LValueToRValue:
4723 case CK_NoOp:
4724 case CK_BaseToDerived:
4725 case CK_DerivedToBase:
4726 case CK_UncheckedDerivedToBase:
4727 case CK_Dynamic:
4728 case CK_CPointerToObjCPointerCast:
4729 case CK_BlockPointerToObjCPointerCast:
4730 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004731 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00004732
4733 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004734 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00004735
Richard Trieudadefde2014-07-02 04:39:38 +00004736 case CK_BitCast:
4737 if (SubExpr->getType()->isAnyPointerType() ||
4738 SubExpr->getType()->isBlockPointerType() ||
4739 SubExpr->getType()->isObjCQualifiedIdType())
4740 return EvalAddr(SubExpr, refVars, ParentDecl);
4741 else
4742 return nullptr;
4743
Eli Friedman8195ad72012-02-23 23:04:32 +00004744 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00004745 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00004746 }
Chris Lattner934edb22007-12-28 05:31:15 +00004747 }
Mike Stump11289f42009-09-09 15:08:12 +00004748
Douglas Gregorfe314812011-06-21 17:03:29 +00004749 case Stmt::MaterializeTemporaryExprClass:
4750 if (Expr *Result = EvalAddr(
4751 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004752 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00004753 return Result;
4754
4755 return E;
4756
Chris Lattner934edb22007-12-28 05:31:15 +00004757 // Everything else: we simply don't reason about them.
4758 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00004759 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00004760 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004761}
Mike Stump11289f42009-09-09 15:08:12 +00004762
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004763
4764/// EvalVal - This function is complements EvalAddr in the mutual recursion.
4765/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004766static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4767 Decl *ParentDecl) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004768do {
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00004769 // We should only be called for evaluating non-pointer expressions, or
4770 // expressions with a pointer type that are not used as references but instead
4771 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00004772
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004773 // Our "symbolic interpreter" is just a dispatch off the currently
4774 // viewed AST node. We then recursively traverse the AST by calling
4775 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00004776
4777 E = E->IgnoreParens();
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004778 switch (E->getStmtClass()) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004779 case Stmt::ImplicitCastExprClass: {
4780 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall2536c6d2010-08-25 10:28:54 +00004781 if (IE->getValueKind() == VK_LValue) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004782 E = IE->getSubExpr();
4783 continue;
4784 }
Craig Topperc3ec1492014-05-26 06:22:03 +00004785 return nullptr;
Ted Kremenekb7861562010-08-04 20:01:07 +00004786 }
4787
John McCall28fc7092011-11-10 05:35:25 +00004788 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004789 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00004790
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004791 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004792 // When we hit a DeclRefExpr we are looking at code that refers to a
4793 // variable's name. If it's not a reference variable we check if it has
4794 // local storage within the function, and if so, return the expression.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004795 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004796
Richard Smith40f08eb2014-01-30 22:05:38 +00004797 // If we leave the immediate function, the lifetime isn't about to end.
4798 if (DR->refersToEnclosingLocal())
Craig Topperc3ec1492014-05-26 06:22:03 +00004799 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00004800
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004801 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
4802 // Check if it refers to itself, e.g. "int& i = i;".
4803 if (V == ParentDecl)
4804 return DR;
4805
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004806 if (V->hasLocalStorage()) {
4807 if (!V->getType()->isReferenceType())
4808 return DR;
4809
4810 // Reference variable, follow through to the expression that
4811 // it points to.
4812 if (V->hasInit()) {
4813 // Add the reference variable to the "trail".
4814 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004815 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004816 }
4817 }
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004818 }
Mike Stump11289f42009-09-09 15:08:12 +00004819
Craig Topperc3ec1492014-05-26 06:22:03 +00004820 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004821 }
Mike Stump11289f42009-09-09 15:08:12 +00004822
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004823 case Stmt::UnaryOperatorClass: {
4824 // The only unary operator that make sense to handle here
4825 // is Deref. All others don't resolve to a "name." This includes
4826 // handling all sorts of rvalues passed to a unary operator.
4827 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004828
John McCalle3027922010-08-25 11:45:40 +00004829 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004830 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004831
Craig Topperc3ec1492014-05-26 06:22:03 +00004832 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004833 }
Mike Stump11289f42009-09-09 15:08:12 +00004834
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004835 case Stmt::ArraySubscriptExprClass: {
4836 // Array subscripts are potential references to data on the stack. We
4837 // retrieve the DeclRefExpr* for the array variable if it indeed
4838 // has local storage.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004839 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004840 }
Mike Stump11289f42009-09-09 15:08:12 +00004841
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004842 case Stmt::ConditionalOperatorClass: {
4843 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004844 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004845 ConditionalOperator *C = cast<ConditionalOperator>(E);
4846
Anders Carlsson801c5c72007-11-30 19:04:31 +00004847 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004848 if (Expr *LHSExpr = C->getLHS()) {
4849 // In C++, we can have a throw-expression, which has 'void' type.
4850 if (!LHSExpr->getType()->isVoidType())
4851 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
4852 return LHS;
4853 }
4854
4855 // In C++, we can have a throw-expression, which has 'void' type.
4856 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00004857 return nullptr;
Anders Carlsson801c5c72007-11-30 19:04:31 +00004858
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004859 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004860 }
Mike Stump11289f42009-09-09 15:08:12 +00004861
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004862 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00004863 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004864 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004865
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004866 // Check for indirect access. We only want direct field accesses.
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00004867 if (M->isArrow())
Craig Topperc3ec1492014-05-26 06:22:03 +00004868 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00004869
4870 // Check whether the member type is itself a reference, in which case
4871 // we're not going to refer to the member, but to what the member refers to.
4872 if (M->getMemberDecl()->getType()->isReferenceType())
Craig Topperc3ec1492014-05-26 06:22:03 +00004873 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00004874
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004875 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004876 }
Mike Stump11289f42009-09-09 15:08:12 +00004877
Douglas Gregorfe314812011-06-21 17:03:29 +00004878 case Stmt::MaterializeTemporaryExprClass:
4879 if (Expr *Result = EvalVal(
4880 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004881 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00004882 return Result;
4883
4884 return E;
4885
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004886 default:
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004887 // Check that we don't return or take the address of a reference to a
4888 // temporary. This is only useful in C++.
4889 if (!E->isTypeDependent() && E->isRValue())
4890 return E;
4891
4892 // Everything else: we simply don't reason about them.
Craig Topperc3ec1492014-05-26 06:22:03 +00004893 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004894 }
Ted Kremenekb7861562010-08-04 20:01:07 +00004895} while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004896}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004897
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004898void
4899Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
4900 SourceLocation ReturnLoc,
4901 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00004902 const AttrVec *Attrs,
4903 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004904 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
4905
4906 // Check if the return value is null but should not be.
Benjamin Kramerae852a62014-02-23 14:34:50 +00004907 if (Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs) &&
4908 CheckNonNullExpr(*this, RetValExp))
4909 Diag(ReturnLoc, diag::warn_null_ret)
4910 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00004911
4912 // C++11 [basic.stc.dynamic.allocation]p4:
4913 // If an allocation function declared with a non-throwing
4914 // exception-specification fails to allocate storage, it shall return
4915 // a null pointer. Any other allocation function that fails to allocate
4916 // storage shall indicate failure only by throwing an exception [...]
4917 if (FD) {
4918 OverloadedOperatorKind Op = FD->getOverloadedOperator();
4919 if (Op == OO_New || Op == OO_Array_New) {
4920 const FunctionProtoType *Proto
4921 = FD->getType()->castAs<FunctionProtoType>();
4922 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
4923 CheckNonNullExpr(*this, RetValExp))
4924 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
4925 << FD << getLangOpts().CPlusPlus11;
4926 }
4927 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004928}
4929
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004930//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
4931
4932/// Check for comparisons of floating point operands using != and ==.
4933/// Issue a warning if these are no self-comparisons, as they are not likely
4934/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00004935void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00004936 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
4937 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004938
4939 // Special case: check for x == x (which is OK).
4940 // Do not emit warnings for such cases.
4941 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
4942 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
4943 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00004944 return;
Mike Stump11289f42009-09-09 15:08:12 +00004945
4946
Ted Kremenekeda40e22007-11-29 00:59:04 +00004947 // Special case: check for comparisons against literals that can be exactly
4948 // represented by APFloat. In such cases, do not emit a warning. This
4949 // is a heuristic: often comparison against such literals are used to
4950 // detect if a value in a variable has not changed. This clearly can
4951 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00004952 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
4953 if (FLL->isExact())
4954 return;
4955 } else
4956 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
4957 if (FLR->isExact())
4958 return;
Mike Stump11289f42009-09-09 15:08:12 +00004959
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004960 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00004961 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00004962 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00004963 return;
Mike Stump11289f42009-09-09 15:08:12 +00004964
David Blaikie1f4ff152012-07-16 20:47:22 +00004965 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00004966 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00004967 return;
Mike Stump11289f42009-09-09 15:08:12 +00004968
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004969 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00004970 Diag(Loc, diag::warn_floatingpoint_eq)
4971 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004972}
John McCallca01b222010-01-04 23:21:16 +00004973
John McCall70aa5392010-01-06 05:24:50 +00004974//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
4975//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00004976
John McCall70aa5392010-01-06 05:24:50 +00004977namespace {
John McCallca01b222010-01-04 23:21:16 +00004978
John McCall70aa5392010-01-06 05:24:50 +00004979/// Structure recording the 'active' range of an integer-valued
4980/// expression.
4981struct IntRange {
4982 /// The number of bits active in the int.
4983 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00004984
John McCall70aa5392010-01-06 05:24:50 +00004985 /// True if the int is known not to have negative values.
4986 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00004987
John McCall70aa5392010-01-06 05:24:50 +00004988 IntRange(unsigned Width, bool NonNegative)
4989 : Width(Width), NonNegative(NonNegative)
4990 {}
John McCallca01b222010-01-04 23:21:16 +00004991
John McCall817d4af2010-11-10 23:38:19 +00004992 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00004993 static IntRange forBoolType() {
4994 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00004995 }
4996
John McCall817d4af2010-11-10 23:38:19 +00004997 /// Returns the range of an opaque value of the given integral type.
4998 static IntRange forValueOfType(ASTContext &C, QualType T) {
4999 return forValueOfCanonicalType(C,
5000 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00005001 }
5002
John McCall817d4af2010-11-10 23:38:19 +00005003 /// Returns the range of an opaque value of a canonical integral type.
5004 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00005005 assert(T->isCanonicalUnqualified());
5006
5007 if (const VectorType *VT = dyn_cast<VectorType>(T))
5008 T = VT->getElementType().getTypePtr();
5009 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5010 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005011 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5012 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00005013
David Majnemer6a426652013-06-07 22:07:20 +00005014 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00005015 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00005016 EnumDecl *Enum = ET->getDecl();
5017 if (!Enum->isCompleteDefinition())
5018 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00005019
David Majnemer6a426652013-06-07 22:07:20 +00005020 unsigned NumPositive = Enum->getNumPositiveBits();
5021 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00005022
David Majnemer6a426652013-06-07 22:07:20 +00005023 if (NumNegative == 0)
5024 return IntRange(NumPositive, true/*NonNegative*/);
5025 else
5026 return IntRange(std::max(NumPositive + 1, NumNegative),
5027 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00005028 }
John McCall70aa5392010-01-06 05:24:50 +00005029
5030 const BuiltinType *BT = cast<BuiltinType>(T);
5031 assert(BT->isInteger());
5032
5033 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5034 }
5035
John McCall817d4af2010-11-10 23:38:19 +00005036 /// Returns the "target" range of a canonical integral type, i.e.
5037 /// the range of values expressible in the type.
5038 ///
5039 /// This matches forValueOfCanonicalType except that enums have the
5040 /// full range of their type, not the range of their enumerators.
5041 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
5042 assert(T->isCanonicalUnqualified());
5043
5044 if (const VectorType *VT = dyn_cast<VectorType>(T))
5045 T = VT->getElementType().getTypePtr();
5046 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5047 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005048 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5049 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00005050 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00005051 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00005052
5053 const BuiltinType *BT = cast<BuiltinType>(T);
5054 assert(BT->isInteger());
5055
5056 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5057 }
5058
5059 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00005060 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00005061 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00005062 L.NonNegative && R.NonNegative);
5063 }
5064
John McCall817d4af2010-11-10 23:38:19 +00005065 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00005066 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00005067 return IntRange(std::min(L.Width, R.Width),
5068 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00005069 }
5070};
5071
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005072static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
5073 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005074 if (value.isSigned() && value.isNegative())
5075 return IntRange(value.getMinSignedBits(), false);
5076
5077 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00005078 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00005079
5080 // isNonNegative() just checks the sign bit without considering
5081 // signedness.
5082 return IntRange(value.getActiveBits(), true);
5083}
5084
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005085static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
5086 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005087 if (result.isInt())
5088 return GetValueRange(C, result.getInt(), MaxWidth);
5089
5090 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00005091 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
5092 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
5093 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
5094 R = IntRange::join(R, El);
5095 }
John McCall70aa5392010-01-06 05:24:50 +00005096 return R;
5097 }
5098
5099 if (result.isComplexInt()) {
5100 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
5101 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
5102 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00005103 }
5104
5105 // This can happen with lossless casts to intptr_t of "based" lvalues.
5106 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00005107 // FIXME: The only reason we need to pass the type in here is to get
5108 // the sign right on this one case. It would be nice if APValue
5109 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005110 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00005111 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00005112}
John McCall70aa5392010-01-06 05:24:50 +00005113
Eli Friedmane6d33952013-07-08 20:20:06 +00005114static QualType GetExprType(Expr *E) {
5115 QualType Ty = E->getType();
5116 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
5117 Ty = AtomicRHS->getValueType();
5118 return Ty;
5119}
5120
John McCall70aa5392010-01-06 05:24:50 +00005121/// Pseudo-evaluate the given integer expression, estimating the
5122/// range of values it might take.
5123///
5124/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005125static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005126 E = E->IgnoreParens();
5127
5128 // Try a full evaluation first.
5129 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00005130 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00005131 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00005132
5133 // I think we only want to look through implicit casts here; if the
5134 // user has an explicit widening cast, we should treat the value as
5135 // being of the new, wider type.
5136 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00005137 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00005138 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
5139
Eli Friedmane6d33952013-07-08 20:20:06 +00005140 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00005141
John McCalle3027922010-08-25 11:45:40 +00005142 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall2ce81ad2010-01-06 22:07:33 +00005143
John McCall70aa5392010-01-06 05:24:50 +00005144 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00005145 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00005146 return OutputTypeRange;
5147
5148 IntRange SubRange
5149 = GetExprRange(C, CE->getSubExpr(),
5150 std::min(MaxWidth, OutputTypeRange.Width));
5151
5152 // Bail out if the subexpr's range is as wide as the cast type.
5153 if (SubRange.Width >= OutputTypeRange.Width)
5154 return OutputTypeRange;
5155
5156 // Otherwise, we take the smaller width, and we're non-negative if
5157 // either the output type or the subexpr is.
5158 return IntRange(SubRange.Width,
5159 SubRange.NonNegative || OutputTypeRange.NonNegative);
5160 }
5161
5162 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5163 // If we can fold the condition, just take that operand.
5164 bool CondResult;
5165 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
5166 return GetExprRange(C, CondResult ? CO->getTrueExpr()
5167 : CO->getFalseExpr(),
5168 MaxWidth);
5169
5170 // Otherwise, conservatively merge.
5171 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
5172 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
5173 return IntRange::join(L, R);
5174 }
5175
5176 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5177 switch (BO->getOpcode()) {
5178
5179 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00005180 case BO_LAnd:
5181 case BO_LOr:
5182 case BO_LT:
5183 case BO_GT:
5184 case BO_LE:
5185 case BO_GE:
5186 case BO_EQ:
5187 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00005188 return IntRange::forBoolType();
5189
John McCallc3688382011-07-13 06:35:24 +00005190 // The type of the assignments is the type of the LHS, so the RHS
5191 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00005192 case BO_MulAssign:
5193 case BO_DivAssign:
5194 case BO_RemAssign:
5195 case BO_AddAssign:
5196 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00005197 case BO_XorAssign:
5198 case BO_OrAssign:
5199 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00005200 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00005201
John McCallc3688382011-07-13 06:35:24 +00005202 // Simple assignments just pass through the RHS, which will have
5203 // been coerced to the LHS type.
5204 case BO_Assign:
5205 // TODO: bitfields?
5206 return GetExprRange(C, BO->getRHS(), MaxWidth);
5207
John McCall70aa5392010-01-06 05:24:50 +00005208 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005209 case BO_PtrMemD:
5210 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00005211 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005212
John McCall2ce81ad2010-01-06 22:07:33 +00005213 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00005214 case BO_And:
5215 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00005216 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
5217 GetExprRange(C, BO->getRHS(), MaxWidth));
5218
John McCall70aa5392010-01-06 05:24:50 +00005219 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00005220 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00005221 // ...except that we want to treat '1 << (blah)' as logically
5222 // positive. It's an important idiom.
5223 if (IntegerLiteral *I
5224 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
5225 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005226 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00005227 return IntRange(R.Width, /*NonNegative*/ true);
5228 }
5229 }
5230 // fallthrough
5231
John McCalle3027922010-08-25 11:45:40 +00005232 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00005233 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005234
John McCall2ce81ad2010-01-06 22:07:33 +00005235 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00005236 case BO_Shr:
5237 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00005238 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5239
5240 // If the shift amount is a positive constant, drop the width by
5241 // that much.
5242 llvm::APSInt shift;
5243 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
5244 shift.isNonNegative()) {
5245 unsigned zext = shift.getZExtValue();
5246 if (zext >= L.Width)
5247 L.Width = (L.NonNegative ? 0 : 1);
5248 else
5249 L.Width -= zext;
5250 }
5251
5252 return L;
5253 }
5254
5255 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00005256 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00005257 return GetExprRange(C, BO->getRHS(), MaxWidth);
5258
John McCall2ce81ad2010-01-06 22:07:33 +00005259 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00005260 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00005261 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00005262 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005263 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005264
John McCall51431812011-07-14 22:39:48 +00005265 // The width of a division result is mostly determined by the size
5266 // of the LHS.
5267 case BO_Div: {
5268 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005269 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005270 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5271
5272 // If the divisor is constant, use that.
5273 llvm::APSInt divisor;
5274 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
5275 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
5276 if (log2 >= L.Width)
5277 L.Width = (L.NonNegative ? 0 : 1);
5278 else
5279 L.Width = std::min(L.Width - log2, MaxWidth);
5280 return L;
5281 }
5282
5283 // Otherwise, just use the LHS's width.
5284 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5285 return IntRange(L.Width, L.NonNegative && R.NonNegative);
5286 }
5287
5288 // The result of a remainder can't be larger than the result of
5289 // either side.
5290 case BO_Rem: {
5291 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005292 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005293 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5294 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5295
5296 IntRange meet = IntRange::meet(L, R);
5297 meet.Width = std::min(meet.Width, MaxWidth);
5298 return meet;
5299 }
5300
5301 // The default behavior is okay for these.
5302 case BO_Mul:
5303 case BO_Add:
5304 case BO_Xor:
5305 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00005306 break;
5307 }
5308
John McCall51431812011-07-14 22:39:48 +00005309 // The default case is to treat the operation as if it were closed
5310 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00005311 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5312 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
5313 return IntRange::join(L, R);
5314 }
5315
5316 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5317 switch (UO->getOpcode()) {
5318 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00005319 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00005320 return IntRange::forBoolType();
5321
5322 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005323 case UO_Deref:
5324 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00005325 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005326
5327 default:
5328 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
5329 }
5330 }
5331
Ted Kremeneka553fbf2013-10-14 18:55:27 +00005332 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5333 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
5334
John McCalld25db7e2013-05-06 21:39:12 +00005335 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00005336 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00005337 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00005338
Eli Friedmane6d33952013-07-08 20:20:06 +00005339 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005340}
John McCall263a48b2010-01-04 23:31:57 +00005341
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005342static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005343 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00005344}
5345
John McCall263a48b2010-01-04 23:31:57 +00005346/// Checks whether the given value, which currently has the given
5347/// source semantics, has the same value when coerced through the
5348/// target semantics.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005349static bool IsSameFloatAfterCast(const llvm::APFloat &value,
5350 const llvm::fltSemantics &Src,
5351 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005352 llvm::APFloat truncated = value;
5353
5354 bool ignored;
5355 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
5356 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
5357
5358 return truncated.bitwiseIsEqual(value);
5359}
5360
5361/// Checks whether the given value, which currently has the given
5362/// source semantics, has the same value when coerced through the
5363/// target semantics.
5364///
5365/// The value might be a vector of floats (or a complex number).
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005366static bool IsSameFloatAfterCast(const APValue &value,
5367 const llvm::fltSemantics &Src,
5368 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005369 if (value.isFloat())
5370 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
5371
5372 if (value.isVector()) {
5373 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
5374 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
5375 return false;
5376 return true;
5377 }
5378
5379 assert(value.isComplexFloat());
5380 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
5381 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
5382}
5383
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005384static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005385
Ted Kremenek6274be42010-09-23 21:43:44 +00005386static bool IsZero(Sema &S, Expr *E) {
5387 // Suppress cases where we are comparing against an enum constant.
5388 if (const DeclRefExpr *DR =
5389 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
5390 if (isa<EnumConstantDecl>(DR->getDecl()))
5391 return false;
5392
5393 // Suppress cases where the '0' value is expanded from a macro.
5394 if (E->getLocStart().isMacroID())
5395 return false;
5396
John McCallcc7e5bf2010-05-06 08:58:33 +00005397 llvm::APSInt Value;
5398 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
5399}
5400
John McCall2551c1b2010-10-06 00:25:24 +00005401static bool HasEnumType(Expr *E) {
5402 // Strip off implicit integral promotions.
5403 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005404 if (ICE->getCastKind() != CK_IntegralCast &&
5405 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00005406 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005407 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00005408 }
5409
5410 return E->getType()->isEnumeralType();
5411}
5412
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005413static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00005414 // Disable warning in template instantiations.
5415 if (!S.ActiveTemplateInstantiations.empty())
5416 return;
5417
John McCalle3027922010-08-25 11:45:40 +00005418 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00005419 if (E->isValueDependent())
5420 return;
5421
John McCalle3027922010-08-25 11:45:40 +00005422 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005423 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005424 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005425 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005426 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005427 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005428 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005429 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005430 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005431 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005432 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005433 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005434 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005435 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005436 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005437 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5438 }
5439}
5440
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005441static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005442 Expr *Constant, Expr *Other,
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005443 llvm::APSInt Value,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005444 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00005445 // Disable warning in template instantiations.
5446 if (!S.ActiveTemplateInstantiations.empty())
5447 return;
5448
Richard Trieu0f097742014-04-04 04:13:47 +00005449 // TODO: Investigate using GetExprRange() to get tighter bounds
5450 // on the bit ranges.
5451 QualType OtherT = Other->getType();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005452 if (const AtomicType *AT = dyn_cast<AtomicType>(OtherT))
5453 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00005454 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
5455 unsigned OtherWidth = OtherRange.Width;
5456
5457 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
5458
Richard Trieu560910c2012-11-14 22:50:24 +00005459 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00005460 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00005461 return;
5462
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005463 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00005464 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00005465
Richard Trieu0f097742014-04-04 04:13:47 +00005466 // Used for diagnostic printout.
5467 enum {
5468 LiteralConstant = 0,
5469 CXXBoolLiteralTrue,
5470 CXXBoolLiteralFalse
5471 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00005472
Richard Trieu0f097742014-04-04 04:13:47 +00005473 if (!OtherIsBooleanType) {
5474 QualType ConstantT = Constant->getType();
5475 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00005476
Richard Trieu0f097742014-04-04 04:13:47 +00005477 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
5478 return;
5479 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
5480 "comparison with non-integer type");
5481
5482 bool ConstantSigned = ConstantT->isSignedIntegerType();
5483 bool CommonSigned = CommonT->isSignedIntegerType();
5484
5485 bool EqualityOnly = false;
5486
5487 if (CommonSigned) {
5488 // The common type is signed, therefore no signed to unsigned conversion.
5489 if (!OtherRange.NonNegative) {
5490 // Check that the constant is representable in type OtherT.
5491 if (ConstantSigned) {
5492 if (OtherWidth >= Value.getMinSignedBits())
5493 return;
5494 } else { // !ConstantSigned
5495 if (OtherWidth >= Value.getActiveBits() + 1)
5496 return;
5497 }
5498 } else { // !OtherSigned
5499 // Check that the constant is representable in type OtherT.
5500 // Negative values are out of range.
5501 if (ConstantSigned) {
5502 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
5503 return;
5504 } else { // !ConstantSigned
5505 if (OtherWidth >= Value.getActiveBits())
5506 return;
5507 }
Richard Trieu560910c2012-11-14 22:50:24 +00005508 }
Richard Trieu0f097742014-04-04 04:13:47 +00005509 } else { // !CommonSigned
5510 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00005511 if (OtherWidth >= Value.getActiveBits())
5512 return;
Craig Toppercf360162014-06-18 05:13:11 +00005513 } else { // OtherSigned
5514 assert(!ConstantSigned &&
5515 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00005516 // Check to see if the constant is representable in OtherT.
5517 if (OtherWidth > Value.getActiveBits())
5518 return;
5519 // Check to see if the constant is equivalent to a negative value
5520 // cast to CommonT.
5521 if (S.Context.getIntWidth(ConstantT) ==
5522 S.Context.getIntWidth(CommonT) &&
5523 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
5524 return;
5525 // The constant value rests between values that OtherT can represent
5526 // after conversion. Relational comparison still works, but equality
5527 // comparisons will be tautological.
5528 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00005529 }
5530 }
Richard Trieu0f097742014-04-04 04:13:47 +00005531
5532 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
5533
5534 if (op == BO_EQ || op == BO_NE) {
5535 IsTrue = op == BO_NE;
5536 } else if (EqualityOnly) {
5537 return;
5538 } else if (RhsConstant) {
5539 if (op == BO_GT || op == BO_GE)
5540 IsTrue = !PositiveConstant;
5541 else // op == BO_LT || op == BO_LE
5542 IsTrue = PositiveConstant;
5543 } else {
5544 if (op == BO_LT || op == BO_LE)
5545 IsTrue = !PositiveConstant;
5546 else // op == BO_GT || op == BO_GE
5547 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00005548 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005549 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00005550 // Other isKnownToHaveBooleanValue
5551 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
5552 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
5553 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
5554
5555 static const struct LinkedConditions {
5556 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
5557 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
5558 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
5559 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
5560 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
5561 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
5562
5563 } TruthTable = {
5564 // Constant on LHS. | Constant on RHS. |
5565 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
5566 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
5567 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
5568 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
5569 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
5570 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
5571 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
5572 };
5573
5574 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
5575
5576 enum ConstantValue ConstVal = Zero;
5577 if (Value.isUnsigned() || Value.isNonNegative()) {
5578 if (Value == 0) {
5579 LiteralOrBoolConstant =
5580 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
5581 ConstVal = Zero;
5582 } else if (Value == 1) {
5583 LiteralOrBoolConstant =
5584 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
5585 ConstVal = One;
5586 } else {
5587 LiteralOrBoolConstant = LiteralConstant;
5588 ConstVal = GT_One;
5589 }
5590 } else {
5591 ConstVal = LT_Zero;
5592 }
5593
5594 CompareBoolWithConstantResult CmpRes;
5595
5596 switch (op) {
5597 case BO_LT:
5598 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
5599 break;
5600 case BO_GT:
5601 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
5602 break;
5603 case BO_LE:
5604 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
5605 break;
5606 case BO_GE:
5607 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
5608 break;
5609 case BO_EQ:
5610 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
5611 break;
5612 case BO_NE:
5613 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
5614 break;
5615 default:
5616 CmpRes = Unkwn;
5617 break;
5618 }
5619
5620 if (CmpRes == AFals) {
5621 IsTrue = false;
5622 } else if (CmpRes == ATrue) {
5623 IsTrue = true;
5624 } else {
5625 return;
5626 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005627 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005628
5629 // If this is a comparison to an enum constant, include that
5630 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00005631 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005632 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
5633 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
5634
5635 SmallString<64> PrettySourceValue;
5636 llvm::raw_svector_ostream OS(PrettySourceValue);
5637 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00005638 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005639 else
5640 OS << Value;
5641
Richard Trieu0f097742014-04-04 04:13:47 +00005642 S.DiagRuntimeBehavior(
5643 E->getOperatorLoc(), E,
5644 S.PDiag(diag::warn_out_of_range_compare)
5645 << OS.str() << LiteralOrBoolConstant
5646 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
5647 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005648}
5649
John McCallcc7e5bf2010-05-06 08:58:33 +00005650/// Analyze the operands of the given comparison. Implements the
5651/// fallback case from AnalyzeComparison.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005652static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00005653 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5654 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00005655}
John McCall263a48b2010-01-04 23:31:57 +00005656
John McCallca01b222010-01-04 23:21:16 +00005657/// \brief Implements -Wsign-compare.
5658///
Richard Trieu82402a02011-09-15 21:56:47 +00005659/// \param E the binary operator to check for warnings
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005660static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005661 // The type the comparison is being performed in.
5662 QualType T = E->getLHS()->getType();
5663 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
5664 && "comparison with mismatched types");
Fariborz Jahanian282071e2012-09-18 17:46:26 +00005665 if (E->isValueDependent())
5666 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005667
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005668 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
5669 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005670
5671 bool IsComparisonConstant = false;
5672
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005673 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005674 // of 'true' or 'false'.
5675 if (T->isIntegralType(S.Context)) {
5676 llvm::APSInt RHSValue;
5677 bool IsRHSIntegralLiteral =
5678 RHS->isIntegerConstantExpr(RHSValue, S.Context);
5679 llvm::APSInt LHSValue;
5680 bool IsLHSIntegralLiteral =
5681 LHS->isIntegerConstantExpr(LHSValue, S.Context);
5682 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
5683 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
5684 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
5685 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
5686 else
5687 IsComparisonConstant =
5688 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005689 } else if (!T->hasUnsignedIntegerRepresentation())
5690 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005691
John McCallcc7e5bf2010-05-06 08:58:33 +00005692 // We don't do anything special if this isn't an unsigned integral
5693 // comparison: we're only interested in integral comparisons, and
5694 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00005695 //
5696 // We also don't care about value-dependent expressions or expressions
5697 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005698 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00005699 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005700
John McCallcc7e5bf2010-05-06 08:58:33 +00005701 // Check to see if one of the (unmodified) operands is of different
5702 // signedness.
5703 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00005704 if (LHS->getType()->hasSignedIntegerRepresentation()) {
5705 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00005706 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00005707 signedOperand = LHS;
5708 unsignedOperand = RHS;
5709 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
5710 signedOperand = RHS;
5711 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00005712 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00005713 CheckTrivialUnsignedComparison(S, E);
5714 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005715 }
5716
John McCallcc7e5bf2010-05-06 08:58:33 +00005717 // Otherwise, calculate the effective range of the signed operand.
5718 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00005719
John McCallcc7e5bf2010-05-06 08:58:33 +00005720 // Go ahead and analyze implicit conversions in the operands. Note
5721 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00005722 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
5723 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00005724
John McCallcc7e5bf2010-05-06 08:58:33 +00005725 // If the signed range is non-negative, -Wsign-compare won't fire,
5726 // but we should still check for comparisons which are always true
5727 // or false.
5728 if (signedRange.NonNegative)
5729 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005730
5731 // For (in)equality comparisons, if the unsigned operand is a
5732 // constant which cannot collide with a overflowed signed operand,
5733 // then reinterpreting the signed operand as unsigned will not
5734 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00005735 if (E->isEqualityOp()) {
5736 unsigned comparisonWidth = S.Context.getIntWidth(T);
5737 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00005738
John McCallcc7e5bf2010-05-06 08:58:33 +00005739 // We should never be unable to prove that the unsigned operand is
5740 // non-negative.
5741 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
5742
5743 if (unsignedRange.Width < comparisonWidth)
5744 return;
5745 }
5746
Douglas Gregorbfb4a212012-05-01 01:53:49 +00005747 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
5748 S.PDiag(diag::warn_mixed_sign_comparison)
5749 << LHS->getType() << RHS->getType()
5750 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00005751}
5752
John McCall1f425642010-11-11 03:21:53 +00005753/// Analyzes an attempt to assign the given value to a bitfield.
5754///
5755/// Returns true if there was something fishy about the attempt.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005756static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
5757 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00005758 assert(Bitfield->isBitField());
5759 if (Bitfield->isInvalidDecl())
5760 return false;
5761
John McCalldeebbcf2010-11-11 05:33:51 +00005762 // White-list bool bitfields.
5763 if (Bitfield->getType()->isBooleanType())
5764 return false;
5765
Douglas Gregor789adec2011-02-04 13:09:01 +00005766 // Ignore value- or type-dependent expressions.
5767 if (Bitfield->getBitWidth()->isValueDependent() ||
5768 Bitfield->getBitWidth()->isTypeDependent() ||
5769 Init->isValueDependent() ||
5770 Init->isTypeDependent())
5771 return false;
5772
John McCall1f425642010-11-11 03:21:53 +00005773 Expr *OriginalInit = Init->IgnoreParenImpCasts();
5774
Richard Smith5fab0c92011-12-28 19:48:30 +00005775 llvm::APSInt Value;
5776 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00005777 return false;
5778
John McCall1f425642010-11-11 03:21:53 +00005779 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00005780 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00005781
5782 if (OriginalWidth <= FieldWidth)
5783 return false;
5784
Eli Friedmanc267a322012-01-26 23:11:39 +00005785 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00005786 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00005787 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00005788
Eli Friedmanc267a322012-01-26 23:11:39 +00005789 // Check whether the stored value is equal to the original value.
5790 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00005791 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00005792 return false;
5793
Eli Friedmanc267a322012-01-26 23:11:39 +00005794 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00005795 // therefore don't strictly fit into a signed bitfield of width 1.
5796 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00005797 return false;
5798
John McCall1f425642010-11-11 03:21:53 +00005799 std::string PrettyValue = Value.toString(10);
5800 std::string PrettyTrunc = TruncatedValue.toString(10);
5801
5802 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
5803 << PrettyValue << PrettyTrunc << OriginalInit->getType()
5804 << Init->getSourceRange();
5805
5806 return true;
5807}
5808
John McCalld2a53122010-11-09 23:24:47 +00005809/// Analyze the given simple or compound assignment for warning-worthy
5810/// operations.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005811static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00005812 // Just recurse on the LHS.
5813 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5814
5815 // We want to recurse on the RHS as normal unless we're assigning to
5816 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00005817 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005818 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00005819 E->getOperatorLoc())) {
5820 // Recurse, ignoring any implicit conversions on the RHS.
5821 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
5822 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00005823 }
5824 }
5825
5826 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
5827}
5828
John McCall263a48b2010-01-04 23:31:57 +00005829/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005830static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00005831 SourceLocation CContext, unsigned diag,
5832 bool pruneControlFlow = false) {
5833 if (pruneControlFlow) {
5834 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5835 S.PDiag(diag)
5836 << SourceType << T << E->getSourceRange()
5837 << SourceRange(CContext));
5838 return;
5839 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00005840 S.Diag(E->getExprLoc(), diag)
5841 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
5842}
5843
Chandler Carruth7f3654f2011-04-05 06:47:57 +00005844/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005845static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00005846 SourceLocation CContext, unsigned diag,
5847 bool pruneControlFlow = false) {
5848 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00005849}
5850
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005851/// Diagnose an implicit cast from a literal expression. Does not warn when the
5852/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00005853void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
5854 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005855 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00005856 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005857 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00005858 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
5859 T->hasUnsignedIntegerRepresentation());
5860 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00005861 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005862 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00005863 return;
5864
Eli Friedman07185912013-08-29 23:44:43 +00005865 // FIXME: Force the precision of the source value down so we don't print
5866 // digits which are usually useless (we don't really care here if we
5867 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
5868 // would automatically print the shortest representation, but it's a bit
5869 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00005870 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00005871 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
5872 precision = (precision * 59 + 195) / 196;
5873 Value.toString(PrettySourceValue, precision);
5874
David Blaikie9b88cc02012-05-15 17:18:27 +00005875 SmallString<16> PrettyTargetValue;
David Blaikie7555b6a2012-05-15 16:56:36 +00005876 if (T->isSpecificBuiltinType(BuiltinType::Bool))
5877 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
5878 else
David Blaikie9b88cc02012-05-15 17:18:27 +00005879 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00005880
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005881 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikie7555b6a2012-05-15 16:56:36 +00005882 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
5883 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00005884}
5885
John McCall18a2c2c2010-11-09 22:22:12 +00005886std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
5887 if (!Range.Width) return "0";
5888
5889 llvm::APSInt ValueInRange = Value;
5890 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00005891 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00005892 return ValueInRange.toString(10);
5893}
5894
Hans Wennborgf4ad2322012-08-28 15:44:30 +00005895static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
5896 if (!isa<ImplicitCastExpr>(Ex))
5897 return false;
5898
5899 Expr *InnerE = Ex->IgnoreParenImpCasts();
5900 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
5901 const Type *Source =
5902 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5903 if (Target->isDependentType())
5904 return false;
5905
5906 const BuiltinType *FloatCandidateBT =
5907 dyn_cast<BuiltinType>(ToBool ? Source : Target);
5908 const Type *BoolCandidateType = ToBool ? Target : Source;
5909
5910 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
5911 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
5912}
5913
5914void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
5915 SourceLocation CC) {
5916 unsigned NumArgs = TheCall->getNumArgs();
5917 for (unsigned i = 0; i < NumArgs; ++i) {
5918 Expr *CurrA = TheCall->getArg(i);
5919 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
5920 continue;
5921
5922 bool IsSwapped = ((i > 0) &&
5923 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
5924 IsSwapped |= ((i < (NumArgs - 1)) &&
5925 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
5926 if (IsSwapped) {
5927 // Warn on this floating-point to bool conversion.
5928 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
5929 CurrA->getType(), CC,
5930 diag::warn_impcast_floating_point_to_bool);
5931 }
5932 }
5933}
5934
John McCallcc7e5bf2010-05-06 08:58:33 +00005935void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00005936 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005937 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00005938
John McCallcc7e5bf2010-05-06 08:58:33 +00005939 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
5940 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
5941 if (Source == Target) return;
5942 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00005943
Chandler Carruthc22845a2011-07-26 05:40:03 +00005944 // If the conversion context location is invalid don't complain. We also
5945 // don't want to emit a warning if the issue occurs from the expansion of
5946 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
5947 // delay this check as long as possible. Once we detect we are in that
5948 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005949 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00005950 return;
5951
Richard Trieu021baa32011-09-23 20:10:00 +00005952 // Diagnose implicit casts to bool.
5953 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
5954 if (isa<StringLiteral>(E))
5955 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00005956 // and expressions, for instance, assert(0 && "error here"), are
5957 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00005958 return DiagnoseImpCast(S, E, T, CC,
5959 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00005960 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
5961 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
5962 // This covers the literal expressions that evaluate to Objective-C
5963 // objects.
5964 return DiagnoseImpCast(S, E, T, CC,
5965 diag::warn_impcast_objective_c_literal_to_bool);
5966 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00005967 if (Source->isPointerType() || Source->canDecayToPointerType()) {
5968 // Warn on pointer to bool conversion that is always true.
5969 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
5970 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00005971 }
Richard Trieu021baa32011-09-23 20:10:00 +00005972 }
John McCall263a48b2010-01-04 23:31:57 +00005973
5974 // Strip vector types.
5975 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005976 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005977 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005978 return;
John McCallacf0ee52010-10-08 02:01:28 +00005979 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005980 }
Chris Lattneree7286f2011-06-14 04:51:15 +00005981
5982 // If the vector cast is cast between two vectors of the same size, it is
5983 // a bitcast, not a conversion.
5984 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
5985 return;
John McCall263a48b2010-01-04 23:31:57 +00005986
5987 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
5988 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
5989 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00005990 if (auto VecTy = dyn_cast<VectorType>(Target))
5991 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00005992
5993 // Strip complex types.
5994 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005995 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005996 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005997 return;
5998
John McCallacf0ee52010-10-08 02:01:28 +00005999 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006000 }
John McCall263a48b2010-01-04 23:31:57 +00006001
6002 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
6003 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
6004 }
6005
6006 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
6007 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
6008
6009 // If the source is floating point...
6010 if (SourceBT && SourceBT->isFloatingPoint()) {
6011 // ...and the target is floating point...
6012 if (TargetBT && TargetBT->isFloatingPoint()) {
6013 // ...then warn if we're dropping FP rank.
6014
6015 // Builtin FP kinds are ordered by increasing FP rank.
6016 if (SourceBT->getKind() > TargetBT->getKind()) {
6017 // Don't warn about float constants that are precisely
6018 // representable in the target type.
6019 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00006020 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00006021 // Value might be a float, a float vector, or a float complex.
6022 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00006023 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
6024 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00006025 return;
6026 }
6027
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006028 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006029 return;
6030
John McCallacf0ee52010-10-08 02:01:28 +00006031 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall263a48b2010-01-04 23:31:57 +00006032 }
6033 return;
6034 }
6035
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006036 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00006037 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006038 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006039 return;
6040
Chandler Carruth22c7a792011-02-17 11:05:49 +00006041 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00006042 // We also want to warn on, e.g., "int i = -1.234"
6043 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
6044 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
6045 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
6046
Chandler Carruth016ef402011-04-10 08:36:24 +00006047 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
6048 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00006049 } else {
6050 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
6051 }
6052 }
John McCall263a48b2010-01-04 23:31:57 +00006053
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006054 // If the target is bool, warn if expr is a function or method call.
6055 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
6056 isa<CallExpr>(E)) {
6057 // Check last argument of function call to see if it is an
6058 // implicit cast from a type matching the type the result
6059 // is being cast to.
6060 CallExpr *CEx = cast<CallExpr>(E);
6061 unsigned NumArgs = CEx->getNumArgs();
6062 if (NumArgs > 0) {
6063 Expr *LastA = CEx->getArg(NumArgs - 1);
6064 Expr *InnerE = LastA->IgnoreParenImpCasts();
6065 const Type *InnerType =
6066 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6067 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
6068 // Warn on this floating-point to bool conversion
6069 DiagnoseImpCast(S, E, T, CC,
6070 diag::warn_impcast_floating_point_to_bool);
6071 }
6072 }
6073 }
John McCall263a48b2010-01-04 23:31:57 +00006074 return;
6075 }
6076
Richard Trieubeaf3452011-05-29 19:59:02 +00006077 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
David Blaikie9366d2b2012-06-19 21:19:06 +00006078 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
David Blaikiea1edff02012-11-08 00:41:20 +00006079 && !Target->isBlockPointerType() && !Target->isMemberPointerType()
David Blaikiebcd4b552013-02-16 00:56:22 +00006080 && Target->isScalarType() && !Target->isNullPtrType()) {
David Blaikieae12b182012-03-16 20:30:12 +00006081 SourceLocation Loc = E->getSourceRange().getBegin();
6082 if (Loc.isMacroID())
6083 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
David Blaikie18e9ac72012-05-15 21:57:38 +00006084 if (!Loc.isMacroID() || CC.isMacroID())
6085 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
6086 << T << clang::SourceRange(CC)
Richard Smithf7ec86a2013-09-20 00:27:40 +00006087 << FixItHint::CreateReplacement(Loc,
6088 S.getFixItZeroLiteralForType(T, Loc));
Richard Trieubeaf3452011-05-29 19:59:02 +00006089 }
6090
David Blaikie9366d2b2012-06-19 21:19:06 +00006091 if (!Source->isIntegerType() || !Target->isIntegerType())
6092 return;
6093
David Blaikie7555b6a2012-05-15 16:56:36 +00006094 // TODO: remove this early return once the false positives for constant->bool
6095 // in templates, macros, etc, are reduced or removed.
6096 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
6097 return;
6098
John McCallcc7e5bf2010-05-06 08:58:33 +00006099 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00006100 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00006101
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006102 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00006103 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006104 // TODO: this should happen for bitfield stores, too.
6105 llvm::APSInt Value(32);
6106 if (E->isIntegerConstantExpr(Value, S.Context)) {
6107 if (S.SourceMgr.isInSystemMacro(CC))
6108 return;
6109
John McCall18a2c2c2010-11-09 22:22:12 +00006110 std::string PrettySourceValue = Value.toString(10);
6111 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006112
Ted Kremenek33ba9952011-10-22 02:37:33 +00006113 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6114 S.PDiag(diag::warn_impcast_integer_precision_constant)
6115 << PrettySourceValue << PrettyTargetValue
6116 << E->getType() << T << E->getSourceRange()
6117 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00006118 return;
6119 }
6120
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006121 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
6122 if (S.SourceMgr.isInSystemMacro(CC))
6123 return;
6124
David Blaikie9455da02012-04-12 22:40:54 +00006125 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00006126 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
6127 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00006128 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00006129 }
6130
6131 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
6132 (!TargetRange.NonNegative && SourceRange.NonNegative &&
6133 SourceRange.Width == TargetRange.Width)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006134
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006135 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006136 return;
6137
John McCallcc7e5bf2010-05-06 08:58:33 +00006138 unsigned DiagID = diag::warn_impcast_integer_sign;
6139
6140 // Traditionally, gcc has warned about this under -Wsign-compare.
6141 // We also want to warn about it in -Wconversion.
6142 // So if -Wconversion is off, use a completely identical diagnostic
6143 // in the sign-compare group.
6144 // The conditional-checking code will
6145 if (ICContext) {
6146 DiagID = diag::warn_impcast_integer_sign_conditional;
6147 *ICContext = true;
6148 }
6149
John McCallacf0ee52010-10-08 02:01:28 +00006150 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00006151 }
6152
Douglas Gregora78f1932011-02-22 02:45:07 +00006153 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00006154 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
6155 // type, to give us better diagnostics.
6156 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00006157 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00006158 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6159 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
6160 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
6161 SourceType = S.Context.getTypeDeclType(Enum);
6162 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
6163 }
6164 }
6165
Douglas Gregora78f1932011-02-22 02:45:07 +00006166 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
6167 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00006168 if (SourceEnum->getDecl()->hasNameForLinkage() &&
6169 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006170 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006171 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006172 return;
6173
Douglas Gregor364f7db2011-03-12 00:14:31 +00006174 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00006175 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006176 }
Douglas Gregora78f1932011-02-22 02:45:07 +00006177
John McCall263a48b2010-01-04 23:31:57 +00006178 return;
6179}
6180
David Blaikie18e9ac72012-05-15 21:57:38 +00006181void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6182 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006183
6184void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00006185 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006186 E = E->IgnoreParenImpCasts();
6187
6188 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00006189 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006190
John McCallacf0ee52010-10-08 02:01:28 +00006191 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006192 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006193 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00006194 return;
6195}
6196
David Blaikie18e9ac72012-05-15 21:57:38 +00006197void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6198 SourceLocation CC, QualType T) {
John McCallacf0ee52010-10-08 02:01:28 +00006199 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006200
6201 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00006202 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
6203 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006204
6205 // If -Wconversion would have warned about either of the candidates
6206 // for a signedness conversion to the context type...
6207 if (!Suspicious) return;
6208
6209 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006210 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00006211 return;
6212
John McCallcc7e5bf2010-05-06 08:58:33 +00006213 // ...then check whether it would have warned about either of the
6214 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00006215 if (E->getType() == T) return;
6216
6217 Suspicious = false;
6218 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
6219 E->getType(), CC, &Suspicious);
6220 if (!Suspicious)
6221 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00006222 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006223}
6224
6225/// AnalyzeImplicitConversions - Find and report any interesting
6226/// implicit conversions in the given expression. There are a couple
6227/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00006228void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00006229 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00006230 Expr *E = OrigE->IgnoreParenImpCasts();
6231
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00006232 if (E->isTypeDependent() || E->isValueDependent())
6233 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00006234
John McCallcc7e5bf2010-05-06 08:58:33 +00006235 // For conditional operators, we analyze the arguments as if they
6236 // were being fed directly into the output.
6237 if (isa<ConditionalOperator>(E)) {
6238 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00006239 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006240 return;
6241 }
6242
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006243 // Check implicit argument conversions for function calls.
6244 if (CallExpr *Call = dyn_cast<CallExpr>(E))
6245 CheckImplicitArgumentConversions(S, Call, CC);
6246
John McCallcc7e5bf2010-05-06 08:58:33 +00006247 // Go ahead and check any implicit conversions we might have skipped.
6248 // The non-canonical typecheck is just an optimization;
6249 // CheckImplicitConversion will filter out dead implicit conversions.
6250 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006251 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006252
6253 // Now continue drilling into this expression.
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006254
6255 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006256 if (POE->getResultExpr())
6257 E = POE->getResultExpr();
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006258 }
6259
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006260 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
6261 return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
6262
John McCallcc7e5bf2010-05-06 08:58:33 +00006263 // Skip past explicit casts.
6264 if (isa<ExplicitCastExpr>(E)) {
6265 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00006266 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006267 }
6268
John McCalld2a53122010-11-09 23:24:47 +00006269 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6270 // Do a somewhat different check with comparison operators.
6271 if (BO->isComparisonOp())
6272 return AnalyzeComparison(S, BO);
6273
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006274 // And with simple assignments.
6275 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00006276 return AnalyzeAssignment(S, BO);
6277 }
John McCallcc7e5bf2010-05-06 08:58:33 +00006278
6279 // These break the otherwise-useful invariant below. Fortunately,
6280 // we don't really need to recurse into them, because any internal
6281 // expressions should have been analyzed already when they were
6282 // built into statements.
6283 if (isa<StmtExpr>(E)) return;
6284
6285 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00006286 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00006287
6288 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00006289 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00006290 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00006291 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Richard Trieu021baa32011-09-23 20:10:00 +00006292 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor73456262012-02-09 10:18:50 +00006293 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00006294 if (!ChildExpr)
6295 continue;
6296
Richard Trieu955231d2014-01-25 01:10:35 +00006297 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00006298 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00006299 // Ignore checking string literals that are in logical and operators.
6300 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00006301 continue;
6302 AnalyzeImplicitConversions(S, ChildExpr, CC);
6303 }
John McCallcc7e5bf2010-05-06 08:58:33 +00006304}
6305
6306} // end anonymous namespace
6307
Richard Trieu3bb8b562014-02-26 02:36:06 +00006308enum {
6309 AddressOf,
6310 FunctionPointer,
6311 ArrayPointer
6312};
6313
Richard Trieuc1888e02014-06-28 23:25:37 +00006314// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
6315// Returns true when emitting a warning about taking the address of a reference.
6316static bool CheckForReference(Sema &SemaRef, const Expr *E,
6317 PartialDiagnostic PD) {
6318 E = E->IgnoreParenImpCasts();
6319
6320 const FunctionDecl *FD = nullptr;
6321
6322 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
6323 if (!DRE->getDecl()->getType()->isReferenceType())
6324 return false;
6325 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6326 if (!M->getMemberDecl()->getType()->isReferenceType())
6327 return false;
6328 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
6329 if (!Call->getCallReturnType()->isReferenceType())
6330 return false;
6331 FD = Call->getDirectCallee();
6332 } else {
6333 return false;
6334 }
6335
6336 SemaRef.Diag(E->getExprLoc(), PD);
6337
6338 // If possible, point to location of function.
6339 if (FD) {
6340 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
6341 }
6342
6343 return true;
6344}
6345
Richard Trieu3bb8b562014-02-26 02:36:06 +00006346/// \brief Diagnose pointers that are always non-null.
6347/// \param E the expression containing the pointer
6348/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
6349/// compared to a null pointer
6350/// \param IsEqual True when the comparison is equal to a null pointer
6351/// \param Range Extra SourceRange to highlight in the diagnostic
6352void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
6353 Expr::NullPointerConstantKind NullKind,
6354 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00006355 if (!E)
6356 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006357
6358 // Don't warn inside macros.
6359 if (E->getExprLoc().isMacroID())
6360 return;
6361 E = E->IgnoreImpCasts();
6362
6363 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
6364
Richard Trieuf7432752014-06-06 21:39:26 +00006365 if (isa<CXXThisExpr>(E)) {
6366 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
6367 : diag::warn_this_bool_conversion;
6368 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
6369 return;
6370 }
6371
Richard Trieu3bb8b562014-02-26 02:36:06 +00006372 bool IsAddressOf = false;
6373
6374 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6375 if (UO->getOpcode() != UO_AddrOf)
6376 return;
6377 IsAddressOf = true;
6378 E = UO->getSubExpr();
6379 }
6380
Richard Trieuc1888e02014-06-28 23:25:37 +00006381 if (IsAddressOf) {
6382 unsigned DiagID = IsCompare
6383 ? diag::warn_address_of_reference_null_compare
6384 : diag::warn_address_of_reference_bool_conversion;
6385 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
6386 << IsEqual;
6387 if (CheckForReference(*this, E, PD)) {
6388 return;
6389 }
6390 }
6391
Richard Trieu3bb8b562014-02-26 02:36:06 +00006392 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00006393 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006394 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
6395 D = R->getDecl();
6396 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6397 D = M->getMemberDecl();
6398 }
6399
6400 // Weak Decls can be null.
6401 if (!D || D->isWeak())
6402 return;
6403
6404 QualType T = D->getType();
6405 const bool IsArray = T->isArrayType();
6406 const bool IsFunction = T->isFunctionType();
6407
Richard Trieuc1888e02014-06-28 23:25:37 +00006408 // Address of function is used to silence the function warning.
6409 if (IsAddressOf && IsFunction) {
6410 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006411 }
6412
6413 // Found nothing.
6414 if (!IsAddressOf && !IsFunction && !IsArray)
6415 return;
6416
6417 // Pretty print the expression for the diagnostic.
6418 std::string Str;
6419 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00006420 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00006421
6422 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
6423 : diag::warn_impcast_pointer_to_bool;
6424 unsigned DiagType;
6425 if (IsAddressOf)
6426 DiagType = AddressOf;
6427 else if (IsFunction)
6428 DiagType = FunctionPointer;
6429 else if (IsArray)
6430 DiagType = ArrayPointer;
6431 else
6432 llvm_unreachable("Could not determine diagnostic.");
6433 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
6434 << Range << IsEqual;
6435
6436 if (!IsFunction)
6437 return;
6438
6439 // Suggest '&' to silence the function warning.
6440 Diag(E->getExprLoc(), diag::note_function_warning_silence)
6441 << FixItHint::CreateInsertion(E->getLocStart(), "&");
6442
6443 // Check to see if '()' fixit should be emitted.
6444 QualType ReturnType;
6445 UnresolvedSet<4> NonTemplateOverloads;
6446 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
6447 if (ReturnType.isNull())
6448 return;
6449
6450 if (IsCompare) {
6451 // There are two cases here. If there is null constant, the only suggest
6452 // for a pointer return type. If the null is 0, then suggest if the return
6453 // type is a pointer or an integer type.
6454 if (!ReturnType->isPointerType()) {
6455 if (NullKind == Expr::NPCK_ZeroExpression ||
6456 NullKind == Expr::NPCK_ZeroLiteral) {
6457 if (!ReturnType->isIntegerType())
6458 return;
6459 } else {
6460 return;
6461 }
6462 }
6463 } else { // !IsCompare
6464 // For function to bool, only suggest if the function pointer has bool
6465 // return type.
6466 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
6467 return;
6468 }
6469 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00006470 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00006471}
6472
6473
John McCallcc7e5bf2010-05-06 08:58:33 +00006474/// Diagnoses "dangerous" implicit conversions within the given
6475/// expression (which is a full expression). Implements -Wconversion
6476/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00006477///
6478/// \param CC the "context" location of the implicit conversion, i.e.
6479/// the most location of the syntactic entity requiring the implicit
6480/// conversion
6481void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006482 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00006483 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00006484 return;
6485
6486 // Don't diagnose for value- or type-dependent expressions.
6487 if (E->isTypeDependent() || E->isValueDependent())
6488 return;
6489
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006490 // Check for array bounds violations in cases where the check isn't triggered
6491 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
6492 // ArraySubscriptExpr is on the RHS of a variable initialization.
6493 CheckArrayAccess(E);
6494
John McCallacf0ee52010-10-08 02:01:28 +00006495 // This is not the right CC for (e.g.) a variable initialization.
6496 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006497}
6498
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006499/// Diagnose when expression is an integer constant expression and its evaluation
6500/// results in integer overflow
6501void Sema::CheckForIntOverflow (Expr *E) {
Richard Smithe9ff7702013-11-05 22:23:30 +00006502 if (isa<BinaryOperator>(E->IgnoreParens()))
6503 E->EvaluateForOverflow(Context);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006504}
6505
Richard Smithc406cb72013-01-17 01:17:56 +00006506namespace {
6507/// \brief Visitor for expressions which looks for unsequenced operations on the
6508/// same object.
6509class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00006510 typedef EvaluatedExprVisitor<SequenceChecker> Base;
6511
Richard Smithc406cb72013-01-17 01:17:56 +00006512 /// \brief A tree of sequenced regions within an expression. Two regions are
6513 /// unsequenced if one is an ancestor or a descendent of the other. When we
6514 /// finish processing an expression with sequencing, such as a comma
6515 /// expression, we fold its tree nodes into its parent, since they are
6516 /// unsequenced with respect to nodes we will visit later.
6517 class SequenceTree {
6518 struct Value {
6519 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
6520 unsigned Parent : 31;
6521 bool Merged : 1;
6522 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006523 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00006524
6525 public:
6526 /// \brief A region within an expression which may be sequenced with respect
6527 /// to some other region.
6528 class Seq {
6529 explicit Seq(unsigned N) : Index(N) {}
6530 unsigned Index;
6531 friend class SequenceTree;
6532 public:
6533 Seq() : Index(0) {}
6534 };
6535
6536 SequenceTree() { Values.push_back(Value(0)); }
6537 Seq root() const { return Seq(0); }
6538
6539 /// \brief Create a new sequence of operations, which is an unsequenced
6540 /// subset of \p Parent. This sequence of operations is sequenced with
6541 /// respect to other children of \p Parent.
6542 Seq allocate(Seq Parent) {
6543 Values.push_back(Value(Parent.Index));
6544 return Seq(Values.size() - 1);
6545 }
6546
6547 /// \brief Merge a sequence of operations into its parent.
6548 void merge(Seq S) {
6549 Values[S.Index].Merged = true;
6550 }
6551
6552 /// \brief Determine whether two operations are unsequenced. This operation
6553 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
6554 /// should have been merged into its parent as appropriate.
6555 bool isUnsequenced(Seq Cur, Seq Old) {
6556 unsigned C = representative(Cur.Index);
6557 unsigned Target = representative(Old.Index);
6558 while (C >= Target) {
6559 if (C == Target)
6560 return true;
6561 C = Values[C].Parent;
6562 }
6563 return false;
6564 }
6565
6566 private:
6567 /// \brief Pick a representative for a sequence.
6568 unsigned representative(unsigned K) {
6569 if (Values[K].Merged)
6570 // Perform path compression as we go.
6571 return Values[K].Parent = representative(Values[K].Parent);
6572 return K;
6573 }
6574 };
6575
6576 /// An object for which we can track unsequenced uses.
6577 typedef NamedDecl *Object;
6578
6579 /// Different flavors of object usage which we track. We only track the
6580 /// least-sequenced usage of each kind.
6581 enum UsageKind {
6582 /// A read of an object. Multiple unsequenced reads are OK.
6583 UK_Use,
6584 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00006585 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00006586 UK_ModAsValue,
6587 /// A modification of an object which is not sequenced before the value
6588 /// computation of the expression, such as n++.
6589 UK_ModAsSideEffect,
6590
6591 UK_Count = UK_ModAsSideEffect + 1
6592 };
6593
6594 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00006595 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00006596 Expr *Use;
6597 SequenceTree::Seq Seq;
6598 };
6599
6600 struct UsageInfo {
6601 UsageInfo() : Diagnosed(false) {}
6602 Usage Uses[UK_Count];
6603 /// Have we issued a diagnostic for this variable already?
6604 bool Diagnosed;
6605 };
6606 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
6607
6608 Sema &SemaRef;
6609 /// Sequenced regions within the expression.
6610 SequenceTree Tree;
6611 /// Declaration modifications and references which we have seen.
6612 UsageInfoMap UsageMap;
6613 /// The region we are currently within.
6614 SequenceTree::Seq Region;
6615 /// Filled in with declarations which were modified as a side-effect
6616 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006617 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00006618 /// Expressions to check later. We defer checking these to reduce
6619 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006620 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00006621
6622 /// RAII object wrapping the visitation of a sequenced subexpression of an
6623 /// expression. At the end of this process, the side-effects of the evaluation
6624 /// become sequenced with respect to the value computation of the result, so
6625 /// we downgrade any UK_ModAsSideEffect within the evaluation to
6626 /// UK_ModAsValue.
6627 struct SequencedSubexpression {
6628 SequencedSubexpression(SequenceChecker &Self)
6629 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
6630 Self.ModAsSideEffect = &ModAsSideEffect;
6631 }
6632 ~SequencedSubexpression() {
6633 for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) {
6634 UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first];
6635 U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second;
6636 Self.addUsage(U, ModAsSideEffect[I].first,
6637 ModAsSideEffect[I].second.Use, UK_ModAsValue);
6638 }
6639 Self.ModAsSideEffect = OldModAsSideEffect;
6640 }
6641
6642 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006643 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
6644 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00006645 };
6646
Richard Smith40238f02013-06-20 22:21:56 +00006647 /// RAII object wrapping the visitation of a subexpression which we might
6648 /// choose to evaluate as a constant. If any subexpression is evaluated and
6649 /// found to be non-constant, this allows us to suppress the evaluation of
6650 /// the outer expression.
6651 class EvaluationTracker {
6652 public:
6653 EvaluationTracker(SequenceChecker &Self)
6654 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
6655 Self.EvalTracker = this;
6656 }
6657 ~EvaluationTracker() {
6658 Self.EvalTracker = Prev;
6659 if (Prev)
6660 Prev->EvalOK &= EvalOK;
6661 }
6662
6663 bool evaluate(const Expr *E, bool &Result) {
6664 if (!EvalOK || E->isValueDependent())
6665 return false;
6666 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
6667 return EvalOK;
6668 }
6669
6670 private:
6671 SequenceChecker &Self;
6672 EvaluationTracker *Prev;
6673 bool EvalOK;
6674 } *EvalTracker;
6675
Richard Smithc406cb72013-01-17 01:17:56 +00006676 /// \brief Find the object which is produced by the specified expression,
6677 /// if any.
6678 Object getObject(Expr *E, bool Mod) const {
6679 E = E->IgnoreParenCasts();
6680 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6681 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
6682 return getObject(UO->getSubExpr(), Mod);
6683 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6684 if (BO->getOpcode() == BO_Comma)
6685 return getObject(BO->getRHS(), Mod);
6686 if (Mod && BO->isAssignmentOp())
6687 return getObject(BO->getLHS(), Mod);
6688 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
6689 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
6690 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
6691 return ME->getMemberDecl();
6692 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6693 // FIXME: If this is a reference, map through to its value.
6694 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00006695 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00006696 }
6697
6698 /// \brief Note that an object was modified or used by an expression.
6699 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
6700 Usage &U = UI.Uses[UK];
6701 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
6702 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
6703 ModAsSideEffect->push_back(std::make_pair(O, U));
6704 U.Use = Ref;
6705 U.Seq = Region;
6706 }
6707 }
6708 /// \brief Check whether a modification or use conflicts with a prior usage.
6709 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
6710 bool IsModMod) {
6711 if (UI.Diagnosed)
6712 return;
6713
6714 const Usage &U = UI.Uses[OtherKind];
6715 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
6716 return;
6717
6718 Expr *Mod = U.Use;
6719 Expr *ModOrUse = Ref;
6720 if (OtherKind == UK_Use)
6721 std::swap(Mod, ModOrUse);
6722
6723 SemaRef.Diag(Mod->getExprLoc(),
6724 IsModMod ? diag::warn_unsequenced_mod_mod
6725 : diag::warn_unsequenced_mod_use)
6726 << O << SourceRange(ModOrUse->getExprLoc());
6727 UI.Diagnosed = true;
6728 }
6729
6730 void notePreUse(Object O, Expr *Use) {
6731 UsageInfo &U = UsageMap[O];
6732 // Uses conflict with other modifications.
6733 checkUsage(O, U, Use, UK_ModAsValue, false);
6734 }
6735 void notePostUse(Object O, Expr *Use) {
6736 UsageInfo &U = UsageMap[O];
6737 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
6738 addUsage(U, O, Use, UK_Use);
6739 }
6740
6741 void notePreMod(Object O, Expr *Mod) {
6742 UsageInfo &U = UsageMap[O];
6743 // Modifications conflict with other modifications and with uses.
6744 checkUsage(O, U, Mod, UK_ModAsValue, true);
6745 checkUsage(O, U, Mod, UK_Use, false);
6746 }
6747 void notePostMod(Object O, Expr *Use, UsageKind UK) {
6748 UsageInfo &U = UsageMap[O];
6749 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
6750 addUsage(U, O, Use, UK);
6751 }
6752
6753public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006754 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00006755 : Base(S.Context), SemaRef(S), Region(Tree.root()),
6756 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00006757 Visit(E);
6758 }
6759
6760 void VisitStmt(Stmt *S) {
6761 // Skip all statements which aren't expressions for now.
6762 }
6763
6764 void VisitExpr(Expr *E) {
6765 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00006766 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00006767 }
6768
6769 void VisitCastExpr(CastExpr *E) {
6770 Object O = Object();
6771 if (E->getCastKind() == CK_LValueToRValue)
6772 O = getObject(E->getSubExpr(), false);
6773
6774 if (O)
6775 notePreUse(O, E);
6776 VisitExpr(E);
6777 if (O)
6778 notePostUse(O, E);
6779 }
6780
6781 void VisitBinComma(BinaryOperator *BO) {
6782 // C++11 [expr.comma]p1:
6783 // Every value computation and side effect associated with the left
6784 // expression is sequenced before every value computation and side
6785 // effect associated with the right expression.
6786 SequenceTree::Seq LHS = Tree.allocate(Region);
6787 SequenceTree::Seq RHS = Tree.allocate(Region);
6788 SequenceTree::Seq OldRegion = Region;
6789
6790 {
6791 SequencedSubexpression SeqLHS(*this);
6792 Region = LHS;
6793 Visit(BO->getLHS());
6794 }
6795
6796 Region = RHS;
6797 Visit(BO->getRHS());
6798
6799 Region = OldRegion;
6800
6801 // Forget that LHS and RHS are sequenced. They are both unsequenced
6802 // with respect to other stuff.
6803 Tree.merge(LHS);
6804 Tree.merge(RHS);
6805 }
6806
6807 void VisitBinAssign(BinaryOperator *BO) {
6808 // The modification is sequenced after the value computation of the LHS
6809 // and RHS, so check it before inspecting the operands and update the
6810 // map afterwards.
6811 Object O = getObject(BO->getLHS(), true);
6812 if (!O)
6813 return VisitExpr(BO);
6814
6815 notePreMod(O, BO);
6816
6817 // C++11 [expr.ass]p7:
6818 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
6819 // only once.
6820 //
6821 // Therefore, for a compound assignment operator, O is considered used
6822 // everywhere except within the evaluation of E1 itself.
6823 if (isa<CompoundAssignOperator>(BO))
6824 notePreUse(O, BO);
6825
6826 Visit(BO->getLHS());
6827
6828 if (isa<CompoundAssignOperator>(BO))
6829 notePostUse(O, BO);
6830
6831 Visit(BO->getRHS());
6832
Richard Smith83e37bee2013-06-26 23:16:51 +00006833 // C++11 [expr.ass]p1:
6834 // the assignment is sequenced [...] before the value computation of the
6835 // assignment expression.
6836 // C11 6.5.16/3 has no such rule.
6837 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6838 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00006839 }
6840 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
6841 VisitBinAssign(CAO);
6842 }
6843
6844 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
6845 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
6846 void VisitUnaryPreIncDec(UnaryOperator *UO) {
6847 Object O = getObject(UO->getSubExpr(), true);
6848 if (!O)
6849 return VisitExpr(UO);
6850
6851 notePreMod(O, UO);
6852 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00006853 // C++11 [expr.pre.incr]p1:
6854 // the expression ++x is equivalent to x+=1
6855 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6856 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00006857 }
6858
6859 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
6860 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
6861 void VisitUnaryPostIncDec(UnaryOperator *UO) {
6862 Object O = getObject(UO->getSubExpr(), true);
6863 if (!O)
6864 return VisitExpr(UO);
6865
6866 notePreMod(O, UO);
6867 Visit(UO->getSubExpr());
6868 notePostMod(O, UO, UK_ModAsSideEffect);
6869 }
6870
6871 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
6872 void VisitBinLOr(BinaryOperator *BO) {
6873 // The side-effects of the LHS of an '&&' are sequenced before the
6874 // value computation of the RHS, and hence before the value computation
6875 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
6876 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00006877 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00006878 {
6879 SequencedSubexpression Sequenced(*this);
6880 Visit(BO->getLHS());
6881 }
6882
6883 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006884 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00006885 if (!Result)
6886 Visit(BO->getRHS());
6887 } else {
6888 // Check for unsequenced operations in the RHS, treating it as an
6889 // entirely separate evaluation.
6890 //
6891 // FIXME: If there are operations in the RHS which are unsequenced
6892 // with respect to operations outside the RHS, and those operations
6893 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00006894 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00006895 }
Richard Smithc406cb72013-01-17 01:17:56 +00006896 }
6897 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00006898 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00006899 {
6900 SequencedSubexpression Sequenced(*this);
6901 Visit(BO->getLHS());
6902 }
6903
6904 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006905 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00006906 if (Result)
6907 Visit(BO->getRHS());
6908 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00006909 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00006910 }
Richard Smithc406cb72013-01-17 01:17:56 +00006911 }
6912
6913 // Only visit the condition, unless we can be sure which subexpression will
6914 // be chosen.
6915 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00006916 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00006917 {
6918 SequencedSubexpression Sequenced(*this);
6919 Visit(CO->getCond());
6920 }
Richard Smithc406cb72013-01-17 01:17:56 +00006921
6922 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006923 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00006924 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00006925 else {
Richard Smithd33f5202013-01-17 23:18:09 +00006926 WorkList.push_back(CO->getTrueExpr());
6927 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00006928 }
Richard Smithc406cb72013-01-17 01:17:56 +00006929 }
6930
Richard Smithe3dbfe02013-06-30 10:40:20 +00006931 void VisitCallExpr(CallExpr *CE) {
6932 // C++11 [intro.execution]p15:
6933 // When calling a function [...], every value computation and side effect
6934 // associated with any argument expression, or with the postfix expression
6935 // designating the called function, is sequenced before execution of every
6936 // expression or statement in the body of the function [and thus before
6937 // the value computation of its result].
6938 SequencedSubexpression Sequenced(*this);
6939 Base::VisitCallExpr(CE);
6940
6941 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
6942 }
6943
Richard Smithc406cb72013-01-17 01:17:56 +00006944 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00006945 // This is a call, so all subexpressions are sequenced before the result.
6946 SequencedSubexpression Sequenced(*this);
6947
Richard Smithc406cb72013-01-17 01:17:56 +00006948 if (!CCE->isListInitialization())
6949 return VisitExpr(CCE);
6950
6951 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006952 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00006953 SequenceTree::Seq Parent = Region;
6954 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
6955 E = CCE->arg_end();
6956 I != E; ++I) {
6957 Region = Tree.allocate(Parent);
6958 Elts.push_back(Region);
6959 Visit(*I);
6960 }
6961
6962 // Forget that the initializers are sequenced.
6963 Region = Parent;
6964 for (unsigned I = 0; I < Elts.size(); ++I)
6965 Tree.merge(Elts[I]);
6966 }
6967
6968 void VisitInitListExpr(InitListExpr *ILE) {
6969 if (!SemaRef.getLangOpts().CPlusPlus11)
6970 return VisitExpr(ILE);
6971
6972 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006973 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00006974 SequenceTree::Seq Parent = Region;
6975 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
6976 Expr *E = ILE->getInit(I);
6977 if (!E) continue;
6978 Region = Tree.allocate(Parent);
6979 Elts.push_back(Region);
6980 Visit(E);
6981 }
6982
6983 // Forget that the initializers are sequenced.
6984 Region = Parent;
6985 for (unsigned I = 0; I < Elts.size(); ++I)
6986 Tree.merge(Elts[I]);
6987 }
6988};
6989}
6990
6991void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006992 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00006993 WorkList.push_back(E);
6994 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00006995 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00006996 SequenceChecker(*this, Item, WorkList);
6997 }
Richard Smithc406cb72013-01-17 01:17:56 +00006998}
6999
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007000void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
7001 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00007002 CheckImplicitConversions(E, CheckLoc);
7003 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007004 if (!IsConstexpr && !E->isValueDependent())
7005 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00007006}
7007
John McCall1f425642010-11-11 03:21:53 +00007008void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
7009 FieldDecl *BitField,
7010 Expr *Init) {
7011 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
7012}
7013
Mike Stump0c2ec772010-01-21 03:59:47 +00007014/// CheckParmsForFunctionDef - Check that the parameters of the given
7015/// function are appropriate for the definition of a function. This
7016/// takes care of any checks that cannot be performed on the
7017/// declaration itself, e.g., that the types of each of the function
7018/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00007019bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
7020 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00007021 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00007022 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00007023 for (; P != PEnd; ++P) {
7024 ParmVarDecl *Param = *P;
7025
Mike Stump0c2ec772010-01-21 03:59:47 +00007026 // C99 6.7.5.3p4: the parameters in a parameter type list in a
7027 // function declarator that is part of a function definition of
7028 // that function shall not have incomplete type.
7029 //
7030 // This is also C++ [dcl.fct]p6.
7031 if (!Param->isInvalidDecl() &&
7032 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00007033 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00007034 Param->setInvalidDecl();
7035 HasInvalidParm = true;
7036 }
7037
7038 // C99 6.9.1p5: If the declarator includes a parameter type list, the
7039 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00007040 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00007041 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00007042 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00007043 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00007044 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00007045
7046 // C99 6.7.5.3p12:
7047 // If the function declarator is not part of a definition of that
7048 // function, parameters may have incomplete type and may use the [*]
7049 // notation in their sequences of declarator specifiers to specify
7050 // variable length array types.
7051 QualType PType = Param->getOriginalType();
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007052 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigdeb55d52010-02-01 05:02:49 +00007053 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitb3318502013-03-01 21:41:22 +00007054 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigdeb55d52010-02-01 05:02:49 +00007055 // information is added for it.
7056 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007057 break;
Sam Weinigdeb55d52010-02-01 05:02:49 +00007058 }
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007059 PType= AT->getElementType();
Sam Weinigdeb55d52010-02-01 05:02:49 +00007060 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00007061
7062 // MSVC destroys objects passed by value in the callee. Therefore a
7063 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00007064 // object's destructor. However, we don't perform any direct access check
7065 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00007066 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
7067 .getCXXABI()
7068 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00007069 if (!Param->isInvalidDecl()) {
7070 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
7071 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
7072 if (!ClassDecl->isInvalidDecl() &&
7073 !ClassDecl->hasIrrelevantDestructor() &&
7074 !ClassDecl->isDependentContext()) {
7075 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
7076 MarkFunctionReferenced(Param->getLocation(), Destructor);
7077 DiagnoseUseOfDecl(Destructor, Param->getLocation());
7078 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00007079 }
7080 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00007081 }
Mike Stump0c2ec772010-01-21 03:59:47 +00007082 }
7083
7084 return HasInvalidParm;
7085}
John McCall2b5c1b22010-08-12 21:44:57 +00007086
7087/// CheckCastAlign - Implements -Wcast-align, which warns when a
7088/// pointer cast increases the alignment requirements.
7089void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
7090 // This is actually a lot of work to potentially be doing on every
7091 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007092 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00007093 return;
7094
7095 // Ignore dependent types.
7096 if (T->isDependentType() || Op->getType()->isDependentType())
7097 return;
7098
7099 // Require that the destination be a pointer type.
7100 const PointerType *DestPtr = T->getAs<PointerType>();
7101 if (!DestPtr) return;
7102
7103 // If the destination has alignment 1, we're done.
7104 QualType DestPointee = DestPtr->getPointeeType();
7105 if (DestPointee->isIncompleteType()) return;
7106 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
7107 if (DestAlign.isOne()) return;
7108
7109 // Require that the source be a pointer type.
7110 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
7111 if (!SrcPtr) return;
7112 QualType SrcPointee = SrcPtr->getPointeeType();
7113
7114 // Whitelist casts from cv void*. We already implicitly
7115 // whitelisted casts to cv void*, since they have alignment 1.
7116 // Also whitelist casts involving incomplete types, which implicitly
7117 // includes 'void'.
7118 if (SrcPointee->isIncompleteType()) return;
7119
7120 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
7121 if (SrcAlign >= DestAlign) return;
7122
7123 Diag(TRange.getBegin(), diag::warn_cast_align)
7124 << Op->getType() << T
7125 << static_cast<unsigned>(SrcAlign.getQuantity())
7126 << static_cast<unsigned>(DestAlign.getQuantity())
7127 << TRange << Op->getSourceRange();
7128}
7129
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007130static const Type* getElementType(const Expr *BaseExpr) {
7131 const Type* EltType = BaseExpr->getType().getTypePtr();
7132 if (EltType->isAnyPointerType())
7133 return EltType->getPointeeType().getTypePtr();
7134 else if (EltType->isArrayType())
7135 return EltType->getBaseElementTypeUnsafe();
7136 return EltType;
7137}
7138
Chandler Carruth28389f02011-08-05 09:10:50 +00007139/// \brief Check whether this array fits the idiom of a size-one tail padded
7140/// array member of a struct.
7141///
7142/// We avoid emitting out-of-bounds access warnings for such arrays as they are
7143/// commonly used to emulate flexible arrays in C89 code.
7144static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
7145 const NamedDecl *ND) {
7146 if (Size != 1 || !ND) return false;
7147
7148 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
7149 if (!FD) return false;
7150
7151 // Don't consider sizes resulting from macro expansions or template argument
7152 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00007153
7154 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007155 while (TInfo) {
7156 TypeLoc TL = TInfo->getTypeLoc();
7157 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00007158 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
7159 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007160 TInfo = TDL->getTypeSourceInfo();
7161 continue;
7162 }
David Blaikie6adc78e2013-02-18 22:06:02 +00007163 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
7164 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00007165 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
7166 return false;
7167 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007168 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00007169 }
Chandler Carruth28389f02011-08-05 09:10:50 +00007170
7171 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00007172 if (!RD) return false;
7173 if (RD->isUnion()) return false;
7174 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
7175 if (!CRD->isStandardLayout()) return false;
7176 }
Chandler Carruth28389f02011-08-05 09:10:50 +00007177
Benjamin Kramer8c543672011-08-06 03:04:42 +00007178 // See if this is the last field decl in the record.
7179 const Decl *D = FD;
7180 while ((D = D->getNextDeclInContext()))
7181 if (isa<FieldDecl>(D))
7182 return false;
7183 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00007184}
7185
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007186void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007187 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00007188 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007189 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007190 if (IndexExpr->isValueDependent())
7191 return;
7192
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00007193 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007194 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007195 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007196 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007197 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00007198 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00007199
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007200 llvm::APSInt index;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007201 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremenek64699be2011-02-16 01:57:07 +00007202 return;
Richard Smith13f67182011-12-16 19:31:14 +00007203 if (IndexNegated)
7204 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00007205
Craig Topperc3ec1492014-05-26 06:22:03 +00007206 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00007207 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7208 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00007209 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00007210 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00007211
Ted Kremeneke4b316c2011-02-23 23:06:04 +00007212 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007213 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00007214 if (!size.isStrictlyPositive())
7215 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007216
7217 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00007218 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007219 // Make sure we're comparing apples to apples when comparing index to size
7220 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
7221 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00007222 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00007223 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007224 if (ptrarith_typesize != array_typesize) {
7225 // There's a cast to a different size type involved
7226 uint64_t ratio = array_typesize / ptrarith_typesize;
7227 // TODO: Be smarter about handling cases where array_typesize is not a
7228 // multiple of ptrarith_typesize
7229 if (ptrarith_typesize * ratio == array_typesize)
7230 size *= llvm::APInt(size.getBitWidth(), ratio);
7231 }
7232 }
7233
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007234 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007235 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007236 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007237 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007238
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007239 // For array subscripting the index must be less than size, but for pointer
7240 // arithmetic also allow the index (offset) to be equal to size since
7241 // computing the next address after the end of the array is legal and
7242 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007243 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00007244 return;
7245
7246 // Also don't warn for arrays of size 1 which are members of some
7247 // structure. These are often used to approximate flexible arrays in C89
7248 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007249 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00007250 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007251
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007252 // Suppress the warning if the subscript expression (as identified by the
7253 // ']' location) and the index expression are both from macro expansions
7254 // within a system header.
7255 if (ASE) {
7256 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
7257 ASE->getRBracketLoc());
7258 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
7259 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
7260 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00007261 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007262 return;
7263 }
7264 }
7265
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007266 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007267 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007268 DiagID = diag::warn_array_index_exceeds_bounds;
7269
7270 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7271 PDiag(DiagID) << index.toString(10, true)
7272 << size.toString(10, true)
7273 << (unsigned)size.getLimitedValue(~0U)
7274 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007275 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007276 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007277 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007278 DiagID = diag::warn_ptr_arith_precedes_bounds;
7279 if (index.isNegative()) index = -index;
7280 }
7281
7282 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7283 PDiag(DiagID) << index.toString(10, true)
7284 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00007285 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00007286
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00007287 if (!ND) {
7288 // Try harder to find a NamedDecl to point at in the note.
7289 while (const ArraySubscriptExpr *ASE =
7290 dyn_cast<ArraySubscriptExpr>(BaseExpr))
7291 BaseExpr = ASE->getBase()->IgnoreParenCasts();
7292 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7293 ND = dyn_cast<NamedDecl>(DRE->getDecl());
7294 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
7295 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
7296 }
7297
Chandler Carruth1af88f12011-02-17 21:10:52 +00007298 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007299 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
7300 PDiag(diag::note_array_index_out_of_bounds)
7301 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00007302}
7303
Ted Kremenekdf26df72011-03-01 18:41:00 +00007304void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007305 int AllowOnePastEnd = 0;
7306 while (expr) {
7307 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00007308 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007309 case Stmt::ArraySubscriptExprClass: {
7310 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007311 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007312 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00007313 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007314 }
7315 case Stmt::UnaryOperatorClass: {
7316 // Only unwrap the * and & unary operators
7317 const UnaryOperator *UO = cast<UnaryOperator>(expr);
7318 expr = UO->getSubExpr();
7319 switch (UO->getOpcode()) {
7320 case UO_AddrOf:
7321 AllowOnePastEnd++;
7322 break;
7323 case UO_Deref:
7324 AllowOnePastEnd--;
7325 break;
7326 default:
7327 return;
7328 }
7329 break;
7330 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007331 case Stmt::ConditionalOperatorClass: {
7332 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
7333 if (const Expr *lhs = cond->getLHS())
7334 CheckArrayAccess(lhs);
7335 if (const Expr *rhs = cond->getRHS())
7336 CheckArrayAccess(rhs);
7337 return;
7338 }
7339 default:
7340 return;
7341 }
Peter Collingbourne91147592011-04-15 00:35:48 +00007342 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007343}
John McCall31168b02011-06-15 23:02:42 +00007344
7345//===--- CHECK: Objective-C retain cycles ----------------------------------//
7346
7347namespace {
7348 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00007349 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00007350 VarDecl *Variable;
7351 SourceRange Range;
7352 SourceLocation Loc;
7353 bool Indirect;
7354
7355 void setLocsFrom(Expr *e) {
7356 Loc = e->getExprLoc();
7357 Range = e->getSourceRange();
7358 }
7359 };
7360}
7361
7362/// Consider whether capturing the given variable can possibly lead to
7363/// a retain cycle.
7364static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00007365 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00007366 // lifetime. In MRR, it's captured strongly if the variable is
7367 // __block and has an appropriate type.
7368 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7369 return false;
7370
7371 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007372 if (ref)
7373 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00007374 return true;
7375}
7376
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007377static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00007378 while (true) {
7379 e = e->IgnoreParens();
7380 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
7381 switch (cast->getCastKind()) {
7382 case CK_BitCast:
7383 case CK_LValueBitCast:
7384 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00007385 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00007386 e = cast->getSubExpr();
7387 continue;
7388
John McCall31168b02011-06-15 23:02:42 +00007389 default:
7390 return false;
7391 }
7392 }
7393
7394 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
7395 ObjCIvarDecl *ivar = ref->getDecl();
7396 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7397 return false;
7398
7399 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007400 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00007401 return false;
7402
7403 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
7404 owner.Indirect = true;
7405 return true;
7406 }
7407
7408 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
7409 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
7410 if (!var) return false;
7411 return considerVariable(var, ref, owner);
7412 }
7413
John McCall31168b02011-06-15 23:02:42 +00007414 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
7415 if (member->isArrow()) return false;
7416
7417 // Don't count this as an indirect ownership.
7418 e = member->getBase();
7419 continue;
7420 }
7421
John McCallfe96e0b2011-11-06 09:01:30 +00007422 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
7423 // Only pay attention to pseudo-objects on property references.
7424 ObjCPropertyRefExpr *pre
7425 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
7426 ->IgnoreParens());
7427 if (!pre) return false;
7428 if (pre->isImplicitProperty()) return false;
7429 ObjCPropertyDecl *property = pre->getExplicitProperty();
7430 if (!property->isRetaining() &&
7431 !(property->getPropertyIvarDecl() &&
7432 property->getPropertyIvarDecl()->getType()
7433 .getObjCLifetime() == Qualifiers::OCL_Strong))
7434 return false;
7435
7436 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007437 if (pre->isSuperReceiver()) {
7438 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
7439 if (!owner.Variable)
7440 return false;
7441 owner.Loc = pre->getLocation();
7442 owner.Range = pre->getSourceRange();
7443 return true;
7444 }
John McCallfe96e0b2011-11-06 09:01:30 +00007445 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
7446 ->getSourceExpr());
7447 continue;
7448 }
7449
John McCall31168b02011-06-15 23:02:42 +00007450 // Array ivars?
7451
7452 return false;
7453 }
7454}
7455
7456namespace {
7457 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
7458 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
7459 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00007460 Context(Context), Variable(variable), Capturer(nullptr),
7461 VarWillBeReased(false) {}
7462 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +00007463 VarDecl *Variable;
7464 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00007465 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +00007466
7467 void VisitDeclRefExpr(DeclRefExpr *ref) {
7468 if (ref->getDecl() == Variable && !Capturer)
7469 Capturer = ref;
7470 }
7471
John McCall31168b02011-06-15 23:02:42 +00007472 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
7473 if (Capturer) return;
7474 Visit(ref->getBase());
7475 if (Capturer && ref->isFreeIvar())
7476 Capturer = ref;
7477 }
7478
7479 void VisitBlockExpr(BlockExpr *block) {
7480 // Look inside nested blocks
7481 if (block->getBlockDecl()->capturesVariable(Variable))
7482 Visit(block->getBlockDecl()->getBody());
7483 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00007484
7485 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
7486 if (Capturer) return;
7487 if (OVE->getSourceExpr())
7488 Visit(OVE->getSourceExpr());
7489 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00007490 void VisitBinaryOperator(BinaryOperator *BinOp) {
7491 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
7492 return;
7493 Expr *LHS = BinOp->getLHS();
7494 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
7495 if (DRE->getDecl() != Variable)
7496 return;
7497 if (Expr *RHS = BinOp->getRHS()) {
7498 RHS = RHS->IgnoreParenCasts();
7499 llvm::APSInt Value;
7500 VarWillBeReased =
7501 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
7502 }
7503 }
7504 }
John McCall31168b02011-06-15 23:02:42 +00007505 };
7506}
7507
7508/// Check whether the given argument is a block which captures a
7509/// variable.
7510static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
7511 assert(owner.Variable && owner.Loc.isValid());
7512
7513 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00007514
7515 // Look through [^{...} copy] and Block_copy(^{...}).
7516 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
7517 Selector Cmd = ME->getSelector();
7518 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
7519 e = ME->getInstanceReceiver();
7520 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +00007521 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +00007522 e = e->IgnoreParenCasts();
7523 }
7524 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
7525 if (CE->getNumArgs() == 1) {
7526 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00007527 if (Fn) {
7528 const IdentifierInfo *FnI = Fn->getIdentifier();
7529 if (FnI && FnI->isStr("_Block_copy")) {
7530 e = CE->getArg(0)->IgnoreParenCasts();
7531 }
7532 }
Jordan Rose67e887c2012-09-17 17:54:30 +00007533 }
7534 }
7535
John McCall31168b02011-06-15 23:02:42 +00007536 BlockExpr *block = dyn_cast<BlockExpr>(e);
7537 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +00007538 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00007539
7540 FindCaptureVisitor visitor(S.Context, owner.Variable);
7541 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00007542 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +00007543}
7544
7545static void diagnoseRetainCycle(Sema &S, Expr *capturer,
7546 RetainCycleOwner &owner) {
7547 assert(capturer);
7548 assert(owner.Variable && owner.Loc.isValid());
7549
7550 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
7551 << owner.Variable << capturer->getSourceRange();
7552 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
7553 << owner.Indirect << owner.Range;
7554}
7555
7556/// Check for a keyword selector that starts with the word 'add' or
7557/// 'set'.
7558static bool isSetterLikeSelector(Selector sel) {
7559 if (sel.isUnarySelector()) return false;
7560
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007561 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00007562 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00007563 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00007564 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00007565 else if (str.startswith("add")) {
7566 // Specially whitelist 'addOperationWithBlock:'.
7567 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
7568 return false;
7569 str = str.substr(3);
7570 }
John McCall31168b02011-06-15 23:02:42 +00007571 else
7572 return false;
7573
7574 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00007575 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00007576}
7577
7578/// Check a message send to see if it's likely to cause a retain cycle.
7579void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
7580 // Only check instance methods whose selector looks like a setter.
7581 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
7582 return;
7583
7584 // Try to find a variable that the receiver is strongly owned by.
7585 RetainCycleOwner owner;
7586 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007587 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00007588 return;
7589 } else {
7590 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
7591 owner.Variable = getCurMethodDecl()->getSelfDecl();
7592 owner.Loc = msg->getSuperLoc();
7593 owner.Range = msg->getSuperLoc();
7594 }
7595
7596 // Check whether the receiver is captured by any of the arguments.
7597 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
7598 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
7599 return diagnoseRetainCycle(*this, capturer, owner);
7600}
7601
7602/// Check a property assign to see if it's likely to cause a retain cycle.
7603void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
7604 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007605 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00007606 return;
7607
7608 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
7609 diagnoseRetainCycle(*this, capturer, owner);
7610}
7611
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007612void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
7613 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +00007614 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007615 return;
7616
7617 // Because we don't have an expression for the variable, we have to set the
7618 // location explicitly here.
7619 Owner.Loc = Var->getLocation();
7620 Owner.Range = Var->getSourceRange();
7621
7622 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
7623 diagnoseRetainCycle(*this, Capturer, Owner);
7624}
7625
Ted Kremenek9304da92012-12-21 08:04:28 +00007626static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
7627 Expr *RHS, bool isProperty) {
7628 // Check if RHS is an Objective-C object literal, which also can get
7629 // immediately zapped in a weak reference. Note that we explicitly
7630 // allow ObjCStringLiterals, since those are designed to never really die.
7631 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00007632
Ted Kremenek64873352012-12-21 22:46:35 +00007633 // This enum needs to match with the 'select' in
7634 // warn_objc_arc_literal_assign (off-by-1).
7635 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
7636 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
7637 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00007638
7639 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00007640 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00007641 << (isProperty ? 0 : 1)
7642 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00007643
7644 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00007645}
7646
Ted Kremenekc1f014a2012-12-21 19:45:30 +00007647static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
7648 Qualifiers::ObjCLifetime LT,
7649 Expr *RHS, bool isProperty) {
7650 // Strip off any implicit cast added to get to the one ARC-specific.
7651 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
7652 if (cast->getCastKind() == CK_ARCConsumeObject) {
7653 S.Diag(Loc, diag::warn_arc_retained_assign)
7654 << (LT == Qualifiers::OCL_ExplicitNone)
7655 << (isProperty ? 0 : 1)
7656 << RHS->getSourceRange();
7657 return true;
7658 }
7659 RHS = cast->getSubExpr();
7660 }
7661
7662 if (LT == Qualifiers::OCL_Weak &&
7663 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
7664 return true;
7665
7666 return false;
7667}
7668
Ted Kremenekb36234d2012-12-21 08:04:20 +00007669bool Sema::checkUnsafeAssigns(SourceLocation Loc,
7670 QualType LHS, Expr *RHS) {
7671 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
7672
7673 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
7674 return false;
7675
7676 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
7677 return true;
7678
7679 return false;
7680}
7681
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007682void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
7683 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007684 QualType LHSType;
7685 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00007686 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007687 ObjCPropertyRefExpr *PRE
7688 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
7689 if (PRE && !PRE->isImplicitProperty()) {
7690 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
7691 if (PD)
7692 LHSType = PD->getType();
7693 }
7694
7695 if (LHSType.isNull())
7696 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00007697
7698 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
7699
7700 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007701 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +00007702 getCurFunction()->markSafeWeakUse(LHS);
7703 }
7704
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007705 if (checkUnsafeAssigns(Loc, LHSType, RHS))
7706 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00007707
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007708 // FIXME. Check for other life times.
7709 if (LT != Qualifiers::OCL_None)
7710 return;
7711
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007712 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007713 if (PRE->isImplicitProperty())
7714 return;
7715 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
7716 if (!PD)
7717 return;
7718
Bill Wendling44426052012-12-20 19:22:21 +00007719 unsigned Attributes = PD->getPropertyAttributes();
7720 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007721 // when 'assign' attribute was not explicitly specified
7722 // by user, ignore it and rely on property type itself
7723 // for lifetime info.
7724 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
7725 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
7726 LHSType->isObjCRetainableType())
7727 return;
7728
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007729 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00007730 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007731 Diag(Loc, diag::warn_arc_retained_property_assign)
7732 << RHS->getSourceRange();
7733 return;
7734 }
7735 RHS = cast->getSubExpr();
7736 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007737 }
Bill Wendling44426052012-12-20 19:22:21 +00007738 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00007739 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
7740 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00007741 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007742 }
7743}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00007744
7745//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
7746
7747namespace {
7748bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
7749 SourceLocation StmtLoc,
7750 const NullStmt *Body) {
7751 // Do not warn if the body is a macro that expands to nothing, e.g:
7752 //
7753 // #define CALL(x)
7754 // if (condition)
7755 // CALL(0);
7756 //
7757 if (Body->hasLeadingEmptyMacro())
7758 return false;
7759
7760 // Get line numbers of statement and body.
7761 bool StmtLineInvalid;
7762 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
7763 &StmtLineInvalid);
7764 if (StmtLineInvalid)
7765 return false;
7766
7767 bool BodyLineInvalid;
7768 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
7769 &BodyLineInvalid);
7770 if (BodyLineInvalid)
7771 return false;
7772
7773 // Warn if null statement and body are on the same line.
7774 if (StmtLine != BodyLine)
7775 return false;
7776
7777 return true;
7778}
7779} // Unnamed namespace
7780
7781void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
7782 const Stmt *Body,
7783 unsigned DiagID) {
7784 // Since this is a syntactic check, don't emit diagnostic for template
7785 // instantiations, this just adds noise.
7786 if (CurrentInstantiationScope)
7787 return;
7788
7789 // The body should be a null statement.
7790 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
7791 if (!NBody)
7792 return;
7793
7794 // Do the usual checks.
7795 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
7796 return;
7797
7798 Diag(NBody->getSemiLoc(), DiagID);
7799 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
7800}
7801
7802void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
7803 const Stmt *PossibleBody) {
7804 assert(!CurrentInstantiationScope); // Ensured by caller
7805
7806 SourceLocation StmtLoc;
7807 const Stmt *Body;
7808 unsigned DiagID;
7809 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
7810 StmtLoc = FS->getRParenLoc();
7811 Body = FS->getBody();
7812 DiagID = diag::warn_empty_for_body;
7813 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
7814 StmtLoc = WS->getCond()->getSourceRange().getEnd();
7815 Body = WS->getBody();
7816 DiagID = diag::warn_empty_while_body;
7817 } else
7818 return; // Neither `for' nor `while'.
7819
7820 // The body should be a null statement.
7821 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
7822 if (!NBody)
7823 return;
7824
7825 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007826 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00007827 return;
7828
7829 // Do the usual checks.
7830 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
7831 return;
7832
7833 // `for(...);' and `while(...);' are popular idioms, so in order to keep
7834 // noise level low, emit diagnostics only if for/while is followed by a
7835 // CompoundStmt, e.g.:
7836 // for (int i = 0; i < n; i++);
7837 // {
7838 // a(i);
7839 // }
7840 // or if for/while is followed by a statement with more indentation
7841 // than for/while itself:
7842 // for (int i = 0; i < n; i++);
7843 // a(i);
7844 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
7845 if (!ProbableTypo) {
7846 bool BodyColInvalid;
7847 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
7848 PossibleBody->getLocStart(),
7849 &BodyColInvalid);
7850 if (BodyColInvalid)
7851 return;
7852
7853 bool StmtColInvalid;
7854 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
7855 S->getLocStart(),
7856 &StmtColInvalid);
7857 if (StmtColInvalid)
7858 return;
7859
7860 if (BodyCol > StmtCol)
7861 ProbableTypo = true;
7862 }
7863
7864 if (ProbableTypo) {
7865 Diag(NBody->getSemiLoc(), DiagID);
7866 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
7867 }
7868}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007869
7870//===--- Layout compatibility ----------------------------------------------//
7871
7872namespace {
7873
7874bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
7875
7876/// \brief Check if two enumeration types are layout-compatible.
7877bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
7878 // C++11 [dcl.enum] p8:
7879 // Two enumeration types are layout-compatible if they have the same
7880 // underlying type.
7881 return ED1->isComplete() && ED2->isComplete() &&
7882 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
7883}
7884
7885/// \brief Check if two fields are layout-compatible.
7886bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
7887 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
7888 return false;
7889
7890 if (Field1->isBitField() != Field2->isBitField())
7891 return false;
7892
7893 if (Field1->isBitField()) {
7894 // Make sure that the bit-fields are the same length.
7895 unsigned Bits1 = Field1->getBitWidthValue(C);
7896 unsigned Bits2 = Field2->getBitWidthValue(C);
7897
7898 if (Bits1 != Bits2)
7899 return false;
7900 }
7901
7902 return true;
7903}
7904
7905/// \brief Check if two standard-layout structs are layout-compatible.
7906/// (C++11 [class.mem] p17)
7907bool isLayoutCompatibleStruct(ASTContext &C,
7908 RecordDecl *RD1,
7909 RecordDecl *RD2) {
7910 // If both records are C++ classes, check that base classes match.
7911 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
7912 // If one of records is a CXXRecordDecl we are in C++ mode,
7913 // thus the other one is a CXXRecordDecl, too.
7914 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
7915 // Check number of base classes.
7916 if (D1CXX->getNumBases() != D2CXX->getNumBases())
7917 return false;
7918
7919 // Check the base classes.
7920 for (CXXRecordDecl::base_class_const_iterator
7921 Base1 = D1CXX->bases_begin(),
7922 BaseEnd1 = D1CXX->bases_end(),
7923 Base2 = D2CXX->bases_begin();
7924 Base1 != BaseEnd1;
7925 ++Base1, ++Base2) {
7926 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
7927 return false;
7928 }
7929 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
7930 // If only RD2 is a C++ class, it should have zero base classes.
7931 if (D2CXX->getNumBases() > 0)
7932 return false;
7933 }
7934
7935 // Check the fields.
7936 RecordDecl::field_iterator Field2 = RD2->field_begin(),
7937 Field2End = RD2->field_end(),
7938 Field1 = RD1->field_begin(),
7939 Field1End = RD1->field_end();
7940 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
7941 if (!isLayoutCompatible(C, *Field1, *Field2))
7942 return false;
7943 }
7944 if (Field1 != Field1End || Field2 != Field2End)
7945 return false;
7946
7947 return true;
7948}
7949
7950/// \brief Check if two standard-layout unions are layout-compatible.
7951/// (C++11 [class.mem] p18)
7952bool isLayoutCompatibleUnion(ASTContext &C,
7953 RecordDecl *RD1,
7954 RecordDecl *RD2) {
7955 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007956 for (auto *Field2 : RD2->fields())
7957 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007958
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007959 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007960 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
7961 I = UnmatchedFields.begin(),
7962 E = UnmatchedFields.end();
7963
7964 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007965 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007966 bool Result = UnmatchedFields.erase(*I);
7967 (void) Result;
7968 assert(Result);
7969 break;
7970 }
7971 }
7972 if (I == E)
7973 return false;
7974 }
7975
7976 return UnmatchedFields.empty();
7977}
7978
7979bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
7980 if (RD1->isUnion() != RD2->isUnion())
7981 return false;
7982
7983 if (RD1->isUnion())
7984 return isLayoutCompatibleUnion(C, RD1, RD2);
7985 else
7986 return isLayoutCompatibleStruct(C, RD1, RD2);
7987}
7988
7989/// \brief Check if two types are layout-compatible in C++11 sense.
7990bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
7991 if (T1.isNull() || T2.isNull())
7992 return false;
7993
7994 // C++11 [basic.types] p11:
7995 // If two types T1 and T2 are the same type, then T1 and T2 are
7996 // layout-compatible types.
7997 if (C.hasSameType(T1, T2))
7998 return true;
7999
8000 T1 = T1.getCanonicalType().getUnqualifiedType();
8001 T2 = T2.getCanonicalType().getUnqualifiedType();
8002
8003 const Type::TypeClass TC1 = T1->getTypeClass();
8004 const Type::TypeClass TC2 = T2->getTypeClass();
8005
8006 if (TC1 != TC2)
8007 return false;
8008
8009 if (TC1 == Type::Enum) {
8010 return isLayoutCompatible(C,
8011 cast<EnumType>(T1)->getDecl(),
8012 cast<EnumType>(T2)->getDecl());
8013 } else if (TC1 == Type::Record) {
8014 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
8015 return false;
8016
8017 return isLayoutCompatible(C,
8018 cast<RecordType>(T1)->getDecl(),
8019 cast<RecordType>(T2)->getDecl());
8020 }
8021
8022 return false;
8023}
8024}
8025
8026//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
8027
8028namespace {
8029/// \brief Given a type tag expression find the type tag itself.
8030///
8031/// \param TypeExpr Type tag expression, as it appears in user's code.
8032///
8033/// \param VD Declaration of an identifier that appears in a type tag.
8034///
8035/// \param MagicValue Type tag magic value.
8036bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
8037 const ValueDecl **VD, uint64_t *MagicValue) {
8038 while(true) {
8039 if (!TypeExpr)
8040 return false;
8041
8042 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
8043
8044 switch (TypeExpr->getStmtClass()) {
8045 case Stmt::UnaryOperatorClass: {
8046 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
8047 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
8048 TypeExpr = UO->getSubExpr();
8049 continue;
8050 }
8051 return false;
8052 }
8053
8054 case Stmt::DeclRefExprClass: {
8055 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
8056 *VD = DRE->getDecl();
8057 return true;
8058 }
8059
8060 case Stmt::IntegerLiteralClass: {
8061 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
8062 llvm::APInt MagicValueAPInt = IL->getValue();
8063 if (MagicValueAPInt.getActiveBits() <= 64) {
8064 *MagicValue = MagicValueAPInt.getZExtValue();
8065 return true;
8066 } else
8067 return false;
8068 }
8069
8070 case Stmt::BinaryConditionalOperatorClass:
8071 case Stmt::ConditionalOperatorClass: {
8072 const AbstractConditionalOperator *ACO =
8073 cast<AbstractConditionalOperator>(TypeExpr);
8074 bool Result;
8075 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
8076 if (Result)
8077 TypeExpr = ACO->getTrueExpr();
8078 else
8079 TypeExpr = ACO->getFalseExpr();
8080 continue;
8081 }
8082 return false;
8083 }
8084
8085 case Stmt::BinaryOperatorClass: {
8086 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
8087 if (BO->getOpcode() == BO_Comma) {
8088 TypeExpr = BO->getRHS();
8089 continue;
8090 }
8091 return false;
8092 }
8093
8094 default:
8095 return false;
8096 }
8097 }
8098}
8099
8100/// \brief Retrieve the C type corresponding to type tag TypeExpr.
8101///
8102/// \param TypeExpr Expression that specifies a type tag.
8103///
8104/// \param MagicValues Registered magic values.
8105///
8106/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
8107/// kind.
8108///
8109/// \param TypeInfo Information about the corresponding C type.
8110///
8111/// \returns true if the corresponding C type was found.
8112bool GetMatchingCType(
8113 const IdentifierInfo *ArgumentKind,
8114 const Expr *TypeExpr, const ASTContext &Ctx,
8115 const llvm::DenseMap<Sema::TypeTagMagicValue,
8116 Sema::TypeTagData> *MagicValues,
8117 bool &FoundWrongKind,
8118 Sema::TypeTagData &TypeInfo) {
8119 FoundWrongKind = false;
8120
8121 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +00008122 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008123
8124 uint64_t MagicValue;
8125
8126 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
8127 return false;
8128
8129 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +00008130 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008131 if (I->getArgumentKind() != ArgumentKind) {
8132 FoundWrongKind = true;
8133 return false;
8134 }
8135 TypeInfo.Type = I->getMatchingCType();
8136 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
8137 TypeInfo.MustBeNull = I->getMustBeNull();
8138 return true;
8139 }
8140 return false;
8141 }
8142
8143 if (!MagicValues)
8144 return false;
8145
8146 llvm::DenseMap<Sema::TypeTagMagicValue,
8147 Sema::TypeTagData>::const_iterator I =
8148 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
8149 if (I == MagicValues->end())
8150 return false;
8151
8152 TypeInfo = I->second;
8153 return true;
8154}
8155} // unnamed namespace
8156
8157void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
8158 uint64_t MagicValue, QualType Type,
8159 bool LayoutCompatible,
8160 bool MustBeNull) {
8161 if (!TypeTagForDatatypeMagicValues)
8162 TypeTagForDatatypeMagicValues.reset(
8163 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
8164
8165 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
8166 (*TypeTagForDatatypeMagicValues)[Magic] =
8167 TypeTagData(Type, LayoutCompatible, MustBeNull);
8168}
8169
8170namespace {
8171bool IsSameCharType(QualType T1, QualType T2) {
8172 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
8173 if (!BT1)
8174 return false;
8175
8176 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
8177 if (!BT2)
8178 return false;
8179
8180 BuiltinType::Kind T1Kind = BT1->getKind();
8181 BuiltinType::Kind T2Kind = BT2->getKind();
8182
8183 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
8184 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
8185 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
8186 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
8187}
8188} // unnamed namespace
8189
8190void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
8191 const Expr * const *ExprArgs) {
8192 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
8193 bool IsPointerAttr = Attr->getIsPointer();
8194
8195 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
8196 bool FoundWrongKind;
8197 TypeTagData TypeInfo;
8198 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
8199 TypeTagForDatatypeMagicValues.get(),
8200 FoundWrongKind, TypeInfo)) {
8201 if (FoundWrongKind)
8202 Diag(TypeTagExpr->getExprLoc(),
8203 diag::warn_type_tag_for_datatype_wrong_kind)
8204 << TypeTagExpr->getSourceRange();
8205 return;
8206 }
8207
8208 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
8209 if (IsPointerAttr) {
8210 // Skip implicit cast of pointer to `void *' (as a function argument).
8211 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +00008212 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +00008213 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008214 ArgumentExpr = ICE->getSubExpr();
8215 }
8216 QualType ArgumentType = ArgumentExpr->getType();
8217
8218 // Passing a `void*' pointer shouldn't trigger a warning.
8219 if (IsPointerAttr && ArgumentType->isVoidPointerType())
8220 return;
8221
8222 if (TypeInfo.MustBeNull) {
8223 // Type tag with matching void type requires a null pointer.
8224 if (!ArgumentExpr->isNullPointerConstant(Context,
8225 Expr::NPC_ValueDependentIsNotNull)) {
8226 Diag(ArgumentExpr->getExprLoc(),
8227 diag::warn_type_safety_null_pointer_required)
8228 << ArgumentKind->getName()
8229 << ArgumentExpr->getSourceRange()
8230 << TypeTagExpr->getSourceRange();
8231 }
8232 return;
8233 }
8234
8235 QualType RequiredType = TypeInfo.Type;
8236 if (IsPointerAttr)
8237 RequiredType = Context.getPointerType(RequiredType);
8238
8239 bool mismatch = false;
8240 if (!TypeInfo.LayoutCompatible) {
8241 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
8242
8243 // C++11 [basic.fundamental] p1:
8244 // Plain char, signed char, and unsigned char are three distinct types.
8245 //
8246 // But we treat plain `char' as equivalent to `signed char' or `unsigned
8247 // char' depending on the current char signedness mode.
8248 if (mismatch)
8249 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
8250 RequiredType->getPointeeType())) ||
8251 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
8252 mismatch = false;
8253 } else
8254 if (IsPointerAttr)
8255 mismatch = !isLayoutCompatible(Context,
8256 ArgumentType->getPointeeType(),
8257 RequiredType->getPointeeType());
8258 else
8259 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
8260
8261 if (mismatch)
8262 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +00008263 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008264 << TypeInfo.LayoutCompatible << RequiredType
8265 << ArgumentExpr->getSourceRange()
8266 << TypeTagExpr->getSourceRange();
8267}
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008268