blob: a98b87544a6b043d488437d5b8073ffb8556f6f4 [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
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000114static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
115 CallExpr *TheCall, unsigned SizeIdx,
116 unsigned DstSizeIdx) {
117 if (TheCall->getNumArgs() <= SizeIdx ||
118 TheCall->getNumArgs() <= DstSizeIdx)
119 return;
120
121 const Expr *SizeArg = TheCall->getArg(SizeIdx);
122 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
123
124 llvm::APSInt Size, DstSize;
125
126 // find out if both sizes are known at compile time
127 if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
128 !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
129 return;
130
131 if (Size.ule(DstSize))
132 return;
133
134 // confirmed overflow so generate the diagnostic.
135 IdentifierInfo *FnName = FDecl->getIdentifier();
136 SourceLocation SL = TheCall->getLocStart();
137 SourceRange SR = TheCall->getSourceRange();
138
139 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
140}
141
John McCalldadc5752010-08-24 06:29:42 +0000142ExprResult
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000143Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
144 CallExpr *TheCall) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000145 ExprResult TheCallResult(TheCall);
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000146
Chris Lattner3be167f2010-10-01 23:23:24 +0000147 // Find out if any arguments are required to be integer constant expressions.
148 unsigned ICEArguments = 0;
149 ASTContext::GetBuiltinTypeError Error;
150 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
151 if (Error != ASTContext::GE_None)
152 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
153
154 // If any arguments are required to be ICE's, check and diagnose.
155 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
156 // Skip arguments not required to be ICE's.
157 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
158
159 llvm::APSInt Result;
160 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
161 return true;
162 ICEArguments &= ~(1 << ArgNo);
163 }
164
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000165 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000166 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000167 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000168 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000169 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000170 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000171 break;
Ted Kremeneka174c522008-07-09 17:58:53 +0000172 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000173 case Builtin::BI__builtin_va_start:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000174 if (SemaBuiltinVAStart(TheCall))
175 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000176 break;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000177 case Builtin::BI__va_start: {
178 switch (Context.getTargetInfo().getTriple().getArch()) {
179 case llvm::Triple::arm:
180 case llvm::Triple::thumb:
181 if (SemaBuiltinVAStartARM(TheCall))
182 return ExprError();
183 break;
184 default:
185 if (SemaBuiltinVAStart(TheCall))
186 return ExprError();
187 break;
188 }
189 break;
190 }
Chris Lattner2da14fb2007-12-20 00:26:33 +0000191 case Builtin::BI__builtin_isgreater:
192 case Builtin::BI__builtin_isgreaterequal:
193 case Builtin::BI__builtin_isless:
194 case Builtin::BI__builtin_islessequal:
195 case Builtin::BI__builtin_islessgreater:
196 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000197 if (SemaBuiltinUnorderedCompare(TheCall))
198 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000199 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000200 case Builtin::BI__builtin_fpclassify:
201 if (SemaBuiltinFPClassification(TheCall, 6))
202 return ExprError();
203 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000204 case Builtin::BI__builtin_isfinite:
205 case Builtin::BI__builtin_isinf:
206 case Builtin::BI__builtin_isinf_sign:
207 case Builtin::BI__builtin_isnan:
208 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000209 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000210 return ExprError();
211 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000212 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000213 return SemaBuiltinShuffleVector(TheCall);
214 // TheCall will be freed by the smart pointer here, but that's fine, since
215 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000216 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000217 if (SemaBuiltinPrefetch(TheCall))
218 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000219 break;
Hal Finkelf0417332014-07-17 14:25:55 +0000220 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +0000221 case Builtin::BI__builtin_assume:
Hal Finkelf0417332014-07-17 14:25:55 +0000222 if (SemaBuiltinAssume(TheCall))
223 return ExprError();
224 break;
Hal Finkelbcc06082014-09-07 22:58:14 +0000225 case Builtin::BI__builtin_assume_aligned:
226 if (SemaBuiltinAssumeAligned(TheCall))
227 return ExprError();
228 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000229 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000230 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000231 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000232 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000233 case Builtin::BI__builtin_longjmp:
234 if (SemaBuiltinLongjmp(TheCall))
235 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000236 break;
John McCallbebede42011-02-26 05:39:39 +0000237
238 case Builtin::BI__builtin_classify_type:
239 if (checkArgCount(*this, TheCall, 1)) return true;
240 TheCall->setType(Context.IntTy);
241 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000242 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000243 if (checkArgCount(*this, TheCall, 1)) return true;
244 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000245 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000246 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000247 case Builtin::BI__sync_fetch_and_add_1:
248 case Builtin::BI__sync_fetch_and_add_2:
249 case Builtin::BI__sync_fetch_and_add_4:
250 case Builtin::BI__sync_fetch_and_add_8:
251 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000252 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000253 case Builtin::BI__sync_fetch_and_sub_1:
254 case Builtin::BI__sync_fetch_and_sub_2:
255 case Builtin::BI__sync_fetch_and_sub_4:
256 case Builtin::BI__sync_fetch_and_sub_8:
257 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000258 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000259 case Builtin::BI__sync_fetch_and_or_1:
260 case Builtin::BI__sync_fetch_and_or_2:
261 case Builtin::BI__sync_fetch_and_or_4:
262 case Builtin::BI__sync_fetch_and_or_8:
263 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000264 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000265 case Builtin::BI__sync_fetch_and_and_1:
266 case Builtin::BI__sync_fetch_and_and_2:
267 case Builtin::BI__sync_fetch_and_and_4:
268 case Builtin::BI__sync_fetch_and_and_8:
269 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000270 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000271 case Builtin::BI__sync_fetch_and_xor_1:
272 case Builtin::BI__sync_fetch_and_xor_2:
273 case Builtin::BI__sync_fetch_and_xor_4:
274 case Builtin::BI__sync_fetch_and_xor_8:
275 case Builtin::BI__sync_fetch_and_xor_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000276 case Builtin::BI__sync_fetch_and_nand:
277 case Builtin::BI__sync_fetch_and_nand_1:
278 case Builtin::BI__sync_fetch_and_nand_2:
279 case Builtin::BI__sync_fetch_and_nand_4:
280 case Builtin::BI__sync_fetch_and_nand_8:
281 case Builtin::BI__sync_fetch_and_nand_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000282 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000283 case Builtin::BI__sync_add_and_fetch_1:
284 case Builtin::BI__sync_add_and_fetch_2:
285 case Builtin::BI__sync_add_and_fetch_4:
286 case Builtin::BI__sync_add_and_fetch_8:
287 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000288 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000289 case Builtin::BI__sync_sub_and_fetch_1:
290 case Builtin::BI__sync_sub_and_fetch_2:
291 case Builtin::BI__sync_sub_and_fetch_4:
292 case Builtin::BI__sync_sub_and_fetch_8:
293 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000294 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000295 case Builtin::BI__sync_and_and_fetch_1:
296 case Builtin::BI__sync_and_and_fetch_2:
297 case Builtin::BI__sync_and_and_fetch_4:
298 case Builtin::BI__sync_and_and_fetch_8:
299 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000300 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000301 case Builtin::BI__sync_or_and_fetch_1:
302 case Builtin::BI__sync_or_and_fetch_2:
303 case Builtin::BI__sync_or_and_fetch_4:
304 case Builtin::BI__sync_or_and_fetch_8:
305 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000306 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000307 case Builtin::BI__sync_xor_and_fetch_1:
308 case Builtin::BI__sync_xor_and_fetch_2:
309 case Builtin::BI__sync_xor_and_fetch_4:
310 case Builtin::BI__sync_xor_and_fetch_8:
311 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000312 case Builtin::BI__sync_nand_and_fetch:
313 case Builtin::BI__sync_nand_and_fetch_1:
314 case Builtin::BI__sync_nand_and_fetch_2:
315 case Builtin::BI__sync_nand_and_fetch_4:
316 case Builtin::BI__sync_nand_and_fetch_8:
317 case Builtin::BI__sync_nand_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000318 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000319 case Builtin::BI__sync_val_compare_and_swap_1:
320 case Builtin::BI__sync_val_compare_and_swap_2:
321 case Builtin::BI__sync_val_compare_and_swap_4:
322 case Builtin::BI__sync_val_compare_and_swap_8:
323 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000324 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000325 case Builtin::BI__sync_bool_compare_and_swap_1:
326 case Builtin::BI__sync_bool_compare_and_swap_2:
327 case Builtin::BI__sync_bool_compare_and_swap_4:
328 case Builtin::BI__sync_bool_compare_and_swap_8:
329 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000330 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000331 case Builtin::BI__sync_lock_test_and_set_1:
332 case Builtin::BI__sync_lock_test_and_set_2:
333 case Builtin::BI__sync_lock_test_and_set_4:
334 case Builtin::BI__sync_lock_test_and_set_8:
335 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000336 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000337 case Builtin::BI__sync_lock_release_1:
338 case Builtin::BI__sync_lock_release_2:
339 case Builtin::BI__sync_lock_release_4:
340 case Builtin::BI__sync_lock_release_8:
341 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000342 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000343 case Builtin::BI__sync_swap_1:
344 case Builtin::BI__sync_swap_2:
345 case Builtin::BI__sync_swap_4:
346 case Builtin::BI__sync_swap_8:
347 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000348 return SemaBuiltinAtomicOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +0000349#define BUILTIN(ID, TYPE, ATTRS)
350#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
351 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000352 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +0000353#include "clang/Basic/Builtins.def"
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000354 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000355 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000356 return ExprError();
357 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +0000358 case Builtin::BI__builtin_addressof:
359 if (SemaBuiltinAddressof(*this, TheCall))
360 return ExprError();
361 break;
Richard Smith760520b2014-06-03 23:27:44 +0000362 case Builtin::BI__builtin_operator_new:
363 case Builtin::BI__builtin_operator_delete:
364 if (!getLangOpts().CPlusPlus) {
365 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
366 << (BuiltinID == Builtin::BI__builtin_operator_new
367 ? "__builtin_operator_new"
368 : "__builtin_operator_delete")
369 << "C++";
370 return ExprError();
371 }
372 // CodeGen assumes it can find the global new and delete to call,
373 // so ensure that they are declared.
374 DeclareGlobalNewDelete();
375 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000376
377 // check secure string manipulation functions where overflows
378 // are detectable at compile time
379 case Builtin::BI__builtin___memcpy_chk:
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000380 case Builtin::BI__builtin___memmove_chk:
381 case Builtin::BI__builtin___memset_chk:
382 case Builtin::BI__builtin___strlcat_chk:
383 case Builtin::BI__builtin___strlcpy_chk:
384 case Builtin::BI__builtin___strncat_chk:
385 case Builtin::BI__builtin___strncpy_chk:
386 case Builtin::BI__builtin___stpncpy_chk:
387 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
388 break;
Steven Wu566c14e2014-09-24 04:37:33 +0000389 case Builtin::BI__builtin___memccpy_chk:
390 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
391 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000392 case Builtin::BI__builtin___snprintf_chk:
393 case Builtin::BI__builtin___vsnprintf_chk:
394 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
395 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000396 }
Richard Smith760520b2014-06-03 23:27:44 +0000397
Nate Begeman4904e322010-06-08 02:47:44 +0000398 // Since the target specific builtins for each arch overlap, only check those
399 // of the arch we are compiling for.
400 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000401 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +0000402 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000403 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000404 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000405 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000406 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
407 return ExprError();
408 break;
Tim Northover25e8a672014-05-24 12:51:25 +0000409 case llvm::Triple::aarch64:
410 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +0000411 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +0000412 return ExprError();
413 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000414 case llvm::Triple::mips:
415 case llvm::Triple::mipsel:
416 case llvm::Triple::mips64:
417 case llvm::Triple::mips64el:
418 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
419 return ExprError();
420 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000421 case llvm::Triple::x86:
422 case llvm::Triple::x86_64:
423 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
424 return ExprError();
425 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000426 default:
427 break;
428 }
429 }
430
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000431 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +0000432}
433
Nate Begeman91e1fea2010-06-14 05:21:25 +0000434// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +0000435static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +0000436 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +0000437 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +0000438 switch (Type.getEltType()) {
439 case NeonTypeFlags::Int8:
440 case NeonTypeFlags::Poly8:
441 return shift ? 7 : (8 << IsQuad) - 1;
442 case NeonTypeFlags::Int16:
443 case NeonTypeFlags::Poly16:
444 return shift ? 15 : (4 << IsQuad) - 1;
445 case NeonTypeFlags::Int32:
446 return shift ? 31 : (2 << IsQuad) - 1;
447 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +0000448 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +0000449 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000450 case NeonTypeFlags::Poly128:
451 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +0000452 case NeonTypeFlags::Float16:
453 assert(!shift && "cannot shift float types!");
454 return (4 << IsQuad) - 1;
455 case NeonTypeFlags::Float32:
456 assert(!shift && "cannot shift float types!");
457 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000458 case NeonTypeFlags::Float64:
459 assert(!shift && "cannot shift float types!");
460 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000461 }
David Blaikie8a40f702012-01-17 06:56:22 +0000462 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +0000463}
464
Bob Wilsone4d77232011-11-08 05:04:11 +0000465/// getNeonEltType - Return the QualType corresponding to the elements of
466/// the vector type specified by the NeonTypeFlags. This is used to check
467/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +0000468static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +0000469 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +0000470 switch (Flags.getEltType()) {
471 case NeonTypeFlags::Int8:
472 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
473 case NeonTypeFlags::Int16:
474 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
475 case NeonTypeFlags::Int32:
476 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
477 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +0000478 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +0000479 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
480 else
481 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
482 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000483 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +0000484 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000485 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +0000486 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +0000487 case NeonTypeFlags::Poly64:
Kevin Qinad64f6d2014-02-24 02:45:03 +0000488 return Context.UnsignedLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000489 case NeonTypeFlags::Poly128:
490 break;
Bob Wilsone4d77232011-11-08 05:04:11 +0000491 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +0000492 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000493 case NeonTypeFlags::Float32:
494 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +0000495 case NeonTypeFlags::Float64:
496 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000497 }
David Blaikie8a40f702012-01-17 06:56:22 +0000498 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +0000499}
500
Tim Northover12670412014-02-19 10:37:05 +0000501bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +0000502 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +0000503 uint64_t mask = 0;
504 unsigned TV = 0;
505 int PtrArgNum = -1;
506 bool HasConstPtr = false;
507 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +0000508#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000509#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000510#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000511 }
512
513 // For NEON intrinsics which are overloaded on vector element type, validate
514 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +0000515 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000516 if (mask) {
517 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
518 return true;
519
520 TV = Result.getLimitedValue(64);
521 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
522 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +0000523 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +0000524 }
525
526 if (PtrArgNum >= 0) {
527 // Check that pointer arguments have the specified type.
528 Expr *Arg = TheCall->getArg(PtrArgNum);
529 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
530 Arg = ICE->getSubExpr();
531 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
532 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +0000533
Tim Northovera2ee4332014-03-29 15:09:45 +0000534 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Tim Northover40956e62014-07-23 12:32:58 +0000535 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
Tim Northovera2ee4332014-03-29 15:09:45 +0000536 bool IsInt64Long =
537 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
538 QualType EltTy =
539 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +0000540 if (HasConstPtr)
541 EltTy = EltTy.withConst();
542 QualType LHSTy = Context.getPointerType(EltTy);
543 AssignConvertType ConvTy;
544 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
545 if (RHS.isInvalid())
546 return true;
547 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
548 RHS.get(), AA_Assigning))
549 return true;
550 }
551
552 // For NEON intrinsics which take an immediate value as part of the
553 // instruction, range check them here.
554 unsigned i = 0, l = 0, u = 0;
555 switch (BuiltinID) {
556 default:
557 return false;
Tim Northover12670412014-02-19 10:37:05 +0000558#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000559#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000560#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000561 }
Tim Northover2fe823a2013-08-01 09:23:19 +0000562
Richard Sandiford28940af2014-04-16 08:47:51 +0000563 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +0000564}
565
Tim Northovera2ee4332014-03-29 15:09:45 +0000566bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
567 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +0000568 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000569 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +0000570 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000571 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +0000572 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000573 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
574 BuiltinID == AArch64::BI__builtin_arm_strex ||
575 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +0000576 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +0000577 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000578 BuiltinID == ARM::BI__builtin_arm_ldaex ||
579 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
580 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +0000581
582 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
583
584 // Ensure that we have the proper number of arguments.
585 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
586 return true;
587
588 // Inspect the pointer argument of the atomic builtin. This should always be
589 // a pointer type, whose element is an integral scalar or pointer type.
590 // Because it is a pointer type, we don't have to worry about any implicit
591 // casts here.
592 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
593 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
594 if (PointerArgRes.isInvalid())
595 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000596 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000597
598 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
599 if (!pointerType) {
600 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
601 << PointerArg->getType() << PointerArg->getSourceRange();
602 return true;
603 }
604
605 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
606 // task is to insert the appropriate casts into the AST. First work out just
607 // what the appropriate type is.
608 QualType ValType = pointerType->getPointeeType();
609 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
610 if (IsLdrex)
611 AddrType.addConst();
612
613 // Issue a warning if the cast is dodgy.
614 CastKind CastNeeded = CK_NoOp;
615 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
616 CastNeeded = CK_BitCast;
617 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
618 << PointerArg->getType()
619 << Context.getPointerType(AddrType)
620 << AA_Passing << PointerArg->getSourceRange();
621 }
622
623 // Finally, do the cast and replace the argument with the corrected version.
624 AddrType = Context.getPointerType(AddrType);
625 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
626 if (PointerArgRes.isInvalid())
627 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000628 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000629
630 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
631
632 // In general, we allow ints, floats and pointers to be loaded and stored.
633 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
634 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
635 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
636 << PointerArg->getType() << PointerArg->getSourceRange();
637 return true;
638 }
639
640 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +0000641 if (Context.getTypeSize(ValType) > MaxWidth) {
642 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +0000643 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
644 << PointerArg->getType() << PointerArg->getSourceRange();
645 return true;
646 }
647
648 switch (ValType.getObjCLifetime()) {
649 case Qualifiers::OCL_None:
650 case Qualifiers::OCL_ExplicitNone:
651 // okay
652 break;
653
654 case Qualifiers::OCL_Weak:
655 case Qualifiers::OCL_Strong:
656 case Qualifiers::OCL_Autoreleasing:
657 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
658 << ValType << PointerArg->getSourceRange();
659 return true;
660 }
661
662
663 if (IsLdrex) {
664 TheCall->setType(ValType);
665 return false;
666 }
667
668 // Initialize the argument to be stored.
669 ExprResult ValArg = TheCall->getArg(0);
670 InitializedEntity Entity = InitializedEntity::InitializeParameter(
671 Context, ValType, /*consume*/ false);
672 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
673 if (ValArg.isInvalid())
674 return true;
Tim Northover6aacd492013-07-16 09:47:53 +0000675 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +0000676
677 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
678 // but the custom checker bypasses all default analysis.
679 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +0000680 return false;
681}
682
Nate Begeman4904e322010-06-08 02:47:44 +0000683bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +0000684 llvm::APSInt Result;
685
Tim Northover6aacd492013-07-16 09:47:53 +0000686 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000687 BuiltinID == ARM::BI__builtin_arm_ldaex ||
688 BuiltinID == ARM::BI__builtin_arm_strex ||
689 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000690 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +0000691 }
692
Yi Kong26d104a2014-08-13 19:18:14 +0000693 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
694 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
695 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
696 }
697
Tim Northover12670412014-02-19 10:37:05 +0000698 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
699 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +0000700
Yi Kong4efadfb2014-07-03 16:01:25 +0000701 // For intrinsics which take an immediate value as part of the instruction,
702 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +0000703 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +0000704 switch (BuiltinID) {
705 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +0000706 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
707 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +0000708 case ARM::BI__builtin_arm_vcvtr_f:
709 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +0000710 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +0000711 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +0000712 case ARM::BI__builtin_arm_isb:
713 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +0000714 }
Nate Begemand773fe62010-06-13 04:47:52 +0000715
Nate Begemanf568b072010-08-03 21:32:34 +0000716 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +0000717 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000718}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000719
Tim Northover573cbee2014-05-24 12:52:07 +0000720bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +0000721 CallExpr *TheCall) {
722 llvm::APSInt Result;
723
Tim Northover573cbee2014-05-24 12:52:07 +0000724 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000725 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
726 BuiltinID == AArch64::BI__builtin_arm_strex ||
727 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000728 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
729 }
730
Yi Konga5548432014-08-13 19:18:20 +0000731 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
732 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
733 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
734 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
735 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
736 }
737
Tim Northovera2ee4332014-03-29 15:09:45 +0000738 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
739 return true;
740
Yi Kong19a29ac2014-07-17 10:52:06 +0000741 // For intrinsics which take an immediate value as part of the instruction,
742 // range check them here.
743 unsigned i = 0, l = 0, u = 0;
744 switch (BuiltinID) {
745 default: return false;
746 case AArch64::BI__builtin_arm_dmb:
747 case AArch64::BI__builtin_arm_dsb:
748 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
749 }
750
Yi Kong19a29ac2014-07-17 10:52:06 +0000751 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +0000752}
753
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000754bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
755 unsigned i = 0, l = 0, u = 0;
756 switch (BuiltinID) {
757 default: return false;
758 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
759 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +0000760 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
761 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
762 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
763 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
764 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Richard Sandiford28940af2014-04-16 08:47:51 +0000765 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000766
Richard Sandiford28940af2014-04-16 08:47:51 +0000767 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000768}
769
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000770bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
771 switch (BuiltinID) {
772 case X86::BI_mm_prefetch:
Richard Sandiford28940af2014-04-16 08:47:51 +0000773 // This is declared to take (const char*, int)
774 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000775 }
776 return false;
777}
778
Richard Smith55ce3522012-06-25 20:30:08 +0000779/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
780/// parameter with the FormatAttr's correct format_idx and firstDataArg.
781/// Returns true when the format fits the function and the FormatStringInfo has
782/// been populated.
783bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
784 FormatStringInfo *FSI) {
785 FSI->HasVAListArg = Format->getFirstArg() == 0;
786 FSI->FormatIdx = Format->getFormatIdx() - 1;
787 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000788
Richard Smith55ce3522012-06-25 20:30:08 +0000789 // The way the format attribute works in GCC, the implicit this argument
790 // of member functions is counted. However, it doesn't appear in our own
791 // lists, so decrement format_idx in that case.
792 if (IsCXXMember) {
793 if(FSI->FormatIdx == 0)
794 return false;
795 --FSI->FormatIdx;
796 if (FSI->FirstDataArg != 0)
797 --FSI->FirstDataArg;
798 }
799 return true;
800}
Mike Stump11289f42009-09-09 15:08:12 +0000801
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000802/// Checks if a the given expression evaluates to null.
803///
804/// \brief Returns true if the value evaluates to null.
805static bool CheckNonNullExpr(Sema &S,
806 const Expr *Expr) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000807 // As a special case, transparent unions initialized with zero are
808 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000809 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000810 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
811 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000812 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000813 if (const InitListExpr *ILE =
814 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000815 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +0000816 }
817
818 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +0000819 return (!Expr->isValueDependent() &&
820 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
821 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000822}
823
824static void CheckNonNullArgument(Sema &S,
825 const Expr *ArgExpr,
826 SourceLocation CallSiteLoc) {
827 if (CheckNonNullExpr(S, ArgExpr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000828 S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
829}
830
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +0000831bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
832 FormatStringInfo FSI;
833 if ((GetFormatStringType(Format) == FST_NSString) &&
834 getFormatStringInfo(Format, false, &FSI)) {
835 Idx = FSI.FormatIdx;
836 return true;
837 }
838 return false;
839}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +0000840/// \brief Diagnose use of %s directive in an NSString which is being passed
841/// as formatting string to formatting method.
842static void
843DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
844 const NamedDecl *FDecl,
845 Expr **Args,
846 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +0000847 unsigned Idx = 0;
848 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +0000849 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
850 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +0000851 Idx = 2;
852 Format = true;
853 }
854 else
855 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
856 if (S.GetFormatNSStringIdx(I, Idx)) {
857 Format = true;
858 break;
859 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +0000860 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +0000861 if (!Format || NumArgs <= Idx)
862 return;
863 const Expr *FormatExpr = Args[Idx];
864 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
865 FormatExpr = CSCE->getSubExpr();
866 const StringLiteral *FormatString;
867 if (const ObjCStringLiteral *OSL =
868 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
869 FormatString = OSL->getString();
870 else
871 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
872 if (!FormatString)
873 return;
874 if (S.FormatStringHasSArg(FormatString)) {
875 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
876 << "%s" << 1 << 1;
877 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
878 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +0000879 }
880}
881
Ted Kremenek2bc73332014-01-17 06:24:43 +0000882static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +0000883 const NamedDecl *FDecl,
Richard Smith588bd9b2014-08-27 04:59:42 +0000884 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +0000885 SourceLocation CallSiteLoc) {
Ted Kremenek9aedc152014-01-17 06:24:56 +0000886 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +0000887 llvm::SmallBitVector NonNullArgs;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000888 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
Richard Smith588bd9b2014-08-27 04:59:42 +0000889 if (!NonNull->args_size()) {
890 // Easy case: all pointer arguments are nonnull.
891 for (const auto *Arg : Args)
Hal Finkelee90a222014-09-26 05:04:30 +0000892 if (S.isValidPointerAttrType(Arg->getType()))
Richard Smith588bd9b2014-08-27 04:59:42 +0000893 CheckNonNullArgument(S, Arg, CallSiteLoc);
894 return;
895 }
896
897 for (unsigned Val : NonNull->args()) {
898 if (Val >= Args.size())
899 continue;
900 if (NonNullArgs.empty())
901 NonNullArgs.resize(Args.size());
902 NonNullArgs.set(Val);
903 }
Ted Kremenek2bc73332014-01-17 06:24:43 +0000904 }
Ted Kremenek9aedc152014-01-17 06:24:56 +0000905
906 // Check the attributes on the parameters.
907 ArrayRef<ParmVarDecl*> parms;
908 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
909 parms = FD->parameters();
910 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(FDecl))
911 parms = MD->parameters();
912
Richard Smith588bd9b2014-08-27 04:59:42 +0000913 unsigned ArgIndex = 0;
Ted Kremenek9aedc152014-01-17 06:24:56 +0000914 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
Richard Smith588bd9b2014-08-27 04:59:42 +0000915 I != E; ++I, ++ArgIndex) {
Ted Kremenek9aedc152014-01-17 06:24:56 +0000916 const ParmVarDecl *PVD = *I;
Richard Smith588bd9b2014-08-27 04:59:42 +0000917 if (PVD->hasAttr<NonNullAttr>() ||
918 (ArgIndex < NonNullArgs.size() && NonNullArgs[ArgIndex]))
919 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Ted Kremenek9aedc152014-01-17 06:24:56 +0000920 }
Richard Smith588bd9b2014-08-27 04:59:42 +0000921
922 // In case this is a variadic call, check any remaining arguments.
923 for (/**/; ArgIndex < NonNullArgs.size(); ++ArgIndex)
924 if (NonNullArgs[ArgIndex])
925 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Ted Kremenek2bc73332014-01-17 06:24:43 +0000926}
927
Richard Smith55ce3522012-06-25 20:30:08 +0000928/// Handles the checks for format strings, non-POD arguments to vararg
929/// functions, and NULL arguments passed to non-NULL parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +0000930void Sema::checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
931 unsigned NumParams, bool IsMemberFunction,
932 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +0000933 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +0000934 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +0000935 if (CurContext->isDependentContext())
936 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000937
Ted Kremenekb8176da2010-09-09 04:33:05 +0000938 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +0000939 llvm::SmallBitVector CheckedVarArgs;
940 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000941 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +0000942 // Only create vector if there are format attributes.
943 CheckedVarArgs.resize(Args.size());
944
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000945 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +0000946 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +0000947 }
Richard Smithd7293d72013-08-05 18:49:43 +0000948 }
Richard Smith55ce3522012-06-25 20:30:08 +0000949
950 // Refuse POD arguments that weren't caught by the format string
951 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +0000952 if (CallType != VariadicDoesNotApply) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000953 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +0000954 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +0000955 if (const Expr *Arg = Args[ArgIdx]) {
956 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
957 checkVariadicArgument(Arg, CallType);
958 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +0000959 }
Richard Smithd7293d72013-08-05 18:49:43 +0000960 }
Mike Stump11289f42009-09-09 15:08:12 +0000961
Richard Trieu41bc0992013-06-22 00:20:41 +0000962 if (FDecl) {
Richard Smith588bd9b2014-08-27 04:59:42 +0000963 CheckNonNullArguments(*this, FDecl, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000964
Richard Trieu41bc0992013-06-22 00:20:41 +0000965 // Type safety checking.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000966 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
967 CheckArgumentWithTypeTag(I, Args.data());
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000968 }
Richard Smith55ce3522012-06-25 20:30:08 +0000969}
970
971/// CheckConstructorCall - Check a constructor call for correctness and safety
972/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +0000973void Sema::CheckConstructorCall(FunctionDecl *FDecl,
974 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +0000975 const FunctionProtoType *Proto,
976 SourceLocation Loc) {
977 VariadicCallType CallType =
978 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Alp Toker9cacbab2014-01-20 20:26:09 +0000979 checkCall(FDecl, Args, Proto->getNumParams(),
Richard Smith55ce3522012-06-25 20:30:08 +0000980 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
981}
982
983/// CheckFunctionCall - Check a direct function call for various correctness
984/// and safety properties not strictly enforced by the C type system.
985bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
986 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +0000987 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
988 isa<CXXMethodDecl>(FDecl);
989 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
990 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +0000991 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
992 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +0000993 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Eli Friedman726d11c2012-10-11 00:30:58 +0000994 Expr** Args = TheCall->getArgs();
995 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +0000996 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +0000997 // If this is a call to a member operator, hide the first argument
998 // from checkCall.
999 // FIXME: Our choice of AST representation here is less than ideal.
1000 ++Args;
1001 --NumArgs;
1002 }
Craig Topper8c2a2a02014-08-30 16:55:39 +00001003 checkCall(FDecl, llvm::makeArrayRef(Args, NumArgs), NumParams,
Richard Smith55ce3522012-06-25 20:30:08 +00001004 IsMemberFunction, TheCall->getRParenLoc(),
1005 TheCall->getCallee()->getSourceRange(), CallType);
1006
1007 IdentifierInfo *FnInfo = FDecl->getIdentifier();
1008 // None of the checks below are needed for functions that don't have
1009 // simple names (e.g., C++ conversion functions).
1010 if (!FnInfo)
1011 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001012
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001013 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001014 if (getLangOpts().ObjC1)
1015 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001016
Anna Zaks22122702012-01-17 00:37:07 +00001017 unsigned CMId = FDecl->getMemoryFunctionKind();
1018 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00001019 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00001020
Anna Zaks201d4892012-01-13 21:52:01 +00001021 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00001022 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00001023 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00001024 else if (CMId == Builtin::BIstrncat)
1025 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00001026 else
Anna Zaks22122702012-01-17 00:37:07 +00001027 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00001028
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001029 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00001030}
1031
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001032bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00001033 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00001034 VariadicCallType CallType =
1035 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001036
Dmitri Gribenko1debc462013-05-05 19:42:09 +00001037 checkCall(Method, Args, Method->param_size(),
Richard Smith55ce3522012-06-25 20:30:08 +00001038 /*IsMemberFunction=*/false,
1039 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001040
1041 return false;
1042}
1043
Richard Trieu664c4c62013-06-20 21:03:13 +00001044bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
1045 const FunctionProtoType *Proto) {
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001046 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
1047 if (!V)
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001048 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001049
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001050 QualType Ty = V->getType();
Richard Trieu664c4c62013-06-20 21:03:13 +00001051 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001052 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001053
Richard Trieu664c4c62013-06-20 21:03:13 +00001054 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00001055 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00001056 CallType = VariadicDoesNotApply;
1057 } else if (Ty->isBlockPointerType()) {
1058 CallType = VariadicBlock;
1059 } else { // Ty->isFunctionPointerType()
1060 CallType = VariadicFunction;
1061 }
Alp Toker9cacbab2014-01-20 20:26:09 +00001062 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001063
Craig Topper8c2a2a02014-08-30 16:55:39 +00001064 checkCall(NDecl, llvm::makeArrayRef(TheCall->getArgs(),
1065 TheCall->getNumArgs()),
Alp Toker9cacbab2014-01-20 20:26:09 +00001066 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00001067 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00001068
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001069 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001070}
1071
Richard Trieu41bc0992013-06-22 00:20:41 +00001072/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
1073/// such as function pointers returned from functions.
1074bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001075 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00001076 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +00001077 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Richard Trieu41bc0992013-06-22 00:20:41 +00001078
Craig Topperc3ec1492014-05-26 06:22:03 +00001079 checkCall(/*FDecl=*/nullptr,
Craig Topper8c2a2a02014-08-30 16:55:39 +00001080 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Alp Toker9cacbab2014-01-20 20:26:09 +00001081 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00001082 TheCall->getCallee()->getSourceRange(), CallType);
1083
1084 return false;
1085}
1086
Tim Northovere94a34c2014-03-11 10:49:14 +00001087static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
1088 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
1089 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
1090 return false;
1091
1092 switch (Op) {
1093 case AtomicExpr::AO__c11_atomic_init:
1094 llvm_unreachable("There is no ordering argument for an init");
1095
1096 case AtomicExpr::AO__c11_atomic_load:
1097 case AtomicExpr::AO__atomic_load_n:
1098 case AtomicExpr::AO__atomic_load:
1099 return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
1100 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1101
1102 case AtomicExpr::AO__c11_atomic_store:
1103 case AtomicExpr::AO__atomic_store:
1104 case AtomicExpr::AO__atomic_store_n:
1105 return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
1106 Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
1107 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1108
1109 default:
1110 return true;
1111 }
1112}
1113
Richard Smithfeea8832012-04-12 05:08:17 +00001114ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
1115 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001116 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
1117 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001118
Richard Smithfeea8832012-04-12 05:08:17 +00001119 // All these operations take one of the following forms:
1120 enum {
1121 // C __c11_atomic_init(A *, C)
1122 Init,
1123 // C __c11_atomic_load(A *, int)
1124 Load,
1125 // void __atomic_load(A *, CP, int)
1126 Copy,
1127 // C __c11_atomic_add(A *, M, int)
1128 Arithmetic,
1129 // C __atomic_exchange_n(A *, CP, int)
1130 Xchg,
1131 // void __atomic_exchange(A *, C *, CP, int)
1132 GNUXchg,
1133 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
1134 C11CmpXchg,
1135 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
1136 GNUCmpXchg
1137 } Form = Init;
1138 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
1139 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
1140 // where:
1141 // C is an appropriate type,
1142 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
1143 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
1144 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
1145 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001146
Richard Smithfeea8832012-04-12 05:08:17 +00001147 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
1148 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
1149 && "need to update code for modified C11 atomics");
1150 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
1151 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
1152 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
1153 Op == AtomicExpr::AO__atomic_store_n ||
1154 Op == AtomicExpr::AO__atomic_exchange_n ||
1155 Op == AtomicExpr::AO__atomic_compare_exchange_n;
1156 bool IsAddSub = false;
1157
1158 switch (Op) {
1159 case AtomicExpr::AO__c11_atomic_init:
1160 Form = Init;
1161 break;
1162
1163 case AtomicExpr::AO__c11_atomic_load:
1164 case AtomicExpr::AO__atomic_load_n:
1165 Form = Load;
1166 break;
1167
1168 case AtomicExpr::AO__c11_atomic_store:
1169 case AtomicExpr::AO__atomic_load:
1170 case AtomicExpr::AO__atomic_store:
1171 case AtomicExpr::AO__atomic_store_n:
1172 Form = Copy;
1173 break;
1174
1175 case AtomicExpr::AO__c11_atomic_fetch_add:
1176 case AtomicExpr::AO__c11_atomic_fetch_sub:
1177 case AtomicExpr::AO__atomic_fetch_add:
1178 case AtomicExpr::AO__atomic_fetch_sub:
1179 case AtomicExpr::AO__atomic_add_fetch:
1180 case AtomicExpr::AO__atomic_sub_fetch:
1181 IsAddSub = true;
1182 // Fall through.
1183 case AtomicExpr::AO__c11_atomic_fetch_and:
1184 case AtomicExpr::AO__c11_atomic_fetch_or:
1185 case AtomicExpr::AO__c11_atomic_fetch_xor:
1186 case AtomicExpr::AO__atomic_fetch_and:
1187 case AtomicExpr::AO__atomic_fetch_or:
1188 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00001189 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00001190 case AtomicExpr::AO__atomic_and_fetch:
1191 case AtomicExpr::AO__atomic_or_fetch:
1192 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00001193 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00001194 Form = Arithmetic;
1195 break;
1196
1197 case AtomicExpr::AO__c11_atomic_exchange:
1198 case AtomicExpr::AO__atomic_exchange_n:
1199 Form = Xchg;
1200 break;
1201
1202 case AtomicExpr::AO__atomic_exchange:
1203 Form = GNUXchg;
1204 break;
1205
1206 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1207 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1208 Form = C11CmpXchg;
1209 break;
1210
1211 case AtomicExpr::AO__atomic_compare_exchange:
1212 case AtomicExpr::AO__atomic_compare_exchange_n:
1213 Form = GNUCmpXchg;
1214 break;
1215 }
1216
1217 // Check we have the right number of arguments.
1218 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001219 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001220 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001221 << TheCall->getCallee()->getSourceRange();
1222 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00001223 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1224 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001225 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001226 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001227 << TheCall->getCallee()->getSourceRange();
1228 return ExprError();
1229 }
1230
Richard Smithfeea8832012-04-12 05:08:17 +00001231 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001232 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001233 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1234 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1235 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00001236 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001237 << Ptr->getType() << Ptr->getSourceRange();
1238 return ExprError();
1239 }
1240
Richard Smithfeea8832012-04-12 05:08:17 +00001241 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1242 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1243 QualType ValType = AtomTy; // 'C'
1244 if (IsC11) {
1245 if (!AtomTy->isAtomicType()) {
1246 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1247 << Ptr->getType() << Ptr->getSourceRange();
1248 return ExprError();
1249 }
Richard Smithe00921a2012-09-15 06:09:58 +00001250 if (AtomTy.isConstQualified()) {
1251 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1252 << Ptr->getType() << Ptr->getSourceRange();
1253 return ExprError();
1254 }
Richard Smithfeea8832012-04-12 05:08:17 +00001255 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001256 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001257
Richard Smithfeea8832012-04-12 05:08:17 +00001258 // For an arithmetic operation, the implied arithmetic must be well-formed.
1259 if (Form == Arithmetic) {
1260 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1261 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1262 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1263 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1264 return ExprError();
1265 }
1266 if (!IsAddSub && !ValType->isIntegerType()) {
1267 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1268 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1269 return ExprError();
1270 }
1271 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1272 // For __atomic_*_n operations, the value type must be a scalar integral or
1273 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001274 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00001275 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1276 return ExprError();
1277 }
1278
Eli Friedmanaa769812013-09-11 03:49:34 +00001279 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1280 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00001281 // For GNU atomics, require a trivially-copyable type. This is not part of
1282 // the GNU atomics specification, but we enforce it for sanity.
1283 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001284 << Ptr->getType() << Ptr->getSourceRange();
1285 return ExprError();
1286 }
1287
Richard Smithfeea8832012-04-12 05:08:17 +00001288 // FIXME: For any builtin other than a load, the ValType must not be
1289 // const-qualified.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001290
1291 switch (ValType.getObjCLifetime()) {
1292 case Qualifiers::OCL_None:
1293 case Qualifiers::OCL_ExplicitNone:
1294 // okay
1295 break;
1296
1297 case Qualifiers::OCL_Weak:
1298 case Qualifiers::OCL_Strong:
1299 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00001300 // FIXME: Can this happen? By this point, ValType should be known
1301 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001302 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1303 << ValType << Ptr->getSourceRange();
1304 return ExprError();
1305 }
1306
1307 QualType ResultType = ValType;
Richard Smithfeea8832012-04-12 05:08:17 +00001308 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001309 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00001310 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001311 ResultType = Context.BoolTy;
1312
Richard Smithfeea8832012-04-12 05:08:17 +00001313 // The type of a parameter passed 'by value'. In the GNU atomics, such
1314 // arguments are actually passed as pointers.
1315 QualType ByValType = ValType; // 'CP'
1316 if (!IsC11 && !IsN)
1317 ByValType = Ptr->getType();
1318
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001319 // The first argument --- the pointer --- has a fixed type; we
1320 // deduce the types of the rest of the arguments accordingly. Walk
1321 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00001322 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001323 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00001324 if (i < NumVals[Form] + 1) {
1325 switch (i) {
1326 case 1:
1327 // The second argument is the non-atomic operand. For arithmetic, this
1328 // is always passed by value, and for a compare_exchange it is always
1329 // passed by address. For the rest, GNU uses by-address and C11 uses
1330 // by-value.
1331 assert(Form != Load);
1332 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1333 Ty = ValType;
1334 else if (Form == Copy || Form == Xchg)
1335 Ty = ByValType;
1336 else if (Form == Arithmetic)
1337 Ty = Context.getPointerDiffType();
1338 else
1339 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1340 break;
1341 case 2:
1342 // The third argument to compare_exchange / GNU exchange is a
1343 // (pointer to a) desired value.
1344 Ty = ByValType;
1345 break;
1346 case 3:
1347 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1348 Ty = Context.BoolTy;
1349 break;
1350 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001351 } else {
1352 // The order(s) are always converted to int.
1353 Ty = Context.IntTy;
1354 }
Richard Smithfeea8832012-04-12 05:08:17 +00001355
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001356 InitializedEntity Entity =
1357 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00001358 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001359 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1360 if (Arg.isInvalid())
1361 return true;
1362 TheCall->setArg(i, Arg.get());
1363 }
1364
Richard Smithfeea8832012-04-12 05:08:17 +00001365 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001366 SmallVector<Expr*, 5> SubExprs;
1367 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00001368 switch (Form) {
1369 case Init:
1370 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00001371 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001372 break;
1373 case Load:
1374 SubExprs.push_back(TheCall->getArg(1)); // Order
1375 break;
1376 case Copy:
1377 case Arithmetic:
1378 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001379 SubExprs.push_back(TheCall->getArg(2)); // Order
1380 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001381 break;
1382 case GNUXchg:
1383 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1384 SubExprs.push_back(TheCall->getArg(3)); // Order
1385 SubExprs.push_back(TheCall->getArg(1)); // Val1
1386 SubExprs.push_back(TheCall->getArg(2)); // Val2
1387 break;
1388 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001389 SubExprs.push_back(TheCall->getArg(3)); // Order
1390 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001391 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00001392 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00001393 break;
1394 case GNUCmpXchg:
1395 SubExprs.push_back(TheCall->getArg(4)); // Order
1396 SubExprs.push_back(TheCall->getArg(1)); // Val1
1397 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1398 SubExprs.push_back(TheCall->getArg(2)); // Val2
1399 SubExprs.push_back(TheCall->getArg(3)); // Weak
1400 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001401 }
Tim Northovere94a34c2014-03-11 10:49:14 +00001402
1403 if (SubExprs.size() >= 2 && Form != Init) {
1404 llvm::APSInt Result(32);
1405 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
1406 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00001407 Diag(SubExprs[1]->getLocStart(),
1408 diag::warn_atomic_op_has_invalid_memory_order)
1409 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00001410 }
1411
Fariborz Jahanian615de762013-05-28 17:37:39 +00001412 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1413 SubExprs, ResultType, Op,
1414 TheCall->getRParenLoc());
1415
1416 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1417 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1418 Context.AtomicUsesUnsupportedLibcall(AE))
1419 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1420 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001421
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001422 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001423}
1424
1425
John McCall29ad95b2011-08-27 01:09:30 +00001426/// checkBuiltinArgument - Given a call to a builtin function, perform
1427/// normal type-checking on the given argument, updating the call in
1428/// place. This is useful when a builtin function requires custom
1429/// type-checking for some of its arguments but not necessarily all of
1430/// them.
1431///
1432/// Returns true on error.
1433static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1434 FunctionDecl *Fn = E->getDirectCallee();
1435 assert(Fn && "builtin call without direct callee!");
1436
1437 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1438 InitializedEntity Entity =
1439 InitializedEntity::InitializeParameter(S.Context, Param);
1440
1441 ExprResult Arg = E->getArg(0);
1442 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1443 if (Arg.isInvalid())
1444 return true;
1445
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001446 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00001447 return false;
1448}
1449
Chris Lattnerdc046542009-05-08 06:58:22 +00001450/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1451/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1452/// type of its first argument. The main ActOnCallExpr routines have already
1453/// promoted the types of arguments because all of these calls are prototyped as
1454/// void(...).
1455///
1456/// This function goes through and does final semantic checking for these
1457/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00001458ExprResult
1459Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001460 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00001461 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1462 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1463
1464 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001465 if (TheCall->getNumArgs() < 1) {
1466 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1467 << 0 << 1 << TheCall->getNumArgs()
1468 << TheCall->getCallee()->getSourceRange();
1469 return ExprError();
1470 }
Mike Stump11289f42009-09-09 15:08:12 +00001471
Chris Lattnerdc046542009-05-08 06:58:22 +00001472 // Inspect the first argument of the atomic builtin. This should always be
1473 // a pointer type, whose element is an integral scalar or pointer type.
1474 // Because it is a pointer type, we don't have to worry about any implicit
1475 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001476 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00001477 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00001478 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1479 if (FirstArgResult.isInvalid())
1480 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001481 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00001482 TheCall->setArg(0, FirstArg);
1483
John McCall31168b02011-06-15 23:02:42 +00001484 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1485 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001486 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1487 << FirstArg->getType() << FirstArg->getSourceRange();
1488 return ExprError();
1489 }
Mike Stump11289f42009-09-09 15:08:12 +00001490
John McCall31168b02011-06-15 23:02:42 +00001491 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00001492 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001493 !ValType->isBlockPointerType()) {
1494 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1495 << FirstArg->getType() << FirstArg->getSourceRange();
1496 return ExprError();
1497 }
Chris Lattnerdc046542009-05-08 06:58:22 +00001498
John McCall31168b02011-06-15 23:02:42 +00001499 switch (ValType.getObjCLifetime()) {
1500 case Qualifiers::OCL_None:
1501 case Qualifiers::OCL_ExplicitNone:
1502 // okay
1503 break;
1504
1505 case Qualifiers::OCL_Weak:
1506 case Qualifiers::OCL_Strong:
1507 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00001508 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00001509 << ValType << FirstArg->getSourceRange();
1510 return ExprError();
1511 }
1512
John McCallb50451a2011-10-05 07:41:44 +00001513 // Strip any qualifiers off ValType.
1514 ValType = ValType.getUnqualifiedType();
1515
Chandler Carruth3973af72010-07-18 20:54:12 +00001516 // The majority of builtins return a value, but a few have special return
1517 // types, so allow them to override appropriately below.
1518 QualType ResultType = ValType;
1519
Chris Lattnerdc046542009-05-08 06:58:22 +00001520 // We need to figure out which concrete builtin this maps onto. For example,
1521 // __sync_fetch_and_add with a 2 byte object turns into
1522 // __sync_fetch_and_add_2.
1523#define BUILTIN_ROW(x) \
1524 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1525 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00001526
Chris Lattnerdc046542009-05-08 06:58:22 +00001527 static const unsigned BuiltinIndices[][5] = {
1528 BUILTIN_ROW(__sync_fetch_and_add),
1529 BUILTIN_ROW(__sync_fetch_and_sub),
1530 BUILTIN_ROW(__sync_fetch_and_or),
1531 BUILTIN_ROW(__sync_fetch_and_and),
1532 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00001533 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00001534
Chris Lattnerdc046542009-05-08 06:58:22 +00001535 BUILTIN_ROW(__sync_add_and_fetch),
1536 BUILTIN_ROW(__sync_sub_and_fetch),
1537 BUILTIN_ROW(__sync_and_and_fetch),
1538 BUILTIN_ROW(__sync_or_and_fetch),
1539 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00001540 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00001541
Chris Lattnerdc046542009-05-08 06:58:22 +00001542 BUILTIN_ROW(__sync_val_compare_and_swap),
1543 BUILTIN_ROW(__sync_bool_compare_and_swap),
1544 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00001545 BUILTIN_ROW(__sync_lock_release),
1546 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00001547 };
Mike Stump11289f42009-09-09 15:08:12 +00001548#undef BUILTIN_ROW
1549
Chris Lattnerdc046542009-05-08 06:58:22 +00001550 // Determine the index of the size.
1551 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00001552 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00001553 case 1: SizeIndex = 0; break;
1554 case 2: SizeIndex = 1; break;
1555 case 4: SizeIndex = 2; break;
1556 case 8: SizeIndex = 3; break;
1557 case 16: SizeIndex = 4; break;
1558 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001559 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1560 << FirstArg->getType() << FirstArg->getSourceRange();
1561 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00001562 }
Mike Stump11289f42009-09-09 15:08:12 +00001563
Chris Lattnerdc046542009-05-08 06:58:22 +00001564 // Each of these builtins has one pointer argument, followed by some number of
1565 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1566 // that we ignore. Find out which row of BuiltinIndices to read from as well
1567 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00001568 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00001569 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00001570 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00001571 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00001572 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00001573 case Builtin::BI__sync_fetch_and_add:
1574 case Builtin::BI__sync_fetch_and_add_1:
1575 case Builtin::BI__sync_fetch_and_add_2:
1576 case Builtin::BI__sync_fetch_and_add_4:
1577 case Builtin::BI__sync_fetch_and_add_8:
1578 case Builtin::BI__sync_fetch_and_add_16:
1579 BuiltinIndex = 0;
1580 break;
1581
1582 case Builtin::BI__sync_fetch_and_sub:
1583 case Builtin::BI__sync_fetch_and_sub_1:
1584 case Builtin::BI__sync_fetch_and_sub_2:
1585 case Builtin::BI__sync_fetch_and_sub_4:
1586 case Builtin::BI__sync_fetch_and_sub_8:
1587 case Builtin::BI__sync_fetch_and_sub_16:
1588 BuiltinIndex = 1;
1589 break;
1590
1591 case Builtin::BI__sync_fetch_and_or:
1592 case Builtin::BI__sync_fetch_and_or_1:
1593 case Builtin::BI__sync_fetch_and_or_2:
1594 case Builtin::BI__sync_fetch_and_or_4:
1595 case Builtin::BI__sync_fetch_and_or_8:
1596 case Builtin::BI__sync_fetch_and_or_16:
1597 BuiltinIndex = 2;
1598 break;
1599
1600 case Builtin::BI__sync_fetch_and_and:
1601 case Builtin::BI__sync_fetch_and_and_1:
1602 case Builtin::BI__sync_fetch_and_and_2:
1603 case Builtin::BI__sync_fetch_and_and_4:
1604 case Builtin::BI__sync_fetch_and_and_8:
1605 case Builtin::BI__sync_fetch_and_and_16:
1606 BuiltinIndex = 3;
1607 break;
Mike Stump11289f42009-09-09 15:08:12 +00001608
Douglas Gregor73722482011-11-28 16:30:08 +00001609 case Builtin::BI__sync_fetch_and_xor:
1610 case Builtin::BI__sync_fetch_and_xor_1:
1611 case Builtin::BI__sync_fetch_and_xor_2:
1612 case Builtin::BI__sync_fetch_and_xor_4:
1613 case Builtin::BI__sync_fetch_and_xor_8:
1614 case Builtin::BI__sync_fetch_and_xor_16:
1615 BuiltinIndex = 4;
1616 break;
1617
Hal Finkeld2208b52014-10-02 20:53:50 +00001618 case Builtin::BI__sync_fetch_and_nand:
1619 case Builtin::BI__sync_fetch_and_nand_1:
1620 case Builtin::BI__sync_fetch_and_nand_2:
1621 case Builtin::BI__sync_fetch_and_nand_4:
1622 case Builtin::BI__sync_fetch_and_nand_8:
1623 case Builtin::BI__sync_fetch_and_nand_16:
1624 BuiltinIndex = 5;
1625 WarnAboutSemanticsChange = true;
1626 break;
1627
Douglas Gregor73722482011-11-28 16:30:08 +00001628 case Builtin::BI__sync_add_and_fetch:
1629 case Builtin::BI__sync_add_and_fetch_1:
1630 case Builtin::BI__sync_add_and_fetch_2:
1631 case Builtin::BI__sync_add_and_fetch_4:
1632 case Builtin::BI__sync_add_and_fetch_8:
1633 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001634 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00001635 break;
1636
1637 case Builtin::BI__sync_sub_and_fetch:
1638 case Builtin::BI__sync_sub_and_fetch_1:
1639 case Builtin::BI__sync_sub_and_fetch_2:
1640 case Builtin::BI__sync_sub_and_fetch_4:
1641 case Builtin::BI__sync_sub_and_fetch_8:
1642 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001643 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00001644 break;
1645
1646 case Builtin::BI__sync_and_and_fetch:
1647 case Builtin::BI__sync_and_and_fetch_1:
1648 case Builtin::BI__sync_and_and_fetch_2:
1649 case Builtin::BI__sync_and_and_fetch_4:
1650 case Builtin::BI__sync_and_and_fetch_8:
1651 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001652 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00001653 break;
1654
1655 case Builtin::BI__sync_or_and_fetch:
1656 case Builtin::BI__sync_or_and_fetch_1:
1657 case Builtin::BI__sync_or_and_fetch_2:
1658 case Builtin::BI__sync_or_and_fetch_4:
1659 case Builtin::BI__sync_or_and_fetch_8:
1660 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001661 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00001662 break;
1663
1664 case Builtin::BI__sync_xor_and_fetch:
1665 case Builtin::BI__sync_xor_and_fetch_1:
1666 case Builtin::BI__sync_xor_and_fetch_2:
1667 case Builtin::BI__sync_xor_and_fetch_4:
1668 case Builtin::BI__sync_xor_and_fetch_8:
1669 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001670 BuiltinIndex = 10;
1671 break;
1672
1673 case Builtin::BI__sync_nand_and_fetch:
1674 case Builtin::BI__sync_nand_and_fetch_1:
1675 case Builtin::BI__sync_nand_and_fetch_2:
1676 case Builtin::BI__sync_nand_and_fetch_4:
1677 case Builtin::BI__sync_nand_and_fetch_8:
1678 case Builtin::BI__sync_nand_and_fetch_16:
1679 BuiltinIndex = 11;
1680 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00001681 break;
Mike Stump11289f42009-09-09 15:08:12 +00001682
Chris Lattnerdc046542009-05-08 06:58:22 +00001683 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001684 case Builtin::BI__sync_val_compare_and_swap_1:
1685 case Builtin::BI__sync_val_compare_and_swap_2:
1686 case Builtin::BI__sync_val_compare_and_swap_4:
1687 case Builtin::BI__sync_val_compare_and_swap_8:
1688 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001689 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00001690 NumFixed = 2;
1691 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001692
Chris Lattnerdc046542009-05-08 06:58:22 +00001693 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001694 case Builtin::BI__sync_bool_compare_and_swap_1:
1695 case Builtin::BI__sync_bool_compare_and_swap_2:
1696 case Builtin::BI__sync_bool_compare_and_swap_4:
1697 case Builtin::BI__sync_bool_compare_and_swap_8:
1698 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001699 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00001700 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00001701 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001702 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001703
1704 case Builtin::BI__sync_lock_test_and_set:
1705 case Builtin::BI__sync_lock_test_and_set_1:
1706 case Builtin::BI__sync_lock_test_and_set_2:
1707 case Builtin::BI__sync_lock_test_and_set_4:
1708 case Builtin::BI__sync_lock_test_and_set_8:
1709 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001710 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00001711 break;
1712
Chris Lattnerdc046542009-05-08 06:58:22 +00001713 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00001714 case Builtin::BI__sync_lock_release_1:
1715 case Builtin::BI__sync_lock_release_2:
1716 case Builtin::BI__sync_lock_release_4:
1717 case Builtin::BI__sync_lock_release_8:
1718 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001719 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00001720 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00001721 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001722 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001723
1724 case Builtin::BI__sync_swap:
1725 case Builtin::BI__sync_swap_1:
1726 case Builtin::BI__sync_swap_2:
1727 case Builtin::BI__sync_swap_4:
1728 case Builtin::BI__sync_swap_8:
1729 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001730 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00001731 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00001732 }
Mike Stump11289f42009-09-09 15:08:12 +00001733
Chris Lattnerdc046542009-05-08 06:58:22 +00001734 // Now that we know how many fixed arguments we expect, first check that we
1735 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001736 if (TheCall->getNumArgs() < 1+NumFixed) {
1737 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1738 << 0 << 1+NumFixed << TheCall->getNumArgs()
1739 << TheCall->getCallee()->getSourceRange();
1740 return ExprError();
1741 }
Mike Stump11289f42009-09-09 15:08:12 +00001742
Hal Finkeld2208b52014-10-02 20:53:50 +00001743 if (WarnAboutSemanticsChange) {
1744 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
1745 << TheCall->getCallee()->getSourceRange();
1746 }
1747
Chris Lattner5b9241b2009-05-08 15:36:58 +00001748 // Get the decl for the concrete builtin from this, we can tell what the
1749 // concrete integer type we should convert to is.
1750 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1751 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001752 FunctionDecl *NewBuiltinDecl;
1753 if (NewBuiltinID == BuiltinID)
1754 NewBuiltinDecl = FDecl;
1755 else {
1756 // Perform builtin lookup to avoid redeclaring it.
1757 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1758 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1759 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1760 assert(Res.getFoundDecl());
1761 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00001762 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001763 return ExprError();
1764 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001765
John McCallcf142162010-08-07 06:22:56 +00001766 // The first argument --- the pointer --- has a fixed type; we
1767 // deduce the types of the rest of the arguments accordingly. Walk
1768 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00001769 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00001770 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00001771
Chris Lattnerdc046542009-05-08 06:58:22 +00001772 // GCC does an implicit conversion to the pointer or integer ValType. This
1773 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00001774 // Initialize the argument.
1775 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1776 ValType, /*consume*/ false);
1777 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00001778 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001779 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001780
Chris Lattnerdc046542009-05-08 06:58:22 +00001781 // Okay, we have something that *can* be converted to the right type. Check
1782 // to see if there is a potentially weird extension going on here. This can
1783 // happen when you do an atomic operation on something like an char* and
1784 // pass in 42. The 42 gets converted to char. This is even more strange
1785 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00001786 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001787 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00001788 }
Mike Stump11289f42009-09-09 15:08:12 +00001789
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001790 ASTContext& Context = this->getASTContext();
1791
1792 // Create a new DeclRefExpr to refer to the new decl.
1793 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1794 Context,
1795 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001796 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001797 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00001798 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001799 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00001800 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001801 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00001802
Chris Lattnerdc046542009-05-08 06:58:22 +00001803 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00001804 // FIXME: This loses syntactic information.
1805 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1806 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1807 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001808 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00001809
Chandler Carruthbc8cab12010-07-18 07:23:17 +00001810 // Change the result type of the call to match the original value type. This
1811 // is arbitrary, but the codegen for these builtins ins design to handle it
1812 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00001813 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001814
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001815 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00001816}
1817
Chris Lattner6436fb62009-02-18 06:01:06 +00001818/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00001819/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00001820/// Note: It might also make sense to do the UTF-16 conversion here (would
1821/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00001822bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00001823 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00001824 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1825
Douglas Gregorfb65e592011-07-27 05:40:30 +00001826 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00001827 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1828 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00001829 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00001830 }
Mike Stump11289f42009-09-09 15:08:12 +00001831
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001832 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001833 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001834 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001835 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00001836 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001837 UTF16 *ToPtr = &ToBuf[0];
1838
1839 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1840 &ToPtr, ToPtr + NumBytes,
1841 strictConversion);
1842 // Check for conversion failure.
1843 if (Result != conversionOK)
1844 Diag(Arg->getLocStart(),
1845 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1846 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00001847 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001848}
1849
Chris Lattnere202e6a2007-12-20 00:05:45 +00001850/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1851/// Emit an error and return true on failure, return false on success.
Chris Lattner08464942007-12-28 05:29:59 +00001852bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1853 Expr *Fn = TheCall->getCallee();
1854 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00001855 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001856 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001857 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1858 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00001859 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001860 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00001861 return true;
1862 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00001863
1864 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00001865 return Diag(TheCall->getLocEnd(),
1866 diag::err_typecheck_call_too_few_args_at_least)
1867 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00001868 }
1869
John McCall29ad95b2011-08-27 01:09:30 +00001870 // Type-check the first argument normally.
1871 if (checkBuiltinArgument(*this, TheCall, 0))
1872 return true;
1873
Chris Lattnere202e6a2007-12-20 00:05:45 +00001874 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00001875 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00001876 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00001877 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00001878 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00001879 else if (FunctionDecl *FD = getCurFunctionDecl())
1880 isVariadic = FD->isVariadic();
1881 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001882 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00001883
Chris Lattnere202e6a2007-12-20 00:05:45 +00001884 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00001885 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1886 return true;
1887 }
Mike Stump11289f42009-09-09 15:08:12 +00001888
Chris Lattner43be2e62007-12-19 23:59:04 +00001889 // Verify that the second argument to the builtin is the last argument of the
1890 // current function or method.
1891 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00001892 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00001893
Nico Weber9eea7642013-05-24 23:31:57 +00001894 // These are valid if SecondArgIsLastNamedArgument is false after the next
1895 // block.
1896 QualType Type;
1897 SourceLocation ParamLoc;
1898
Anders Carlsson6a8350b2008-02-11 04:20:54 +00001899 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1900 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00001901 // FIXME: This isn't correct for methods (results in bogus warning).
1902 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00001903 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00001904 if (CurBlock)
1905 LastArg = *(CurBlock->TheDecl->param_end()-1);
1906 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00001907 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00001908 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001909 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00001910 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00001911
1912 Type = PV->getType();
1913 ParamLoc = PV->getLocation();
Chris Lattner43be2e62007-12-19 23:59:04 +00001914 }
1915 }
Mike Stump11289f42009-09-09 15:08:12 +00001916
Chris Lattner43be2e62007-12-19 23:59:04 +00001917 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001918 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +00001919 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weber9eea7642013-05-24 23:31:57 +00001920 else if (Type->isReferenceType()) {
1921 Diag(Arg->getLocStart(),
1922 diag::warn_va_start_of_reference_type_is_undefined);
1923 Diag(ParamLoc, diag::note_parameter_type) << Type;
1924 }
1925
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00001926 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00001927 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00001928}
Chris Lattner43be2e62007-12-19 23:59:04 +00001929
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00001930bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
1931 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
1932 // const char *named_addr);
1933
1934 Expr *Func = Call->getCallee();
1935
1936 if (Call->getNumArgs() < 3)
1937 return Diag(Call->getLocEnd(),
1938 diag::err_typecheck_call_too_few_args_at_least)
1939 << 0 /*function call*/ << 3 << Call->getNumArgs();
1940
1941 // Determine whether the current function is variadic or not.
1942 bool IsVariadic;
1943 if (BlockScopeInfo *CurBlock = getCurBlock())
1944 IsVariadic = CurBlock->TheDecl->isVariadic();
1945 else if (FunctionDecl *FD = getCurFunctionDecl())
1946 IsVariadic = FD->isVariadic();
1947 else if (ObjCMethodDecl *MD = getCurMethodDecl())
1948 IsVariadic = MD->isVariadic();
1949 else
1950 llvm_unreachable("unexpected statement type");
1951
1952 if (!IsVariadic) {
1953 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1954 return true;
1955 }
1956
1957 // Type-check the first argument normally.
1958 if (checkBuiltinArgument(*this, Call, 0))
1959 return true;
1960
1961 static const struct {
1962 unsigned ArgNo;
1963 QualType Type;
1964 } ArgumentTypes[] = {
1965 { 1, Context.getPointerType(Context.CharTy.withConst()) },
1966 { 2, Context.getSizeType() },
1967 };
1968
1969 for (const auto &AT : ArgumentTypes) {
1970 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
1971 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
1972 continue;
1973 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
1974 << Arg->getType() << AT.Type << 1 /* different class */
1975 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
1976 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
1977 }
1978
1979 return false;
1980}
1981
Chris Lattner2da14fb2007-12-20 00:26:33 +00001982/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1983/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00001984bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1985 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00001986 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00001987 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00001988 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00001989 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001990 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001991 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00001992 << SourceRange(TheCall->getArg(2)->getLocStart(),
1993 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00001994
John Wiegley01296292011-04-08 18:41:53 +00001995 ExprResult OrigArg0 = TheCall->getArg(0);
1996 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00001997
Chris Lattner2da14fb2007-12-20 00:26:33 +00001998 // Do standard promotions between the two arguments, returning their common
1999 // type.
Chris Lattner08464942007-12-28 05:29:59 +00002000 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00002001 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
2002 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00002003
2004 // Make sure any conversions are pushed back into the call; this is
2005 // type safe since unordered compare builtins are declared as "_Bool
2006 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00002007 TheCall->setArg(0, OrigArg0.get());
2008 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00002009
John Wiegley01296292011-04-08 18:41:53 +00002010 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00002011 return false;
2012
Chris Lattner2da14fb2007-12-20 00:26:33 +00002013 // If the common type isn't a real floating type, then the arguments were
2014 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00002015 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00002016 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002017 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00002018 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
2019 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002020
Chris Lattner2da14fb2007-12-20 00:26:33 +00002021 return false;
2022}
2023
Benjamin Kramer634fc102010-02-15 22:42:31 +00002024/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
2025/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00002026/// to check everything. We expect the last argument to be a floating point
2027/// value.
2028bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
2029 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00002030 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002031 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00002032 if (TheCall->getNumArgs() > NumArgs)
2033 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002034 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002035 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00002036 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002037 (*(TheCall->arg_end()-1))->getLocEnd());
2038
Benjamin Kramer64aae502010-02-16 10:07:31 +00002039 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00002040
Eli Friedman7e4faac2009-08-31 20:06:00 +00002041 if (OrigArg->isTypeDependent())
2042 return false;
2043
Chris Lattner68784ef2010-05-06 05:50:07 +00002044 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00002045 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00002046 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002047 diag::err_typecheck_call_invalid_unary_fp)
2048 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002049
Chris Lattner68784ef2010-05-06 05:50:07 +00002050 // If this is an implicit conversion from float -> double, remove it.
2051 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
2052 Expr *CastArg = Cast->getSubExpr();
2053 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
2054 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
2055 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00002056 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00002057 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00002058 }
2059 }
2060
Eli Friedman7e4faac2009-08-31 20:06:00 +00002061 return false;
2062}
2063
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002064/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
2065// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00002066ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00002067 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002068 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00002069 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00002070 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2071 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002072
Nate Begemana0110022010-06-08 00:16:34 +00002073 // Determine which of the following types of shufflevector we're checking:
2074 // 1) unary, vector mask: (lhs, mask)
2075 // 2) binary, vector mask: (lhs, rhs, mask)
2076 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
2077 QualType resType = TheCall->getArg(0)->getType();
2078 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00002079
Douglas Gregorc25f7662009-05-19 22:10:17 +00002080 if (!TheCall->getArg(0)->isTypeDependent() &&
2081 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00002082 QualType LHSType = TheCall->getArg(0)->getType();
2083 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00002084
Craig Topperbaca3892013-07-29 06:47:04 +00002085 if (!LHSType->isVectorType() || !RHSType->isVectorType())
2086 return ExprError(Diag(TheCall->getLocStart(),
2087 diag::err_shufflevector_non_vector)
2088 << SourceRange(TheCall->getArg(0)->getLocStart(),
2089 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002090
Nate Begemana0110022010-06-08 00:16:34 +00002091 numElements = LHSType->getAs<VectorType>()->getNumElements();
2092 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00002093
Nate Begemana0110022010-06-08 00:16:34 +00002094 // Check to see if we have a call with 2 vector arguments, the unary shuffle
2095 // with mask. If so, verify that RHS is an integer vector type with the
2096 // same number of elts as lhs.
2097 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00002098 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00002099 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00002100 return ExprError(Diag(TheCall->getLocStart(),
2101 diag::err_shufflevector_incompatible_vector)
2102 << SourceRange(TheCall->getArg(1)->getLocStart(),
2103 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002104 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00002105 return ExprError(Diag(TheCall->getLocStart(),
2106 diag::err_shufflevector_incompatible_vector)
2107 << SourceRange(TheCall->getArg(0)->getLocStart(),
2108 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00002109 } else if (numElements != numResElements) {
2110 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00002111 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002112 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002113 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002114 }
2115
2116 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00002117 if (TheCall->getArg(i)->isTypeDependent() ||
2118 TheCall->getArg(i)->isValueDependent())
2119 continue;
2120
Nate Begemana0110022010-06-08 00:16:34 +00002121 llvm::APSInt Result(32);
2122 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
2123 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002124 diag::err_shufflevector_nonconstant_argument)
2125 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002126
Craig Topper50ad5b72013-08-03 17:40:38 +00002127 // Allow -1 which will be translated to undef in the IR.
2128 if (Result.isSigned() && Result.isAllOnesValue())
2129 continue;
2130
Chris Lattner7ab824e2008-08-10 02:05:13 +00002131 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002132 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002133 diag::err_shufflevector_argument_too_large)
2134 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002135 }
2136
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002137 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002138
Chris Lattner7ab824e2008-08-10 02:05:13 +00002139 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002140 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00002141 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002142 }
2143
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002144 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
2145 TheCall->getCallee()->getLocStart(),
2146 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002147}
Chris Lattner43be2e62007-12-19 23:59:04 +00002148
Hal Finkelc4d7c822013-09-18 03:29:45 +00002149/// SemaConvertVectorExpr - Handle __builtin_convertvector
2150ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
2151 SourceLocation BuiltinLoc,
2152 SourceLocation RParenLoc) {
2153 ExprValueKind VK = VK_RValue;
2154 ExprObjectKind OK = OK_Ordinary;
2155 QualType DstTy = TInfo->getType();
2156 QualType SrcTy = E->getType();
2157
2158 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
2159 return ExprError(Diag(BuiltinLoc,
2160 diag::err_convertvector_non_vector)
2161 << E->getSourceRange());
2162 if (!DstTy->isVectorType() && !DstTy->isDependentType())
2163 return ExprError(Diag(BuiltinLoc,
2164 diag::err_convertvector_non_vector_type));
2165
2166 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
2167 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
2168 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
2169 if (SrcElts != DstElts)
2170 return ExprError(Diag(BuiltinLoc,
2171 diag::err_convertvector_incompatible_vector)
2172 << E->getSourceRange());
2173 }
2174
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002175 return new (Context)
2176 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00002177}
2178
Daniel Dunbarb7257262008-07-21 22:59:13 +00002179/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
2180// This is declared to take (const void*, ...) and can take two
2181// optional constant int args.
2182bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00002183 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002184
Chris Lattner3b054132008-11-19 05:08:23 +00002185 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002186 return Diag(TheCall->getLocEnd(),
2187 diag::err_typecheck_call_too_many_args_at_most)
2188 << 0 /*function call*/ << 3 << NumArgs
2189 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002190
2191 // Argument 0 is checked for us and the remaining arguments must be
2192 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00002193 for (unsigned i = 1; i != NumArgs; ++i)
2194 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002195 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002196
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002197 return false;
2198}
2199
Hal Finkelf0417332014-07-17 14:25:55 +00002200/// SemaBuiltinAssume - Handle __assume (MS Extension).
2201// __assume does not evaluate its arguments, and should warn if its argument
2202// has side effects.
2203bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
2204 Expr *Arg = TheCall->getArg(0);
2205 if (Arg->isInstantiationDependent()) return false;
2206
2207 if (Arg->HasSideEffects(Context))
2208 return Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00002209 << Arg->getSourceRange()
2210 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
2211
2212 return false;
2213}
2214
2215/// Handle __builtin_assume_aligned. This is declared
2216/// as (const void*, size_t, ...) and can take one optional constant int arg.
2217bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
2218 unsigned NumArgs = TheCall->getNumArgs();
2219
2220 if (NumArgs > 3)
2221 return Diag(TheCall->getLocEnd(),
2222 diag::err_typecheck_call_too_many_args_at_most)
2223 << 0 /*function call*/ << 3 << NumArgs
2224 << TheCall->getSourceRange();
2225
2226 // The alignment must be a constant integer.
2227 Expr *Arg = TheCall->getArg(1);
2228
2229 // We can't check the value of a dependent argument.
2230 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
2231 llvm::APSInt Result;
2232 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2233 return true;
2234
2235 if (!Result.isPowerOf2())
2236 return Diag(TheCall->getLocStart(),
2237 diag::err_alignment_not_power_of_two)
2238 << Arg->getSourceRange();
2239 }
2240
2241 if (NumArgs > 2) {
2242 ExprResult Arg(TheCall->getArg(2));
2243 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2244 Context.getSizeType(), false);
2245 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2246 if (Arg.isInvalid()) return true;
2247 TheCall->setArg(2, Arg.get());
2248 }
Hal Finkelf0417332014-07-17 14:25:55 +00002249
2250 return false;
2251}
2252
Eric Christopher8d0c6212010-04-17 02:26:23 +00002253/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2254/// TheCall is a constant expression.
2255bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
2256 llvm::APSInt &Result) {
2257 Expr *Arg = TheCall->getArg(ArgNum);
2258 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2259 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2260
2261 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
2262
2263 if (!Arg->isIntegerConstantExpr(Result, Context))
2264 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00002265 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00002266
Chris Lattnerd545ad12009-09-23 06:06:36 +00002267 return false;
2268}
2269
Richard Sandiford28940af2014-04-16 08:47:51 +00002270/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
2271/// TheCall is a constant expression in the range [Low, High].
2272bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
2273 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00002274 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002275
2276 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00002277 Expr *Arg = TheCall->getArg(ArgNum);
2278 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002279 return false;
2280
Eric Christopher8d0c6212010-04-17 02:26:23 +00002281 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00002282 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002283 return true;
2284
Richard Sandiford28940af2014-04-16 08:47:51 +00002285 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00002286 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00002287 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00002288
2289 return false;
2290}
2291
Eli Friedmanc97d0142009-05-03 06:04:26 +00002292/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002293/// This checks that val is a constant 1.
2294bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
2295 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00002296 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00002297
Eric Christopher8d0c6212010-04-17 02:26:23 +00002298 // TODO: This is less than ideal. Overload this to take a value.
2299 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2300 return true;
2301
2302 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002303 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
2304 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
2305
2306 return false;
2307}
2308
Richard Smithd7293d72013-08-05 18:49:43 +00002309namespace {
2310enum StringLiteralCheckType {
2311 SLCT_NotALiteral,
2312 SLCT_UncheckedLiteral,
2313 SLCT_CheckedLiteral
2314};
2315}
2316
Richard Smith55ce3522012-06-25 20:30:08 +00002317// Determine if an expression is a string literal or constant string.
2318// If this function returns false on the arguments to a function expecting a
2319// format string, we will usually need to emit a warning.
2320// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00002321static StringLiteralCheckType
2322checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
2323 bool HasVAListArg, unsigned format_idx,
2324 unsigned firstDataArg, Sema::FormatStringType Type,
2325 Sema::VariadicCallType CallType, bool InFunctionCall,
2326 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek808829352010-09-09 03:51:39 +00002327 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00002328 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00002329 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002330
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002331 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00002332
Richard Smithd7293d72013-08-05 18:49:43 +00002333 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00002334 // Technically -Wformat-nonliteral does not warn about this case.
2335 // The behavior of printf and friends in this case is implementation
2336 // dependent. Ideally if the format string cannot be null then
2337 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00002338 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00002339
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002340 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00002341 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002342 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00002343 // The expression is a literal if both sub-expressions were, and it was
2344 // completely checked only if both sub-expressions were checked.
2345 const AbstractConditionalOperator *C =
2346 cast<AbstractConditionalOperator>(E);
2347 StringLiteralCheckType Left =
Richard Smithd7293d72013-08-05 18:49:43 +00002348 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002349 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002350 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002351 if (Left == SLCT_NotALiteral)
2352 return SLCT_NotALiteral;
2353 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00002354 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002355 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002356 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002357 return Left < Right ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002358 }
2359
2360 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00002361 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2362 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002363 }
2364
John McCallc07a0c72011-02-17 10:25:35 +00002365 case Stmt::OpaqueValueExprClass:
2366 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2367 E = src;
2368 goto tryAgain;
2369 }
Richard Smith55ce3522012-06-25 20:30:08 +00002370 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00002371
Ted Kremeneka8890832011-02-24 23:03:04 +00002372 case Stmt::PredefinedExprClass:
2373 // While __func__, etc., are technically not string literals, they
2374 // cannot contain format specifiers and thus are not a security
2375 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00002376 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00002377
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002378 case Stmt::DeclRefExprClass: {
2379 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002380
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002381 // As an exception, do not flag errors for variables binding to
2382 // const string literals.
2383 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2384 bool isConstant = false;
2385 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002386
Richard Smithd7293d72013-08-05 18:49:43 +00002387 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2388 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00002389 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00002390 isConstant = T.isConstant(S.Context) &&
2391 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00002392 } else if (T->isObjCObjectPointerType()) {
2393 // In ObjC, there is usually no "const ObjectPointer" type,
2394 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00002395 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002396 }
Mike Stump11289f42009-09-09 15:08:12 +00002397
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002398 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002399 if (const Expr *Init = VD->getAnyInitializer()) {
2400 // Look through initializers like const char c[] = { "foo" }
2401 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2402 if (InitList->isStringLiteralInit())
2403 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2404 }
Richard Smithd7293d72013-08-05 18:49:43 +00002405 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002406 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002407 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002408 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002409 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002410 }
Mike Stump11289f42009-09-09 15:08:12 +00002411
Anders Carlssonb012ca92009-06-28 19:55:58 +00002412 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2413 // special check to see if the format string is a function parameter
2414 // of the function calling the printf function. If the function
2415 // has an attribute indicating it is a printf-like function, then we
2416 // should suppress warnings concerning non-literals being used in a call
2417 // to a vprintf function. For example:
2418 //
2419 // void
2420 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2421 // va_list ap;
2422 // va_start(ap, fmt);
2423 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2424 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00002425 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002426 if (HasVAListArg) {
2427 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2428 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2429 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002430 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002431 // adjust for implicit parameter
2432 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2433 if (MD->isInstance())
2434 ++PVIndex;
2435 // We also check if the formats are compatible.
2436 // We can't pass a 'scanf' string to a 'printf' function.
2437 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00002438 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00002439 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002440 }
2441 }
2442 }
2443 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002444 }
Mike Stump11289f42009-09-09 15:08:12 +00002445
Richard Smith55ce3522012-06-25 20:30:08 +00002446 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002447 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002448
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002449 case Stmt::CallExprClass:
2450 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002451 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002452 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2453 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2454 unsigned ArgIndex = FA->getFormatIdx();
2455 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2456 if (MD->isInstance())
2457 --ArgIndex;
2458 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00002459
Richard Smithd7293d72013-08-05 18:49:43 +00002460 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002461 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002462 Type, CallType, InFunctionCall,
2463 CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002464 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2465 unsigned BuiltinID = FD->getBuiltinID();
2466 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2467 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2468 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00002469 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002470 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002471 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002472 InFunctionCall, CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002473 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002474 }
2475 }
Mike Stump11289f42009-09-09 15:08:12 +00002476
Richard Smith55ce3522012-06-25 20:30:08 +00002477 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002478 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002479 case Stmt::ObjCStringLiteralClass:
2480 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00002481 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002482
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002483 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002484 StrE = ObjCFExpr->getString();
2485 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002486 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002487
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002488 if (StrE) {
Richard Smithd7293d72013-08-05 18:49:43 +00002489 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2490 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002491 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002492 }
Mike Stump11289f42009-09-09 15:08:12 +00002493
Richard Smith55ce3522012-06-25 20:30:08 +00002494 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002495 }
Mike Stump11289f42009-09-09 15:08:12 +00002496
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002497 default:
Richard Smith55ce3522012-06-25 20:30:08 +00002498 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002499 }
2500}
2501
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002502Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00002503 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002504 .Case("scanf", FST_Scanf)
2505 .Cases("printf", "printf0", FST_Printf)
2506 .Cases("NSString", "CFString", FST_NSString)
2507 .Case("strftime", FST_Strftime)
2508 .Case("strfmon", FST_Strfmon)
2509 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
2510 .Default(FST_Unknown);
2511}
2512
Jordan Rose3e0ec582012-07-19 18:10:23 +00002513/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00002514/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002515/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002516bool Sema::CheckFormatArguments(const FormatAttr *Format,
2517 ArrayRef<const Expr *> Args,
2518 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002519 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002520 SourceLocation Loc, SourceRange Range,
2521 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00002522 FormatStringInfo FSI;
2523 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002524 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00002525 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00002526 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002527 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002528}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00002529
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002530bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002531 bool HasVAListArg, unsigned format_idx,
2532 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002533 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002534 SourceLocation Loc, SourceRange Range,
2535 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00002536 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002537 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002538 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00002539 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002540 }
Mike Stump11289f42009-09-09 15:08:12 +00002541
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002542 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002543
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002544 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00002545 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002546 // Dynamically generated format strings are difficult to
2547 // automatically vet at compile time. Requiring that format strings
2548 // are string literals: (1) permits the checking of format strings by
2549 // the compiler and thereby (2) can practically remove the source of
2550 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00002551
Mike Stump11289f42009-09-09 15:08:12 +00002552 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00002553 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00002554 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00002555 // the same format string checking logic for both ObjC and C strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002556 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00002557 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2558 format_idx, firstDataArg, Type, CallType,
2559 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002560 if (CT != SLCT_NotALiteral)
2561 // Literal format string found, check done!
2562 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00002563
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002564 // Strftime is particular as it always uses a single 'time' argument,
2565 // so it is safe to pass a non-literal string.
2566 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00002567 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002568
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002569 // Do not emit diag when the string param is a macro expansion and the
2570 // format is either NSString or CFString. This is a hack to prevent
2571 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2572 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupas2b7da832012-05-04 21:08:08 +00002573 if (Type == FST_NSString &&
2574 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith55ce3522012-06-25 20:30:08 +00002575 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002576
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002577 // If there are no arguments specified, warn with -Wformat-security, otherwise
2578 // warn only with -Wformat-nonliteral.
Eli Friedman0e5d6772013-06-18 18:10:01 +00002579 if (Args.size() == firstDataArg)
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002580 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002581 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002582 << OrigFormatExpr->getSourceRange();
2583 else
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002584 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002585 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002586 << OrigFormatExpr->getSourceRange();
Richard Smith55ce3522012-06-25 20:30:08 +00002587 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002588}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002589
Ted Kremenekab278de2010-01-28 23:39:18 +00002590namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00002591class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2592protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00002593 Sema &S;
2594 const StringLiteral *FExpr;
2595 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002596 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00002597 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00002598 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00002599 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002600 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00002601 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00002602 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00002603 bool usesPositionalArgs;
2604 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00002605 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00002606 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00002607 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002608public:
Ted Kremenek02087932010-07-16 02:11:22 +00002609 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002610 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002611 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002612 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002613 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002614 Sema::VariadicCallType callType,
2615 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremenekab278de2010-01-28 23:39:18 +00002616 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002617 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2618 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002619 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00002620 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00002621 inFunctionCall(inFunctionCall), CallType(callType),
2622 CheckedVarArgs(CheckedVarArgs) {
2623 CoveredArgs.resize(numDataArgs);
2624 CoveredArgs.reset();
2625 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002626
Ted Kremenek019d2242010-01-29 01:50:07 +00002627 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002628
Ted Kremenek02087932010-07-16 02:11:22 +00002629 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002630 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002631
Jordan Rose92303592012-09-08 04:00:03 +00002632 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002633 const analyze_format_string::FormatSpecifier &FS,
2634 const analyze_format_string::ConversionSpecifier &CS,
2635 const char *startSpecifier, unsigned specifierLen,
2636 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00002637
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002638 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002639 const analyze_format_string::FormatSpecifier &FS,
2640 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002641
2642 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002643 const analyze_format_string::ConversionSpecifier &CS,
2644 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002645
Craig Toppere14c0f82014-03-12 04:55:44 +00002646 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002647
Craig Toppere14c0f82014-03-12 04:55:44 +00002648 void HandleInvalidPosition(const char *startSpecifier,
2649 unsigned specifierLen,
2650 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002651
Craig Toppere14c0f82014-03-12 04:55:44 +00002652 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002653
Craig Toppere14c0f82014-03-12 04:55:44 +00002654 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002655
Richard Trieu03cf7b72011-10-28 00:41:25 +00002656 template <typename Range>
2657 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2658 const Expr *ArgumentExpr,
2659 PartialDiagnostic PDiag,
2660 SourceLocation StringLoc,
2661 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002662 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002663
Ted Kremenek02087932010-07-16 02:11:22 +00002664protected:
Ted Kremenekce815422010-07-19 21:25:57 +00002665 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2666 const char *startSpec,
2667 unsigned specifierLen,
2668 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002669
2670 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2671 const char *startSpec,
2672 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00002673
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002674 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00002675 CharSourceRange getSpecifierRange(const char *startSpecifier,
2676 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00002677 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002678
Ted Kremenek5739de72010-01-29 01:06:55 +00002679 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002680
2681 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2682 const analyze_format_string::ConversionSpecifier &CS,
2683 const char *startSpecifier, unsigned specifierLen,
2684 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002685
2686 template <typename Range>
2687 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2688 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002689 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00002690};
2691}
2692
Ted Kremenek02087932010-07-16 02:11:22 +00002693SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00002694 return OrigFormatExpr->getSourceRange();
2695}
2696
Ted Kremenek02087932010-07-16 02:11:22 +00002697CharSourceRange CheckFormatHandler::
2698getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00002699 SourceLocation Start = getLocationOfByte(startSpecifier);
2700 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2701
2702 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002703 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00002704
2705 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002706}
2707
Ted Kremenek02087932010-07-16 02:11:22 +00002708SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002709 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00002710}
2711
Ted Kremenek02087932010-07-16 02:11:22 +00002712void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2713 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00002714 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2715 getLocationOfByte(startSpecifier),
2716 /*IsStringLocation*/true,
2717 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00002718}
2719
Jordan Rose92303592012-09-08 04:00:03 +00002720void CheckFormatHandler::HandleInvalidLengthModifier(
2721 const analyze_format_string::FormatSpecifier &FS,
2722 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00002723 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00002724 using namespace analyze_format_string;
2725
2726 const LengthModifier &LM = FS.getLengthModifier();
2727 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2728
2729 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002730 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00002731 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002732 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002733 getLocationOfByte(LM.getStart()),
2734 /*IsStringLocation*/true,
2735 getSpecifierRange(startSpecifier, specifierLen));
2736
2737 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2738 << FixedLM->toString()
2739 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2740
2741 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002742 FixItHint Hint;
2743 if (DiagID == diag::warn_format_nonsensical_length)
2744 Hint = FixItHint::CreateRemoval(LMRange);
2745
2746 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002747 getLocationOfByte(LM.getStart()),
2748 /*IsStringLocation*/true,
2749 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00002750 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00002751 }
2752}
2753
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002754void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00002755 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002756 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002757 using namespace analyze_format_string;
2758
2759 const LengthModifier &LM = FS.getLengthModifier();
2760 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2761
2762 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002763 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00002764 if (FixedLM) {
2765 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2766 << LM.toString() << 0,
2767 getLocationOfByte(LM.getStart()),
2768 /*IsStringLocation*/true,
2769 getSpecifierRange(startSpecifier, specifierLen));
2770
2771 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2772 << FixedLM->toString()
2773 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2774
2775 } else {
2776 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2777 << LM.toString() << 0,
2778 getLocationOfByte(LM.getStart()),
2779 /*IsStringLocation*/true,
2780 getSpecifierRange(startSpecifier, specifierLen));
2781 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002782}
2783
2784void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2785 const analyze_format_string::ConversionSpecifier &CS,
2786 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00002787 using namespace analyze_format_string;
2788
2789 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00002790 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00002791 if (FixedCS) {
2792 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2793 << CS.toString() << /*conversion specifier*/1,
2794 getLocationOfByte(CS.getStart()),
2795 /*IsStringLocation*/true,
2796 getSpecifierRange(startSpecifier, specifierLen));
2797
2798 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2799 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2800 << FixedCS->toString()
2801 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2802 } else {
2803 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2804 << CS.toString() << /*conversion specifier*/1,
2805 getLocationOfByte(CS.getStart()),
2806 /*IsStringLocation*/true,
2807 getSpecifierRange(startSpecifier, specifierLen));
2808 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002809}
2810
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002811void CheckFormatHandler::HandlePosition(const char *startPos,
2812 unsigned posLen) {
2813 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2814 getLocationOfByte(startPos),
2815 /*IsStringLocation*/true,
2816 getSpecifierRange(startPos, posLen));
2817}
2818
Ted Kremenekd1668192010-02-27 01:41:03 +00002819void
Ted Kremenek02087932010-07-16 02:11:22 +00002820CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2821 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002822 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2823 << (unsigned) p,
2824 getLocationOfByte(startPos), /*IsStringLocation*/true,
2825 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00002826}
2827
Ted Kremenek02087932010-07-16 02:11:22 +00002828void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00002829 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002830 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2831 getLocationOfByte(startPos),
2832 /*IsStringLocation*/true,
2833 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00002834}
2835
Ted Kremenek02087932010-07-16 02:11:22 +00002836void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002837 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00002838 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002839 EmitFormatDiagnostic(
2840 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2841 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2842 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00002843 }
Ted Kremenek02087932010-07-16 02:11:22 +00002844}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002845
Jordan Rose58bbe422012-07-19 18:10:08 +00002846// Note that this may return NULL if there was an error parsing or building
2847// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00002848const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002849 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00002850}
2851
2852void CheckFormatHandler::DoneProcessing() {
2853 // Does the number of data arguments exceed the number of
2854 // format conversions in the format string?
2855 if (!HasVAListArg) {
2856 // Find any arguments that weren't covered.
2857 CoveredArgs.flip();
2858 signed notCoveredArg = CoveredArgs.find_first();
2859 if (notCoveredArg >= 0) {
2860 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose58bbe422012-07-19 18:10:08 +00002861 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2862 SourceLocation Loc = E->getLocStart();
2863 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2864 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2865 Loc, /*IsStringLocation*/false,
2866 getFormatStringRange());
2867 }
Bob Wilson23cd4342012-05-03 19:47:19 +00002868 }
Ted Kremenek02087932010-07-16 02:11:22 +00002869 }
2870 }
2871}
2872
Ted Kremenekce815422010-07-19 21:25:57 +00002873bool
2874CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2875 SourceLocation Loc,
2876 const char *startSpec,
2877 unsigned specifierLen,
2878 const char *csStart,
2879 unsigned csLen) {
2880
2881 bool keepGoing = true;
2882 if (argIndex < NumDataArgs) {
2883 // Consider the argument coverered, even though the specifier doesn't
2884 // make sense.
2885 CoveredArgs.set(argIndex);
2886 }
2887 else {
2888 // If argIndex exceeds the number of data arguments we
2889 // don't issue a warning because that is just a cascade of warnings (and
2890 // they may have intended '%%' anyway). We don't want to continue processing
2891 // the format string after this point, however, as we will like just get
2892 // gibberish when trying to match arguments.
2893 keepGoing = false;
2894 }
2895
Richard Trieu03cf7b72011-10-28 00:41:25 +00002896 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2897 << StringRef(csStart, csLen),
2898 Loc, /*IsStringLocation*/true,
2899 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekce815422010-07-19 21:25:57 +00002900
2901 return keepGoing;
2902}
2903
Richard Trieu03cf7b72011-10-28 00:41:25 +00002904void
2905CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2906 const char *startSpec,
2907 unsigned specifierLen) {
2908 EmitFormatDiagnostic(
2909 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2910 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2911}
2912
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002913bool
2914CheckFormatHandler::CheckNumArgs(
2915 const analyze_format_string::FormatSpecifier &FS,
2916 const analyze_format_string::ConversionSpecifier &CS,
2917 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2918
2919 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002920 PartialDiagnostic PDiag = FS.usesPositionalArg()
2921 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2922 << (argIndex+1) << NumDataArgs)
2923 : S.PDiag(diag::warn_printf_insufficient_data_args);
2924 EmitFormatDiagnostic(
2925 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2926 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002927 return false;
2928 }
2929 return true;
2930}
2931
Richard Trieu03cf7b72011-10-28 00:41:25 +00002932template<typename Range>
2933void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2934 SourceLocation Loc,
2935 bool IsStringLocation,
2936 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00002937 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002938 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00002939 Loc, IsStringLocation, StringRange, FixIt);
2940}
2941
2942/// \brief If the format string is not within the funcion call, emit a note
2943/// so that the function call and string are in diagnostic messages.
2944///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002945/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00002946/// call and only one diagnostic message will be produced. Otherwise, an
2947/// extra note will be emitted pointing to location of the format string.
2948///
2949/// \param ArgumentExpr the expression that is passed as the format string
2950/// argument in the function call. Used for getting locations when two
2951/// diagnostics are emitted.
2952///
2953/// \param PDiag the callee should already have provided any strings for the
2954/// diagnostic message. This function only adds locations and fixits
2955/// to diagnostics.
2956///
2957/// \param Loc primary location for diagnostic. If two diagnostics are
2958/// required, one will be at Loc and a new SourceLocation will be created for
2959/// the other one.
2960///
2961/// \param IsStringLocation if true, Loc points to the format string should be
2962/// used for the note. Otherwise, Loc points to the argument list and will
2963/// be used with PDiag.
2964///
2965/// \param StringRange some or all of the string to highlight. This is
2966/// templated so it can accept either a CharSourceRange or a SourceRange.
2967///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002968/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002969template<typename Range>
2970void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2971 const Expr *ArgumentExpr,
2972 PartialDiagnostic PDiag,
2973 SourceLocation Loc,
2974 bool IsStringLocation,
2975 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00002976 ArrayRef<FixItHint> FixIt) {
2977 if (InFunctionCall) {
2978 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2979 D << StringRange;
2980 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2981 I != E; ++I) {
2982 D << *I;
2983 }
2984 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002985 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2986 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00002987
2988 const Sema::SemaDiagnosticBuilder &Note =
2989 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2990 diag::note_format_string_defined);
2991
2992 Note << StringRange;
2993 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2994 I != E; ++I) {
2995 Note << *I;
2996 }
Richard Trieu03cf7b72011-10-28 00:41:25 +00002997 }
2998}
2999
Ted Kremenek02087932010-07-16 02:11:22 +00003000//===--- CHECK: Printf format string checking ------------------------------===//
3001
3002namespace {
3003class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003004 bool ObjCContext;
Ted Kremenek02087932010-07-16 02:11:22 +00003005public:
3006 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
3007 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003008 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00003009 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003010 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003011 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003012 Sema::VariadicCallType CallType,
3013 llvm::SmallBitVector &CheckedVarArgs)
3014 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3015 numDataArgs, beg, hasVAListArg, Args,
3016 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
3017 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003018 {}
3019
Craig Toppere14c0f82014-03-12 04:55:44 +00003020
Ted Kremenek02087932010-07-16 02:11:22 +00003021 bool HandleInvalidPrintfConversionSpecifier(
3022 const analyze_printf::PrintfSpecifier &FS,
3023 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003024 unsigned specifierLen) override;
3025
Ted Kremenek02087932010-07-16 02:11:22 +00003026 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
3027 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003028 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00003029 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3030 const char *StartSpecifier,
3031 unsigned SpecifierLen,
3032 const Expr *E);
3033
Ted Kremenek02087932010-07-16 02:11:22 +00003034 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
3035 const char *startSpecifier, unsigned specifierLen);
3036 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
3037 const analyze_printf::OptionalAmount &Amt,
3038 unsigned type,
3039 const char *startSpecifier, unsigned specifierLen);
3040 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
3041 const analyze_printf::OptionalFlag &flag,
3042 const char *startSpecifier, unsigned specifierLen);
3043 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
3044 const analyze_printf::OptionalFlag &ignoredFlag,
3045 const analyze_printf::OptionalFlag &flag,
3046 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003047 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00003048 const Expr *E);
Richard Smith55ce3522012-06-25 20:30:08 +00003049
Ted Kremenek02087932010-07-16 02:11:22 +00003050};
3051}
3052
3053bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
3054 const analyze_printf::PrintfSpecifier &FS,
3055 const char *startSpecifier,
3056 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003057 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003058 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003059
Ted Kremenekce815422010-07-19 21:25:57 +00003060 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3061 getLocationOfByte(CS.getStart()),
3062 startSpecifier, specifierLen,
3063 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00003064}
3065
Ted Kremenek02087932010-07-16 02:11:22 +00003066bool CheckPrintfHandler::HandleAmount(
3067 const analyze_format_string::OptionalAmount &Amt,
3068 unsigned k, const char *startSpecifier,
3069 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003070
3071 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003072 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00003073 unsigned argIndex = Amt.getArgIndex();
3074 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003075 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
3076 << k,
3077 getLocationOfByte(Amt.getStart()),
3078 /*IsStringLocation*/true,
3079 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00003080 // Don't do any more checking. We will just emit
3081 // spurious errors.
3082 return false;
3083 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003084
Ted Kremenek5739de72010-01-29 01:06:55 +00003085 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00003086 // Although not in conformance with C99, we also allow the argument to be
3087 // an 'unsigned int' as that is a reasonably safe case. GCC also
3088 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00003089 CoveredArgs.set(argIndex);
3090 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00003091 if (!Arg)
3092 return false;
3093
Ted Kremenek5739de72010-01-29 01:06:55 +00003094 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003095
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003096 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
3097 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003098
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003099 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003100 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003101 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00003102 << T << Arg->getSourceRange(),
3103 getLocationOfByte(Amt.getStart()),
3104 /*IsStringLocation*/true,
3105 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00003106 // Don't do any more checking. We will just emit
3107 // spurious errors.
3108 return false;
3109 }
3110 }
3111 }
3112 return true;
3113}
Ted Kremenek5739de72010-01-29 01:06:55 +00003114
Tom Careb49ec692010-06-17 19:00:27 +00003115void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00003116 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003117 const analyze_printf::OptionalAmount &Amt,
3118 unsigned type,
3119 const char *startSpecifier,
3120 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003121 const analyze_printf::PrintfConversionSpecifier &CS =
3122 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00003123
Richard Trieu03cf7b72011-10-28 00:41:25 +00003124 FixItHint fixit =
3125 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
3126 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
3127 Amt.getConstantLength()))
3128 : FixItHint();
3129
3130 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
3131 << type << CS.toString(),
3132 getLocationOfByte(Amt.getStart()),
3133 /*IsStringLocation*/true,
3134 getSpecifierRange(startSpecifier, specifierLen),
3135 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00003136}
3137
Ted Kremenek02087932010-07-16 02:11:22 +00003138void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003139 const analyze_printf::OptionalFlag &flag,
3140 const char *startSpecifier,
3141 unsigned specifierLen) {
3142 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003143 const analyze_printf::PrintfConversionSpecifier &CS =
3144 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00003145 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
3146 << flag.toString() << CS.toString(),
3147 getLocationOfByte(flag.getPosition()),
3148 /*IsStringLocation*/true,
3149 getSpecifierRange(startSpecifier, specifierLen),
3150 FixItHint::CreateRemoval(
3151 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00003152}
3153
3154void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00003155 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003156 const analyze_printf::OptionalFlag &ignoredFlag,
3157 const analyze_printf::OptionalFlag &flag,
3158 const char *startSpecifier,
3159 unsigned specifierLen) {
3160 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003161 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
3162 << ignoredFlag.toString() << flag.toString(),
3163 getLocationOfByte(ignoredFlag.getPosition()),
3164 /*IsStringLocation*/true,
3165 getSpecifierRange(startSpecifier, specifierLen),
3166 FixItHint::CreateRemoval(
3167 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00003168}
3169
Richard Smith55ce3522012-06-25 20:30:08 +00003170// Determines if the specified is a C++ class or struct containing
3171// a member with the specified name and kind (e.g. a CXXMethodDecl named
3172// "c_str()").
3173template<typename MemberKind>
3174static llvm::SmallPtrSet<MemberKind*, 1>
3175CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
3176 const RecordType *RT = Ty->getAs<RecordType>();
3177 llvm::SmallPtrSet<MemberKind*, 1> Results;
3178
3179 if (!RT)
3180 return Results;
3181 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00003182 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00003183 return Results;
3184
Alp Tokerb6cc5922014-05-03 03:45:55 +00003185 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00003186 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00003187 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00003188
3189 // We just need to include all members of the right kind turned up by the
3190 // filter, at this point.
3191 if (S.LookupQualifiedName(R, RT->getDecl()))
3192 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3193 NamedDecl *decl = (*I)->getUnderlyingDecl();
3194 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
3195 Results.insert(FK);
3196 }
3197 return Results;
3198}
3199
Richard Smith2868a732014-02-28 01:36:39 +00003200/// Check if we could call '.c_str()' on an object.
3201///
3202/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
3203/// allow the call, or if it would be ambiguous).
3204bool Sema::hasCStrMethod(const Expr *E) {
3205 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3206 MethodSet Results =
3207 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
3208 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3209 MI != ME; ++MI)
3210 if ((*MI)->getMinRequiredArguments() == 0)
3211 return true;
3212 return false;
3213}
3214
Richard Smith55ce3522012-06-25 20:30:08 +00003215// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003216// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00003217// Returns true when a c_str() conversion method is found.
3218bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00003219 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00003220 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3221
3222 MethodSet Results =
3223 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
3224
3225 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3226 MI != ME; ++MI) {
3227 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00003228 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00003229 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00003230 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00003231 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00003232 S.Diag(E->getLocStart(), diag::note_printf_c_str)
3233 << "c_str()"
3234 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
3235 return true;
3236 }
3237 }
3238
3239 return false;
3240}
3241
Ted Kremenekab278de2010-01-28 23:39:18 +00003242bool
Ted Kremenek02087932010-07-16 02:11:22 +00003243CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00003244 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00003245 const char *startSpecifier,
3246 unsigned specifierLen) {
3247
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003248 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00003249 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003250 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00003251
Ted Kremenek6cd69422010-07-19 22:01:06 +00003252 if (FS.consumesDataArgument()) {
3253 if (atFirstArg) {
3254 atFirstArg = false;
3255 usesPositionalArgs = FS.usesPositionalArg();
3256 }
3257 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003258 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3259 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003260 return false;
3261 }
Ted Kremenek5739de72010-01-29 01:06:55 +00003262 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003263
Ted Kremenekd1668192010-02-27 01:41:03 +00003264 // First check if the field width, precision, and conversion specifier
3265 // have matching data arguments.
3266 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
3267 startSpecifier, specifierLen)) {
3268 return false;
3269 }
3270
3271 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
3272 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003273 return false;
3274 }
3275
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003276 if (!CS.consumesDataArgument()) {
3277 // FIXME: Technically specifying a precision or field width here
3278 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00003279 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003280 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003281
Ted Kremenek4a49d982010-02-26 19:18:41 +00003282 // Consume the argument.
3283 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00003284 if (argIndex < NumDataArgs) {
3285 // The check to see if the argIndex is valid will come later.
3286 // We set the bit here because we may exit early from this
3287 // function if we encounter some other error.
3288 CoveredArgs.set(argIndex);
3289 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00003290
3291 // Check for using an Objective-C specific conversion specifier
3292 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003293 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00003294 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
3295 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00003296 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003297
Tom Careb49ec692010-06-17 19:00:27 +00003298 // Check for invalid use of field width
3299 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00003300 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00003301 startSpecifier, specifierLen);
3302 }
3303
3304 // Check for invalid use of precision
3305 if (!FS.hasValidPrecision()) {
3306 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
3307 startSpecifier, specifierLen);
3308 }
3309
3310 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00003311 if (!FS.hasValidThousandsGroupingPrefix())
3312 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003313 if (!FS.hasValidLeadingZeros())
3314 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
3315 if (!FS.hasValidPlusPrefix())
3316 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00003317 if (!FS.hasValidSpacePrefix())
3318 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003319 if (!FS.hasValidAlternativeForm())
3320 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3321 if (!FS.hasValidLeftJustified())
3322 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3323
3324 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00003325 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3326 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3327 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003328 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3329 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3330 startSpecifier, specifierLen);
3331
3332 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003333 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003334 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3335 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003336 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003337 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003338 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003339 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3340 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00003341
Jordan Rose92303592012-09-08 04:00:03 +00003342 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3343 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3344
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003345 // The remaining checks depend on the data arguments.
3346 if (HasVAListArg)
3347 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003348
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003349 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003350 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003351
Jordan Rose58bbe422012-07-19 18:10:08 +00003352 const Expr *Arg = getDataArg(argIndex);
3353 if (!Arg)
3354 return true;
3355
3356 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00003357}
3358
Jordan Roseaee34382012-09-05 22:56:26 +00003359static bool requiresParensToAddCast(const Expr *E) {
3360 // FIXME: We should have a general way to reason about operator
3361 // precedence and whether parens are actually needed here.
3362 // Take care of a few common cases where they aren't.
3363 const Expr *Inside = E->IgnoreImpCasts();
3364 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3365 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3366
3367 switch (Inside->getStmtClass()) {
3368 case Stmt::ArraySubscriptExprClass:
3369 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003370 case Stmt::CharacterLiteralClass:
3371 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003372 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003373 case Stmt::FloatingLiteralClass:
3374 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003375 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003376 case Stmt::ObjCArrayLiteralClass:
3377 case Stmt::ObjCBoolLiteralExprClass:
3378 case Stmt::ObjCBoxedExprClass:
3379 case Stmt::ObjCDictionaryLiteralClass:
3380 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003381 case Stmt::ObjCIvarRefExprClass:
3382 case Stmt::ObjCMessageExprClass:
3383 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003384 case Stmt::ObjCStringLiteralClass:
3385 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003386 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003387 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003388 case Stmt::UnaryOperatorClass:
3389 return false;
3390 default:
3391 return true;
3392 }
3393}
3394
Richard Smith55ce3522012-06-25 20:30:08 +00003395bool
3396CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3397 const char *StartSpecifier,
3398 unsigned SpecifierLen,
3399 const Expr *E) {
3400 using namespace analyze_format_string;
3401 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003402 // Now type check the data expression that matches the
3403 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003404 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3405 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00003406 if (!AT.isValid())
3407 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00003408
Jordan Rose598ec092012-12-05 18:44:40 +00003409 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00003410 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3411 ExprTy = TET->getUnderlyingExpr()->getType();
3412 }
3413
Jordan Rose598ec092012-12-05 18:44:40 +00003414 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003415 return true;
Jordan Rose98709982012-06-04 22:48:57 +00003416
Jordan Rose22b74712012-09-05 22:56:19 +00003417 // Look through argument promotions for our error message's reported type.
3418 // This includes the integral and floating promotions, but excludes array
3419 // and function pointer decay; seeing that an argument intended to be a
3420 // string has type 'char [6]' is probably more confusing than 'char *'.
3421 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3422 if (ICE->getCastKind() == CK_IntegralCast ||
3423 ICE->getCastKind() == CK_FloatingCast) {
3424 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00003425 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00003426
3427 // Check if we didn't match because of an implicit cast from a 'char'
3428 // or 'short' to an 'int'. This is done because printf is a varargs
3429 // function.
3430 if (ICE->getType() == S.Context.IntTy ||
3431 ICE->getType() == S.Context.UnsignedIntTy) {
3432 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00003433 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003434 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00003435 }
Jordan Rose98709982012-06-04 22:48:57 +00003436 }
Jordan Rose598ec092012-12-05 18:44:40 +00003437 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3438 // Special case for 'a', which has type 'int' in C.
3439 // Note, however, that we do /not/ want to treat multibyte constants like
3440 // 'MooV' as characters! This form is deprecated but still exists.
3441 if (ExprTy == S.Context.IntTy)
3442 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3443 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00003444 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003445
Jordan Rosebc53ed12014-05-31 04:12:14 +00003446 // Look through enums to their underlying type.
3447 bool IsEnum = false;
3448 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
3449 ExprTy = EnumTy->getDecl()->getIntegerType();
3450 IsEnum = true;
3451 }
3452
Jordan Rose0e5badd2012-12-05 18:44:49 +00003453 // %C in an Objective-C context prints a unichar, not a wchar_t.
3454 // If the argument is an integer of some kind, believe the %C and suggest
3455 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00003456 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003457 if (ObjCContext &&
3458 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3459 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3460 !ExprTy->isCharType()) {
3461 // 'unichar' is defined as a typedef of unsigned short, but we should
3462 // prefer using the typedef if it is visible.
3463 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00003464
3465 // While we are here, check if the value is an IntegerLiteral that happens
3466 // to be within the valid range.
3467 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3468 const llvm::APInt &V = IL->getValue();
3469 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3470 return true;
3471 }
3472
Jordan Rose0e5badd2012-12-05 18:44:49 +00003473 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3474 Sema::LookupOrdinaryName);
3475 if (S.LookupName(Result, S.getCurScope())) {
3476 NamedDecl *ND = Result.getFoundDecl();
3477 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3478 if (TD->getUnderlyingType() == IntendedTy)
3479 IntendedTy = S.Context.getTypedefType(TD);
3480 }
3481 }
3482 }
3483
3484 // Special-case some of Darwin's platform-independence types by suggesting
3485 // casts to primitive types that are known to be large enough.
3486 bool ShouldNotPrintDirectly = false;
Jordan Roseaee34382012-09-05 22:56:26 +00003487 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003488 // Use a 'while' to peel off layers of typedefs.
3489 QualType TyTy = IntendedTy;
3490 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
Jordan Roseaee34382012-09-05 22:56:26 +00003491 StringRef Name = UserTy->getDecl()->getName();
Jordan Rose0e5badd2012-12-05 18:44:49 +00003492 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Jordan Roseaee34382012-09-05 22:56:26 +00003493 .Case("NSInteger", S.Context.LongTy)
3494 .Case("NSUInteger", S.Context.UnsignedLongTy)
3495 .Case("SInt32", S.Context.IntTy)
3496 .Case("UInt32", S.Context.UnsignedIntTy)
Jordan Rose0e5badd2012-12-05 18:44:49 +00003497 .Default(QualType());
3498
3499 if (!CastTy.isNull()) {
3500 ShouldNotPrintDirectly = true;
3501 IntendedTy = CastTy;
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003502 break;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003503 }
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003504 TyTy = UserTy->desugar();
Jordan Roseaee34382012-09-05 22:56:26 +00003505 }
3506 }
3507
Jordan Rose22b74712012-09-05 22:56:19 +00003508 // We may be able to offer a FixItHint if it is a supported type.
3509 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00003510 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00003511 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003512
Jordan Rose22b74712012-09-05 22:56:19 +00003513 if (success) {
3514 // Get the fix string from the fixed format specifier
3515 SmallString<16> buf;
3516 llvm::raw_svector_ostream os(buf);
3517 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003518
Jordan Roseaee34382012-09-05 22:56:26 +00003519 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3520
Jordan Rose0e5badd2012-12-05 18:44:49 +00003521 if (IntendedTy == ExprTy) {
3522 // In this case, the specifier is wrong and should be changed to match
3523 // the argument.
3524 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003525 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3526 << AT.getRepresentativeTypeName(S.Context) << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003527 << E->getSourceRange(),
3528 E->getLocStart(),
3529 /*IsStringLocation*/false,
3530 SpecRange,
3531 FixItHint::CreateReplacement(SpecRange, os.str()));
3532
3533 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00003534 // The canonical type for formatting this value is different from the
3535 // actual type of the expression. (This occurs, for example, with Darwin's
3536 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3537 // should be printed as 'long' for 64-bit compatibility.)
3538 // Rather than emitting a normal format/argument mismatch, we want to
3539 // add a cast to the recommended type (and correct the format string
3540 // if necessary).
3541 SmallString<16> CastBuf;
3542 llvm::raw_svector_ostream CastFix(CastBuf);
3543 CastFix << "(";
3544 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3545 CastFix << ")";
3546
3547 SmallVector<FixItHint,4> Hints;
3548 if (!AT.matchesType(S.Context, IntendedTy))
3549 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3550
3551 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3552 // If there's already a cast present, just replace it.
3553 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3554 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3555
3556 } else if (!requiresParensToAddCast(E)) {
3557 // If the expression has high enough precedence,
3558 // just write the C-style cast.
3559 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3560 CastFix.str()));
3561 } else {
3562 // Otherwise, add parens around the expression as well as the cast.
3563 CastFix << "(";
3564 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3565 CastFix.str()));
3566
Alp Tokerb6cc5922014-05-03 03:45:55 +00003567 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00003568 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3569 }
3570
Jordan Rose0e5badd2012-12-05 18:44:49 +00003571 if (ShouldNotPrintDirectly) {
3572 // The expression has a type that should not be printed directly.
3573 // We extract the name from the typedef because we don't want to show
3574 // the underlying type in the diagnostic.
3575 StringRef Name = cast<TypedefType>(ExprTy)->getDecl()->getName();
Jordan Roseaee34382012-09-05 22:56:26 +00003576
Jordan Rose0e5badd2012-12-05 18:44:49 +00003577 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00003578 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003579 << E->getSourceRange(),
3580 E->getLocStart(), /*IsStringLocation=*/false,
3581 SpecRange, Hints);
3582 } else {
3583 // In this case, the expression could be printed using a different
3584 // specifier, but we've decided that the specifier is probably correct
3585 // and we should cast instead. Just use the normal warning message.
3586 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003587 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3588 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003589 << E->getSourceRange(),
3590 E->getLocStart(), /*IsStringLocation*/false,
3591 SpecRange, Hints);
3592 }
Jordan Roseaee34382012-09-05 22:56:26 +00003593 }
Jordan Rose22b74712012-09-05 22:56:19 +00003594 } else {
3595 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3596 SpecifierLen);
3597 // Since the warning for passing non-POD types to variadic functions
3598 // was deferred until now, we emit a warning for non-POD
3599 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00003600 switch (S.isValidVarArgType(ExprTy)) {
3601 case Sema::VAK_Valid:
3602 case Sema::VAK_ValidInCXX11:
Jordan Rose22b74712012-09-05 22:56:19 +00003603 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003604 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3605 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Richard Smithd7293d72013-08-05 18:49:43 +00003606 << CSR
3607 << E->getSourceRange(),
3608 E->getLocStart(), /*IsStringLocation*/false, CSR);
3609 break;
3610
3611 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00003612 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00003613 EmitFormatDiagnostic(
3614 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003615 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00003616 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00003617 << CallType
3618 << AT.getRepresentativeTypeName(S.Context)
3619 << CSR
3620 << E->getSourceRange(),
3621 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00003622 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00003623 break;
3624
3625 case Sema::VAK_Invalid:
3626 if (ExprTy->isObjCObjectType())
3627 EmitFormatDiagnostic(
3628 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3629 << S.getLangOpts().CPlusPlus11
3630 << ExprTy
3631 << CallType
3632 << AT.getRepresentativeTypeName(S.Context)
3633 << CSR
3634 << E->getSourceRange(),
3635 E->getLocStart(), /*IsStringLocation*/false, CSR);
3636 else
3637 // FIXME: If this is an initializer list, suggest removing the braces
3638 // or inserting a cast to the target type.
3639 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3640 << isa<InitListExpr>(E) << ExprTy << CallType
3641 << AT.getRepresentativeTypeName(S.Context)
3642 << E->getSourceRange();
3643 break;
3644 }
3645
3646 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3647 "format string specifier index out of range");
3648 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003649 }
3650
Ted Kremenekab278de2010-01-28 23:39:18 +00003651 return true;
3652}
3653
Ted Kremenek02087932010-07-16 02:11:22 +00003654//===--- CHECK: Scanf format string checking ------------------------------===//
3655
3656namespace {
3657class CheckScanfHandler : public CheckFormatHandler {
3658public:
3659 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3660 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003661 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003662 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003663 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003664 Sema::VariadicCallType CallType,
3665 llvm::SmallBitVector &CheckedVarArgs)
3666 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3667 numDataArgs, beg, hasVAListArg,
3668 Args, formatIdx, inFunctionCall, CallType,
3669 CheckedVarArgs)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003670 {}
Ted Kremenek02087932010-07-16 02:11:22 +00003671
3672 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3673 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003674 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00003675
3676 bool HandleInvalidScanfConversionSpecifier(
3677 const analyze_scanf::ScanfSpecifier &FS,
3678 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003679 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003680
Craig Toppere14c0f82014-03-12 04:55:44 +00003681 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00003682};
Ted Kremenek019d2242010-01-29 01:50:07 +00003683}
Ted Kremenekab278de2010-01-28 23:39:18 +00003684
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003685void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3686 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003687 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3688 getLocationOfByte(end), /*IsStringLocation*/true,
3689 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003690}
3691
Ted Kremenekce815422010-07-19 21:25:57 +00003692bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3693 const analyze_scanf::ScanfSpecifier &FS,
3694 const char *startSpecifier,
3695 unsigned specifierLen) {
3696
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003697 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003698 FS.getConversionSpecifier();
3699
3700 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3701 getLocationOfByte(CS.getStart()),
3702 startSpecifier, specifierLen,
3703 CS.getStart(), CS.getLength());
3704}
3705
Ted Kremenek02087932010-07-16 02:11:22 +00003706bool CheckScanfHandler::HandleScanfSpecifier(
3707 const analyze_scanf::ScanfSpecifier &FS,
3708 const char *startSpecifier,
3709 unsigned specifierLen) {
3710
3711 using namespace analyze_scanf;
3712 using namespace analyze_format_string;
3713
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003714 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003715
Ted Kremenek6cd69422010-07-19 22:01:06 +00003716 // Handle case where '%' and '*' don't consume an argument. These shouldn't
3717 // be used to decide if we are using positional arguments consistently.
3718 if (FS.consumesDataArgument()) {
3719 if (atFirstArg) {
3720 atFirstArg = false;
3721 usesPositionalArgs = FS.usesPositionalArg();
3722 }
3723 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003724 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3725 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003726 return false;
3727 }
Ted Kremenek02087932010-07-16 02:11:22 +00003728 }
3729
3730 // Check if the field with is non-zero.
3731 const OptionalAmount &Amt = FS.getFieldWidth();
3732 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3733 if (Amt.getConstantAmount() == 0) {
3734 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3735 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00003736 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3737 getLocationOfByte(Amt.getStart()),
3738 /*IsStringLocation*/true, R,
3739 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00003740 }
3741 }
3742
3743 if (!FS.consumesDataArgument()) {
3744 // FIXME: Technically specifying a precision or field width here
3745 // makes no sense. Worth issuing a warning at some point.
3746 return true;
3747 }
3748
3749 // Consume the argument.
3750 unsigned argIndex = FS.getArgIndex();
3751 if (argIndex < NumDataArgs) {
3752 // The check to see if the argIndex is valid will come later.
3753 // We set the bit here because we may exit early from this
3754 // function if we encounter some other error.
3755 CoveredArgs.set(argIndex);
3756 }
3757
Ted Kremenek4407ea42010-07-20 20:04:47 +00003758 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003759 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003760 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3761 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003762 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003763 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003764 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003765 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3766 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003767
Jordan Rose92303592012-09-08 04:00:03 +00003768 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3769 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3770
Ted Kremenek02087932010-07-16 02:11:22 +00003771 // The remaining checks depend on the data arguments.
3772 if (HasVAListArg)
3773 return true;
3774
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003775 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00003776 return false;
Ted Kremenek02087932010-07-16 02:11:22 +00003777
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003778 // Check that the argument type matches the format specifier.
3779 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00003780 if (!Ex)
3781 return true;
3782
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00003783 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3784 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003785 ScanfSpecifier fixedFS = FS;
Jordan Rose177b0a32014-03-20 03:32:39 +00003786 bool success = fixedFS.fixType(Ex->getType(),
3787 Ex->IgnoreImpCasts()->getType(),
3788 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003789
3790 if (success) {
3791 // Get the fix string from the fixed format specifier.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003792 SmallString<128> buf;
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003793 llvm::raw_svector_ostream os(buf);
3794 fixedFS.toString(os);
3795
3796 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003797 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3798 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() << false
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003799 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00003800 Ex->getLocStart(),
3801 /*IsStringLocation*/false,
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003802 getSpecifierRange(startSpecifier, specifierLen),
3803 FixItHint::CreateReplacement(
3804 getSpecifierRange(startSpecifier, specifierLen),
3805 os.str()));
3806 } else {
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003807 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003808 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3809 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() << false
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003810 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00003811 Ex->getLocStart(),
3812 /*IsStringLocation*/false,
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003813 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003814 }
3815 }
3816
Ted Kremenek02087932010-07-16 02:11:22 +00003817 return true;
3818}
3819
3820void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00003821 const Expr *OrigFormatExpr,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003822 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003823 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003824 unsigned firstDataArg, FormatStringType Type,
Richard Smithd7293d72013-08-05 18:49:43 +00003825 bool inFunctionCall, VariadicCallType CallType,
3826 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00003827
Ted Kremenekab278de2010-01-28 23:39:18 +00003828 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00003829 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003830 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003831 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00003832 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3833 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00003834 return;
3835 }
Ted Kremenek02087932010-07-16 02:11:22 +00003836
Ted Kremenekab278de2010-01-28 23:39:18 +00003837 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003838 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00003839 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00003840 // Account for cases where the string literal is truncated in a declaration.
3841 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
3842 assert(T && "String literal not of constant array type!");
3843 size_t TypeSize = T->getSize().getZExtValue();
3844 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003845 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00003846
3847 // Emit a warning if the string literal is truncated and does not contain an
3848 // embedded null character.
3849 if (TypeSize <= StrRef.size() &&
3850 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
3851 CheckFormatHandler::EmitFormatDiagnostic(
3852 *this, inFunctionCall, Args[format_idx],
3853 PDiag(diag::warn_printf_format_string_not_null_terminated),
3854 FExpr->getLocStart(),
3855 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
3856 return;
3857 }
3858
Ted Kremenekab278de2010-01-28 23:39:18 +00003859 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00003860 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003861 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003862 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00003863 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3864 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00003865 return;
3866 }
Ted Kremenek02087932010-07-16 02:11:22 +00003867
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003868 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek02087932010-07-16 02:11:22 +00003869 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003870 numDataArgs, (Type == FST_NSString),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003871 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00003872 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00003873
Hans Wennborg23926bd2011-12-15 10:25:47 +00003874 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00003875 getLangOpts(),
3876 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00003877 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003878 } else if (Type == FST_Scanf) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003879 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003880 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00003881 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00003882
Hans Wennborg23926bd2011-12-15 10:25:47 +00003883 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00003884 getLangOpts(),
3885 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00003886 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003887 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00003888}
3889
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00003890bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
3891 // Str - The format string. NOTE: this is NOT null-terminated!
3892 StringRef StrRef = FExpr->getString();
3893 const char *Str = StrRef.data();
3894 // Account for cases where the string literal is truncated in a declaration.
3895 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
3896 assert(T && "String literal not of constant array type!");
3897 size_t TypeSize = T->getSize().getZExtValue();
3898 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
3899 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
3900 getLangOpts(),
3901 Context.getTargetInfo());
3902}
3903
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003904//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
3905
3906// Returns the related absolute value function that is larger, of 0 if one
3907// does not exist.
3908static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
3909 switch (AbsFunction) {
3910 default:
3911 return 0;
3912
3913 case Builtin::BI__builtin_abs:
3914 return Builtin::BI__builtin_labs;
3915 case Builtin::BI__builtin_labs:
3916 return Builtin::BI__builtin_llabs;
3917 case Builtin::BI__builtin_llabs:
3918 return 0;
3919
3920 case Builtin::BI__builtin_fabsf:
3921 return Builtin::BI__builtin_fabs;
3922 case Builtin::BI__builtin_fabs:
3923 return Builtin::BI__builtin_fabsl;
3924 case Builtin::BI__builtin_fabsl:
3925 return 0;
3926
3927 case Builtin::BI__builtin_cabsf:
3928 return Builtin::BI__builtin_cabs;
3929 case Builtin::BI__builtin_cabs:
3930 return Builtin::BI__builtin_cabsl;
3931 case Builtin::BI__builtin_cabsl:
3932 return 0;
3933
3934 case Builtin::BIabs:
3935 return Builtin::BIlabs;
3936 case Builtin::BIlabs:
3937 return Builtin::BIllabs;
3938 case Builtin::BIllabs:
3939 return 0;
3940
3941 case Builtin::BIfabsf:
3942 return Builtin::BIfabs;
3943 case Builtin::BIfabs:
3944 return Builtin::BIfabsl;
3945 case Builtin::BIfabsl:
3946 return 0;
3947
3948 case Builtin::BIcabsf:
3949 return Builtin::BIcabs;
3950 case Builtin::BIcabs:
3951 return Builtin::BIcabsl;
3952 case Builtin::BIcabsl:
3953 return 0;
3954 }
3955}
3956
3957// Returns the argument type of the absolute value function.
3958static QualType getAbsoluteValueArgumentType(ASTContext &Context,
3959 unsigned AbsType) {
3960 if (AbsType == 0)
3961 return QualType();
3962
3963 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3964 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
3965 if (Error != ASTContext::GE_None)
3966 return QualType();
3967
3968 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
3969 if (!FT)
3970 return QualType();
3971
3972 if (FT->getNumParams() != 1)
3973 return QualType();
3974
3975 return FT->getParamType(0);
3976}
3977
3978// Returns the best absolute value function, or zero, based on type and
3979// current absolute value function.
3980static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
3981 unsigned AbsFunctionKind) {
3982 unsigned BestKind = 0;
3983 uint64_t ArgSize = Context.getTypeSize(ArgType);
3984 for (unsigned Kind = AbsFunctionKind; Kind != 0;
3985 Kind = getLargerAbsoluteValueFunction(Kind)) {
3986 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
3987 if (Context.getTypeSize(ParamType) >= ArgSize) {
3988 if (BestKind == 0)
3989 BestKind = Kind;
3990 else if (Context.hasSameType(ParamType, ArgType)) {
3991 BestKind = Kind;
3992 break;
3993 }
3994 }
3995 }
3996 return BestKind;
3997}
3998
3999enum AbsoluteValueKind {
4000 AVK_Integer,
4001 AVK_Floating,
4002 AVK_Complex
4003};
4004
4005static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
4006 if (T->isIntegralOrEnumerationType())
4007 return AVK_Integer;
4008 if (T->isRealFloatingType())
4009 return AVK_Floating;
4010 if (T->isAnyComplexType())
4011 return AVK_Complex;
4012
4013 llvm_unreachable("Type not integer, floating, or complex");
4014}
4015
4016// Changes the absolute value function to a different type. Preserves whether
4017// the function is a builtin.
4018static unsigned changeAbsFunction(unsigned AbsKind,
4019 AbsoluteValueKind ValueKind) {
4020 switch (ValueKind) {
4021 case AVK_Integer:
4022 switch (AbsKind) {
4023 default:
4024 return 0;
4025 case Builtin::BI__builtin_fabsf:
4026 case Builtin::BI__builtin_fabs:
4027 case Builtin::BI__builtin_fabsl:
4028 case Builtin::BI__builtin_cabsf:
4029 case Builtin::BI__builtin_cabs:
4030 case Builtin::BI__builtin_cabsl:
4031 return Builtin::BI__builtin_abs;
4032 case Builtin::BIfabsf:
4033 case Builtin::BIfabs:
4034 case Builtin::BIfabsl:
4035 case Builtin::BIcabsf:
4036 case Builtin::BIcabs:
4037 case Builtin::BIcabsl:
4038 return Builtin::BIabs;
4039 }
4040 case AVK_Floating:
4041 switch (AbsKind) {
4042 default:
4043 return 0;
4044 case Builtin::BI__builtin_abs:
4045 case Builtin::BI__builtin_labs:
4046 case Builtin::BI__builtin_llabs:
4047 case Builtin::BI__builtin_cabsf:
4048 case Builtin::BI__builtin_cabs:
4049 case Builtin::BI__builtin_cabsl:
4050 return Builtin::BI__builtin_fabsf;
4051 case Builtin::BIabs:
4052 case Builtin::BIlabs:
4053 case Builtin::BIllabs:
4054 case Builtin::BIcabsf:
4055 case Builtin::BIcabs:
4056 case Builtin::BIcabsl:
4057 return Builtin::BIfabsf;
4058 }
4059 case AVK_Complex:
4060 switch (AbsKind) {
4061 default:
4062 return 0;
4063 case Builtin::BI__builtin_abs:
4064 case Builtin::BI__builtin_labs:
4065 case Builtin::BI__builtin_llabs:
4066 case Builtin::BI__builtin_fabsf:
4067 case Builtin::BI__builtin_fabs:
4068 case Builtin::BI__builtin_fabsl:
4069 return Builtin::BI__builtin_cabsf;
4070 case Builtin::BIabs:
4071 case Builtin::BIlabs:
4072 case Builtin::BIllabs:
4073 case Builtin::BIfabsf:
4074 case Builtin::BIfabs:
4075 case Builtin::BIfabsl:
4076 return Builtin::BIcabsf;
4077 }
4078 }
4079 llvm_unreachable("Unable to convert function");
4080}
4081
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00004082static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004083 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
4084 if (!FnInfo)
4085 return 0;
4086
4087 switch (FDecl->getBuiltinID()) {
4088 default:
4089 return 0;
4090 case Builtin::BI__builtin_abs:
4091 case Builtin::BI__builtin_fabs:
4092 case Builtin::BI__builtin_fabsf:
4093 case Builtin::BI__builtin_fabsl:
4094 case Builtin::BI__builtin_labs:
4095 case Builtin::BI__builtin_llabs:
4096 case Builtin::BI__builtin_cabs:
4097 case Builtin::BI__builtin_cabsf:
4098 case Builtin::BI__builtin_cabsl:
4099 case Builtin::BIabs:
4100 case Builtin::BIlabs:
4101 case Builtin::BIllabs:
4102 case Builtin::BIfabs:
4103 case Builtin::BIfabsf:
4104 case Builtin::BIfabsl:
4105 case Builtin::BIcabs:
4106 case Builtin::BIcabsf:
4107 case Builtin::BIcabsl:
4108 return FDecl->getBuiltinID();
4109 }
4110 llvm_unreachable("Unknown Builtin type");
4111}
4112
4113// If the replacement is valid, emit a note with replacement function.
4114// Additionally, suggest including the proper header if not already included.
4115static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00004116 unsigned AbsKind, QualType ArgType) {
4117 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00004118 const char *HeaderName = nullptr;
4119 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00004120 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
4121 FunctionName = "std::abs";
4122 if (ArgType->isIntegralOrEnumerationType()) {
4123 HeaderName = "cstdlib";
4124 } else if (ArgType->isRealFloatingType()) {
4125 HeaderName = "cmath";
4126 } else {
4127 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004128 }
Richard Trieubeffb832014-04-15 23:47:53 +00004129
4130 // Lookup all std::abs
4131 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00004132 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00004133 R.suppressDiagnostics();
4134 S.LookupQualifiedName(R, Std);
4135
4136 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004137 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00004138 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
4139 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
4140 } else {
4141 FDecl = dyn_cast<FunctionDecl>(I);
4142 }
4143 if (!FDecl)
4144 continue;
4145
4146 // Found std::abs(), check that they are the right ones.
4147 if (FDecl->getNumParams() != 1)
4148 continue;
4149
4150 // Check that the parameter type can handle the argument.
4151 QualType ParamType = FDecl->getParamDecl(0)->getType();
4152 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
4153 S.Context.getTypeSize(ArgType) <=
4154 S.Context.getTypeSize(ParamType)) {
4155 // Found a function, don't need the header hint.
4156 EmitHeaderHint = false;
4157 break;
4158 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004159 }
Richard Trieubeffb832014-04-15 23:47:53 +00004160 }
4161 } else {
4162 FunctionName = S.Context.BuiltinInfo.GetName(AbsKind);
4163 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
4164
4165 if (HeaderName) {
4166 DeclarationName DN(&S.Context.Idents.get(FunctionName));
4167 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
4168 R.suppressDiagnostics();
4169 S.LookupName(R, S.getCurScope());
4170
4171 if (R.isSingleResult()) {
4172 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
4173 if (FD && FD->getBuiltinID() == AbsKind) {
4174 EmitHeaderHint = false;
4175 } else {
4176 return;
4177 }
4178 } else if (!R.empty()) {
4179 return;
4180 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004181 }
4182 }
4183
4184 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00004185 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004186
Richard Trieubeffb832014-04-15 23:47:53 +00004187 if (!HeaderName)
4188 return;
4189
4190 if (!EmitHeaderHint)
4191 return;
4192
Alp Toker5d96e0a2014-07-11 20:53:51 +00004193 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
4194 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00004195}
4196
4197static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
4198 if (!FDecl)
4199 return false;
4200
4201 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
4202 return false;
4203
4204 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
4205
4206 while (ND && ND->isInlineNamespace()) {
4207 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004208 }
Richard Trieubeffb832014-04-15 23:47:53 +00004209
4210 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
4211 return false;
4212
4213 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
4214 return false;
4215
4216 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004217}
4218
4219// Warn when using the wrong abs() function.
4220void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
4221 const FunctionDecl *FDecl,
4222 IdentifierInfo *FnInfo) {
4223 if (Call->getNumArgs() != 1)
4224 return;
4225
4226 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00004227 bool IsStdAbs = IsFunctionStdAbs(FDecl);
4228 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004229 return;
4230
4231 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
4232 QualType ParamType = Call->getArg(0)->getType();
4233
Alp Toker5d96e0a2014-07-11 20:53:51 +00004234 // Unsigned types cannot be negative. Suggest removing the absolute value
4235 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004236 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00004237 const char *FunctionName =
4238 IsStdAbs ? "std::abs" : Context.BuiltinInfo.GetName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004239 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
4240 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00004241 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004242 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
4243 return;
4244 }
4245
Richard Trieubeffb832014-04-15 23:47:53 +00004246 // std::abs has overloads which prevent most of the absolute value problems
4247 // from occurring.
4248 if (IsStdAbs)
4249 return;
4250
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004251 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
4252 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
4253
4254 // The argument and parameter are the same kind. Check if they are the right
4255 // size.
4256 if (ArgValueKind == ParamValueKind) {
4257 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
4258 return;
4259
4260 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
4261 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
4262 << FDecl << ArgType << ParamType;
4263
4264 if (NewAbsKind == 0)
4265 return;
4266
4267 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00004268 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004269 return;
4270 }
4271
4272 // ArgValueKind != ParamValueKind
4273 // The wrong type of absolute value function was used. Attempt to find the
4274 // proper one.
4275 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
4276 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
4277 if (NewAbsKind == 0)
4278 return;
4279
4280 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
4281 << FDecl << ParamValueKind << ArgValueKind;
4282
4283 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00004284 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004285 return;
4286}
4287
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004288//===--- CHECK: Standard memory functions ---------------------------------===//
4289
Nico Weber0e6daef2013-12-26 23:38:39 +00004290/// \brief Takes the expression passed to the size_t parameter of functions
4291/// such as memcmp, strncat, etc and warns if it's a comparison.
4292///
4293/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
4294static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
4295 IdentifierInfo *FnName,
4296 SourceLocation FnLoc,
4297 SourceLocation RParenLoc) {
4298 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
4299 if (!Size)
4300 return false;
4301
4302 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
4303 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
4304 return false;
4305
Nico Weber0e6daef2013-12-26 23:38:39 +00004306 SourceRange SizeRange = Size->getSourceRange();
4307 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
4308 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00004309 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00004310 << FnName << FixItHint::CreateInsertion(
4311 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00004312 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00004313 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00004314 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00004315 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
4316 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00004317
4318 return true;
4319}
4320
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004321/// \brief Determine whether the given type is or contains a dynamic class type
4322/// (e.g., whether it has a vtable).
4323static const CXXRecordDecl *getContainedDynamicClass(QualType T,
4324 bool &IsContained) {
4325 // Look through array types while ignoring qualifiers.
4326 const Type *Ty = T->getBaseElementTypeUnsafe();
4327 IsContained = false;
4328
4329 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
4330 RD = RD ? RD->getDefinition() : nullptr;
4331 if (!RD)
4332 return nullptr;
4333
4334 if (RD->isDynamicClass())
4335 return RD;
4336
4337 // Check all the fields. If any bases were dynamic, the class is dynamic.
4338 // It's impossible for a class to transitively contain itself by value, so
4339 // infinite recursion is impossible.
4340 for (auto *FD : RD->fields()) {
4341 bool SubContained;
4342 if (const CXXRecordDecl *ContainedRD =
4343 getContainedDynamicClass(FD->getType(), SubContained)) {
4344 IsContained = true;
4345 return ContainedRD;
4346 }
4347 }
4348
4349 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00004350}
4351
Chandler Carruth889ed862011-06-21 23:04:20 +00004352/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004353/// otherwise returns NULL.
4354static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Weberc5e73862011-06-14 16:14:58 +00004355 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004356 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4357 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
4358 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004359
Craig Topperc3ec1492014-05-26 06:22:03 +00004360 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004361}
4362
Chandler Carruth889ed862011-06-21 23:04:20 +00004363/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004364static QualType getSizeOfArgType(const Expr* E) {
4365 if (const UnaryExprOrTypeTraitExpr *SizeOf =
4366 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4367 if (SizeOf->getKind() == clang::UETT_SizeOf)
4368 return SizeOf->getTypeOfArgument();
4369
4370 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00004371}
4372
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004373/// \brief Check for dangerous or invalid arguments to memset().
4374///
Chandler Carruthac687262011-06-03 06:23:57 +00004375/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004376/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
4377/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004378///
4379/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004380void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00004381 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004382 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00004383 assert(BId != 0);
4384
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004385 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00004386 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00004387 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00004388 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004389 return;
4390
Anna Zaks22122702012-01-17 00:37:07 +00004391 unsigned LastArg = (BId == Builtin::BImemset ||
4392 BId == Builtin::BIstrndup ? 1 : 2);
4393 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00004394 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004395
Nico Weber0e6daef2013-12-26 23:38:39 +00004396 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
4397 Call->getLocStart(), Call->getRParenLoc()))
4398 return;
4399
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004400 // We have special checking when the length is a sizeof expression.
4401 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
4402 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
4403 llvm::FoldingSetNodeID SizeOfArgID;
4404
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004405 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
4406 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004407 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004408
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004409 QualType DestTy = Dest->getType();
4410 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
4411 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00004412
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004413 // Never warn about void type pointers. This can be used to suppress
4414 // false positives.
4415 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004416 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004417
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004418 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
4419 // actually comparing the expressions for equality. Because computing the
4420 // expression IDs can be expensive, we only do this if the diagnostic is
4421 // enabled.
4422 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004423 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
4424 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004425 // We only compute IDs for expressions if the warning is enabled, and
4426 // cache the sizeof arg's ID.
4427 if (SizeOfArgID == llvm::FoldingSetNodeID())
4428 SizeOfArg->Profile(SizeOfArgID, Context, true);
4429 llvm::FoldingSetNodeID DestID;
4430 Dest->Profile(DestID, Context, true);
4431 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00004432 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
4433 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004434 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00004435 StringRef ReadableName = FnName->getName();
4436
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004437 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00004438 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004439 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00004440 if (!PointeeTy->isIncompleteType() &&
4441 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004442 ActionIdx = 2; // If the pointee's size is sizeof(char),
4443 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00004444
4445 // If the function is defined as a builtin macro, do not show macro
4446 // expansion.
4447 SourceLocation SL = SizeOfArg->getExprLoc();
4448 SourceRange DSR = Dest->getSourceRange();
4449 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00004450 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00004451
4452 if (SM.isMacroArgExpansion(SL)) {
4453 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
4454 SL = SM.getSpellingLoc(SL);
4455 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
4456 SM.getSpellingLoc(DSR.getEnd()));
4457 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
4458 SM.getSpellingLoc(SSR.getEnd()));
4459 }
4460
Anna Zaksd08d9152012-05-30 23:14:52 +00004461 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004462 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00004463 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00004464 << PointeeTy
4465 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00004466 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00004467 << SSR);
4468 DiagRuntimeBehavior(SL, SizeOfArg,
4469 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
4470 << ActionIdx
4471 << SSR);
4472
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004473 break;
4474 }
4475 }
4476
4477 // Also check for cases where the sizeof argument is the exact same
4478 // type as the memory argument, and where it points to a user-defined
4479 // record type.
4480 if (SizeOfArgTy != QualType()) {
4481 if (PointeeTy->isRecordType() &&
4482 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
4483 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
4484 PDiag(diag::warn_sizeof_pointer_type_memaccess)
4485 << FnName << SizeOfArgTy << ArgIdx
4486 << PointeeTy << Dest->getSourceRange()
4487 << LenExpr->getSourceRange());
4488 break;
4489 }
Nico Weberc5e73862011-06-14 16:14:58 +00004490 }
4491
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004492 // Always complain about dynamic classes.
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004493 bool IsContained;
4494 if (const CXXRecordDecl *ContainedRD =
4495 getContainedDynamicClass(PointeeTy, IsContained)) {
Anna Zaks22122702012-01-17 00:37:07 +00004496
4497 unsigned OperationType = 0;
4498 // "overwritten" if we're warning about the destination for any call
4499 // but memcmp; otherwise a verb appropriate to the call.
4500 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
4501 if (BId == Builtin::BImemcpy)
4502 OperationType = 1;
4503 else if(BId == Builtin::BImemmove)
4504 OperationType = 2;
4505 else if (BId == Builtin::BImemcmp)
4506 OperationType = 3;
4507 }
4508
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004509 DiagRuntimeBehavior(
4510 Dest->getExprLoc(), Dest,
4511 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks22122702012-01-17 00:37:07 +00004512 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004513 << FnName << IsContained << ContainedRD << OperationType
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004514 << Call->getCallee()->getSourceRange());
Anna Zaks22122702012-01-17 00:37:07 +00004515 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
4516 BId != Builtin::BImemset)
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004517 DiagRuntimeBehavior(
4518 Dest->getExprLoc(), Dest,
4519 PDiag(diag::warn_arc_object_memaccess)
4520 << ArgIdx << FnName << PointeeTy
4521 << Call->getCallee()->getSourceRange());
John McCall31168b02011-06-15 23:02:42 +00004522 else
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004523 continue;
John McCall31168b02011-06-15 23:02:42 +00004524
4525 DiagRuntimeBehavior(
4526 Dest->getExprLoc(), Dest,
Chandler Carruthac687262011-06-03 06:23:57 +00004527 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004528 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
4529 break;
4530 }
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004531 }
4532}
4533
Ted Kremenek6865f772011-08-18 20:55:45 +00004534// A little helper routine: ignore addition and subtraction of integer literals.
4535// This intentionally does not ignore all integer constant expressions because
4536// we don't want to remove sizeof().
4537static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
4538 Ex = Ex->IgnoreParenCasts();
4539
4540 for (;;) {
4541 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
4542 if (!BO || !BO->isAdditiveOp())
4543 break;
4544
4545 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
4546 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
4547
4548 if (isa<IntegerLiteral>(RHS))
4549 Ex = LHS;
4550 else if (isa<IntegerLiteral>(LHS))
4551 Ex = RHS;
4552 else
4553 break;
4554 }
4555
4556 return Ex;
4557}
4558
Anna Zaks13b08572012-08-08 21:42:23 +00004559static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
4560 ASTContext &Context) {
4561 // Only handle constant-sized or VLAs, but not flexible members.
4562 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
4563 // Only issue the FIXIT for arrays of size > 1.
4564 if (CAT->getSize().getSExtValue() <= 1)
4565 return false;
4566 } else if (!Ty->isVariableArrayType()) {
4567 return false;
4568 }
4569 return true;
4570}
4571
Ted Kremenek6865f772011-08-18 20:55:45 +00004572// Warn if the user has made the 'size' argument to strlcpy or strlcat
4573// be the size of the source, instead of the destination.
4574void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
4575 IdentifierInfo *FnName) {
4576
4577 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00004578 unsigned NumArgs = Call->getNumArgs();
4579 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00004580 return;
4581
4582 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
4583 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00004584 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00004585
4586 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
4587 Call->getLocStart(), Call->getRParenLoc()))
4588 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00004589
4590 // Look for 'strlcpy(dst, x, sizeof(x))'
4591 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
4592 CompareWithSrc = Ex;
4593 else {
4594 // Look for 'strlcpy(dst, x, strlen(x))'
4595 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00004596 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
4597 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00004598 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
4599 }
4600 }
4601
4602 if (!CompareWithSrc)
4603 return;
4604
4605 // Determine if the argument to sizeof/strlen is equal to the source
4606 // argument. In principle there's all kinds of things you could do
4607 // here, for instance creating an == expression and evaluating it with
4608 // EvaluateAsBooleanCondition, but this uses a more direct technique:
4609 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
4610 if (!SrcArgDRE)
4611 return;
4612
4613 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
4614 if (!CompareWithSrcDRE ||
4615 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
4616 return;
4617
4618 const Expr *OriginalSizeArg = Call->getArg(2);
4619 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
4620 << OriginalSizeArg->getSourceRange() << FnName;
4621
4622 // Output a FIXIT hint if the destination is an array (rather than a
4623 // pointer to an array). This could be enhanced to handle some
4624 // pointers if we know the actual size, like if DstArg is 'array+2'
4625 // we could say 'sizeof(array)-2'.
4626 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00004627 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00004628 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004629
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004630 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004631 llvm::raw_svector_ostream OS(sizeString);
4632 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004633 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00004634 OS << ")";
4635
4636 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
4637 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
4638 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00004639}
4640
Anna Zaks314cd092012-02-01 19:08:57 +00004641/// Check if two expressions refer to the same declaration.
4642static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
4643 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
4644 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
4645 return D1->getDecl() == D2->getDecl();
4646 return false;
4647}
4648
4649static const Expr *getStrlenExprArg(const Expr *E) {
4650 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
4651 const FunctionDecl *FD = CE->getDirectCallee();
4652 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00004653 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00004654 return CE->getArg(0)->IgnoreParenCasts();
4655 }
Craig Topperc3ec1492014-05-26 06:22:03 +00004656 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00004657}
4658
4659// Warn on anti-patterns as the 'size' argument to strncat.
4660// The correct size argument should look like following:
4661// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
4662void Sema::CheckStrncatArguments(const CallExpr *CE,
4663 IdentifierInfo *FnName) {
4664 // Don't crash if the user has the wrong number of arguments.
4665 if (CE->getNumArgs() < 3)
4666 return;
4667 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
4668 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
4669 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
4670
Nico Weber0e6daef2013-12-26 23:38:39 +00004671 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
4672 CE->getRParenLoc()))
4673 return;
4674
Anna Zaks314cd092012-02-01 19:08:57 +00004675 // Identify common expressions, which are wrongly used as the size argument
4676 // to strncat and may lead to buffer overflows.
4677 unsigned PatternType = 0;
4678 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
4679 // - sizeof(dst)
4680 if (referToTheSameDecl(SizeOfArg, DstArg))
4681 PatternType = 1;
4682 // - sizeof(src)
4683 else if (referToTheSameDecl(SizeOfArg, SrcArg))
4684 PatternType = 2;
4685 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
4686 if (BE->getOpcode() == BO_Sub) {
4687 const Expr *L = BE->getLHS()->IgnoreParenCasts();
4688 const Expr *R = BE->getRHS()->IgnoreParenCasts();
4689 // - sizeof(dst) - strlen(dst)
4690 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
4691 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
4692 PatternType = 1;
4693 // - sizeof(src) - (anything)
4694 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
4695 PatternType = 2;
4696 }
4697 }
4698
4699 if (PatternType == 0)
4700 return;
4701
Anna Zaks5069aa32012-02-03 01:27:37 +00004702 // Generate the diagnostic.
4703 SourceLocation SL = LenArg->getLocStart();
4704 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00004705 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00004706
4707 // If the function is defined as a builtin macro, do not show macro expansion.
4708 if (SM.isMacroArgExpansion(SL)) {
4709 SL = SM.getSpellingLoc(SL);
4710 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
4711 SM.getSpellingLoc(SR.getEnd()));
4712 }
4713
Anna Zaks13b08572012-08-08 21:42:23 +00004714 // Check if the destination is an array (rather than a pointer to an array).
4715 QualType DstTy = DstArg->getType();
4716 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
4717 Context);
4718 if (!isKnownSizeArray) {
4719 if (PatternType == 1)
4720 Diag(SL, diag::warn_strncat_wrong_size) << SR;
4721 else
4722 Diag(SL, diag::warn_strncat_src_size) << SR;
4723 return;
4724 }
4725
Anna Zaks314cd092012-02-01 19:08:57 +00004726 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00004727 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004728 else
Anna Zaks5069aa32012-02-03 01:27:37 +00004729 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004730
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004731 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00004732 llvm::raw_svector_ostream OS(sizeString);
4733 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004734 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00004735 OS << ") - ";
4736 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004737 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00004738 OS << ") - 1";
4739
Anna Zaks5069aa32012-02-03 01:27:37 +00004740 Diag(SL, diag::note_strncat_wrong_size)
4741 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00004742}
4743
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004744//===--- CHECK: Return Address of Stack Variable --------------------------===//
4745
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004746static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4747 Decl *ParentDecl);
4748static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
4749 Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004750
4751/// CheckReturnStackAddr - Check if a return statement returns the address
4752/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004753static void
4754CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
4755 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00004756
Craig Topperc3ec1492014-05-26 06:22:03 +00004757 Expr *stackE = nullptr;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004758 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004759
4760 // Perform checking for returned stack addresses, local blocks,
4761 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00004762 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004763 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004764 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00004765 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004766 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004767 }
4768
Craig Topperc3ec1492014-05-26 06:22:03 +00004769 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004770 return; // Nothing suspicious was found.
4771
4772 SourceLocation diagLoc;
4773 SourceRange diagRange;
4774 if (refVars.empty()) {
4775 diagLoc = stackE->getLocStart();
4776 diagRange = stackE->getSourceRange();
4777 } else {
4778 // We followed through a reference variable. 'stackE' contains the
4779 // problematic expression but we will warn at the return statement pointing
4780 // at the reference variable. We will later display the "trail" of
4781 // reference variables using notes.
4782 diagLoc = refVars[0]->getLocStart();
4783 diagRange = refVars[0]->getSourceRange();
4784 }
4785
4786 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004787 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004788 : diag::warn_ret_stack_addr)
4789 << DR->getDecl()->getDeclName() << diagRange;
4790 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004791 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004792 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004793 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004794 } else { // local temporary.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004795 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
4796 : diag::warn_ret_local_temp_addr)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004797 << diagRange;
4798 }
4799
4800 // Display the "trail" of reference variables that we followed until we
4801 // found the problematic expression using notes.
4802 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
4803 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
4804 // If this var binds to another reference var, show the range of the next
4805 // var, otherwise the var binds to the problematic expression, in which case
4806 // show the range of the expression.
4807 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
4808 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004809 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
4810 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004811 }
4812}
4813
4814/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
4815/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004816/// to a location on the stack, a local block, an address of a label, or a
4817/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004818/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004819/// encounter a subexpression that (1) clearly does not lead to one of the
4820/// above problematic expressions (2) is something we cannot determine leads to
4821/// a problematic expression based on such local checking.
4822///
4823/// Both EvalAddr and EvalVal follow through reference variables to evaluate
4824/// the expression that they point to. Such variables are added to the
4825/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004826///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00004827/// EvalAddr processes expressions that are pointers that are used as
4828/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004829/// At the base case of the recursion is a check for the above problematic
4830/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004831///
4832/// This implementation handles:
4833///
4834/// * pointer-to-pointer casts
4835/// * implicit conversions from array references to pointers
4836/// * taking the address of fields
4837/// * arbitrary interplay between "&" and "*" operators
4838/// * pointer arithmetic from an address of a stack variable
4839/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004840static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4841 Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004842 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00004843 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004844
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004845 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00004846 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004847 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004848 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00004849 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00004850
Peter Collingbourne91147592011-04-15 00:35:48 +00004851 E = E->IgnoreParens();
4852
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004853 // Our "symbolic interpreter" is just a dispatch off the currently
4854 // viewed AST node. We then recursively traverse the AST by calling
4855 // EvalAddr and EvalVal appropriately.
4856 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004857 case Stmt::DeclRefExprClass: {
4858 DeclRefExpr *DR = cast<DeclRefExpr>(E);
4859
Richard Smith40f08eb2014-01-30 22:05:38 +00004860 // If we leave the immediate function, the lifetime isn't about to end.
4861 if (DR->refersToEnclosingLocal())
Craig Topperc3ec1492014-05-26 06:22:03 +00004862 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00004863
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004864 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
4865 // If this is a reference variable, follow through to the expression that
4866 // it points to.
4867 if (V->hasLocalStorage() &&
4868 V->getType()->isReferenceType() && V->hasInit()) {
4869 // Add the reference variable to the "trail".
4870 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004871 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004872 }
4873
Craig Topperc3ec1492014-05-26 06:22:03 +00004874 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004875 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004876
Chris Lattner934edb22007-12-28 05:31:15 +00004877 case Stmt::UnaryOperatorClass: {
4878 // The only unary operator that make sense to handle here
4879 // is AddrOf. All others don't make sense as pointers.
4880 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004881
John McCalle3027922010-08-25 11:45:40 +00004882 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004883 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004884 else
Craig Topperc3ec1492014-05-26 06:22:03 +00004885 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004886 }
Mike Stump11289f42009-09-09 15:08:12 +00004887
Chris Lattner934edb22007-12-28 05:31:15 +00004888 case Stmt::BinaryOperatorClass: {
4889 // Handle pointer arithmetic. All other binary operators are not valid
4890 // in this context.
4891 BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00004892 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00004893
John McCalle3027922010-08-25 11:45:40 +00004894 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00004895 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004896
Chris Lattner934edb22007-12-28 05:31:15 +00004897 Expr *Base = B->getLHS();
4898
4899 // Determine which argument is the real pointer base. It could be
4900 // the RHS argument instead of the LHS.
4901 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00004902
Chris Lattner934edb22007-12-28 05:31:15 +00004903 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004904 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004905 }
Steve Naroff2752a172008-09-10 19:17:48 +00004906
Chris Lattner934edb22007-12-28 05:31:15 +00004907 // For conditional operators we need to see if either the LHS or RHS are
4908 // valid DeclRefExpr*s. If one of them is valid, we return it.
4909 case Stmt::ConditionalOperatorClass: {
4910 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004911
Chris Lattner934edb22007-12-28 05:31:15 +00004912 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004913 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
4914 if (Expr *LHSExpr = C->getLHS()) {
4915 // In C++, we can have a throw-expression, which has 'void' type.
4916 if (!LHSExpr->getType()->isVoidType())
4917 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004918 return LHS;
4919 }
Chris Lattner934edb22007-12-28 05:31:15 +00004920
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004921 // In C++, we can have a throw-expression, which has 'void' type.
4922 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00004923 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004924
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004925 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004926 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004927
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004928 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00004929 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004930 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00004931 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004932
4933 case Stmt::AddrLabelExprClass:
4934 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00004935
John McCall28fc7092011-11-10 05:35:25 +00004936 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004937 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
4938 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00004939
Ted Kremenekc3b4c522008-08-07 00:49:01 +00004940 // For casts, we need to handle conversions from arrays to
4941 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00004942 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00004943 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00004944 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00004945 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00004946 case Stmt::CXXStaticCastExprClass:
4947 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00004948 case Stmt::CXXConstCastExprClass:
4949 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8195ad72012-02-23 23:04:32 +00004950 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
4951 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00004952 case CK_LValueToRValue:
4953 case CK_NoOp:
4954 case CK_BaseToDerived:
4955 case CK_DerivedToBase:
4956 case CK_UncheckedDerivedToBase:
4957 case CK_Dynamic:
4958 case CK_CPointerToObjCPointerCast:
4959 case CK_BlockPointerToObjCPointerCast:
4960 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004961 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00004962
4963 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004964 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00004965
Richard Trieudadefde2014-07-02 04:39:38 +00004966 case CK_BitCast:
4967 if (SubExpr->getType()->isAnyPointerType() ||
4968 SubExpr->getType()->isBlockPointerType() ||
4969 SubExpr->getType()->isObjCQualifiedIdType())
4970 return EvalAddr(SubExpr, refVars, ParentDecl);
4971 else
4972 return nullptr;
4973
Eli Friedman8195ad72012-02-23 23:04:32 +00004974 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00004975 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00004976 }
Chris Lattner934edb22007-12-28 05:31:15 +00004977 }
Mike Stump11289f42009-09-09 15:08:12 +00004978
Douglas Gregorfe314812011-06-21 17:03:29 +00004979 case Stmt::MaterializeTemporaryExprClass:
4980 if (Expr *Result = EvalAddr(
4981 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004982 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00004983 return Result;
4984
4985 return E;
4986
Chris Lattner934edb22007-12-28 05:31:15 +00004987 // Everything else: we simply don't reason about them.
4988 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00004989 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00004990 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004991}
Mike Stump11289f42009-09-09 15:08:12 +00004992
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004993
4994/// EvalVal - This function is complements EvalAddr in the mutual recursion.
4995/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004996static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4997 Decl *ParentDecl) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004998do {
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00004999 // We should only be called for evaluating non-pointer expressions, or
5000 // expressions with a pointer type that are not used as references but instead
5001 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00005002
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005003 // Our "symbolic interpreter" is just a dispatch off the currently
5004 // viewed AST node. We then recursively traverse the AST by calling
5005 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00005006
5007 E = E->IgnoreParens();
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005008 switch (E->getStmtClass()) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005009 case Stmt::ImplicitCastExprClass: {
5010 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall2536c6d2010-08-25 10:28:54 +00005011 if (IE->getValueKind() == VK_LValue) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005012 E = IE->getSubExpr();
5013 continue;
5014 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005015 return nullptr;
Ted Kremenekb7861562010-08-04 20:01:07 +00005016 }
5017
John McCall28fc7092011-11-10 05:35:25 +00005018 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005019 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00005020
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005021 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005022 // When we hit a DeclRefExpr we are looking at code that refers to a
5023 // variable's name. If it's not a reference variable we check if it has
5024 // local storage within the function, and if so, return the expression.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005025 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005026
Richard Smith40f08eb2014-01-30 22:05:38 +00005027 // If we leave the immediate function, the lifetime isn't about to end.
5028 if (DR->refersToEnclosingLocal())
Craig Topperc3ec1492014-05-26 06:22:03 +00005029 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00005030
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005031 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
5032 // Check if it refers to itself, e.g. "int& i = i;".
5033 if (V == ParentDecl)
5034 return DR;
5035
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005036 if (V->hasLocalStorage()) {
5037 if (!V->getType()->isReferenceType())
5038 return DR;
5039
5040 // Reference variable, follow through to the expression that
5041 // it points to.
5042 if (V->hasInit()) {
5043 // Add the reference variable to the "trail".
5044 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005045 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005046 }
5047 }
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005048 }
Mike Stump11289f42009-09-09 15:08:12 +00005049
Craig Topperc3ec1492014-05-26 06:22:03 +00005050 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005051 }
Mike Stump11289f42009-09-09 15:08:12 +00005052
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005053 case Stmt::UnaryOperatorClass: {
5054 // The only unary operator that make sense to handle here
5055 // is Deref. All others don't resolve to a "name." This includes
5056 // handling all sorts of rvalues passed to a unary operator.
5057 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005058
John McCalle3027922010-08-25 11:45:40 +00005059 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005060 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005061
Craig Topperc3ec1492014-05-26 06:22:03 +00005062 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005063 }
Mike Stump11289f42009-09-09 15:08:12 +00005064
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005065 case Stmt::ArraySubscriptExprClass: {
5066 // Array subscripts are potential references to data on the stack. We
5067 // retrieve the DeclRefExpr* for the array variable if it indeed
5068 // has local storage.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005069 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005070 }
Mike Stump11289f42009-09-09 15:08:12 +00005071
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005072 case Stmt::ConditionalOperatorClass: {
5073 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005074 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005075 ConditionalOperator *C = cast<ConditionalOperator>(E);
5076
Anders Carlsson801c5c72007-11-30 19:04:31 +00005077 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005078 if (Expr *LHSExpr = C->getLHS()) {
5079 // In C++, we can have a throw-expression, which has 'void' type.
5080 if (!LHSExpr->getType()->isVoidType())
5081 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
5082 return LHS;
5083 }
5084
5085 // In C++, we can have a throw-expression, which has 'void' type.
5086 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005087 return nullptr;
Anders Carlsson801c5c72007-11-30 19:04:31 +00005088
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005089 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005090 }
Mike Stump11289f42009-09-09 15:08:12 +00005091
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005092 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00005093 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005094 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005095
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005096 // Check for indirect access. We only want direct field accesses.
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005097 if (M->isArrow())
Craig Topperc3ec1492014-05-26 06:22:03 +00005098 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005099
5100 // Check whether the member type is itself a reference, in which case
5101 // we're not going to refer to the member, but to what the member refers to.
5102 if (M->getMemberDecl()->getType()->isReferenceType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005103 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005104
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005105 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005106 }
Mike Stump11289f42009-09-09 15:08:12 +00005107
Douglas Gregorfe314812011-06-21 17:03:29 +00005108 case Stmt::MaterializeTemporaryExprClass:
5109 if (Expr *Result = EvalVal(
5110 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005111 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00005112 return Result;
5113
5114 return E;
5115
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005116 default:
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005117 // Check that we don't return or take the address of a reference to a
5118 // temporary. This is only useful in C++.
5119 if (!E->isTypeDependent() && E->isRValue())
5120 return E;
5121
5122 // Everything else: we simply don't reason about them.
Craig Topperc3ec1492014-05-26 06:22:03 +00005123 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005124 }
Ted Kremenekb7861562010-08-04 20:01:07 +00005125} while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005126}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005127
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005128void
5129Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
5130 SourceLocation ReturnLoc,
5131 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00005132 const AttrVec *Attrs,
5133 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005134 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
5135
5136 // Check if the return value is null but should not be.
Benjamin Kramerae852a62014-02-23 14:34:50 +00005137 if (Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs) &&
5138 CheckNonNullExpr(*this, RetValExp))
5139 Diag(ReturnLoc, diag::warn_null_ret)
5140 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00005141
5142 // C++11 [basic.stc.dynamic.allocation]p4:
5143 // If an allocation function declared with a non-throwing
5144 // exception-specification fails to allocate storage, it shall return
5145 // a null pointer. Any other allocation function that fails to allocate
5146 // storage shall indicate failure only by throwing an exception [...]
5147 if (FD) {
5148 OverloadedOperatorKind Op = FD->getOverloadedOperator();
5149 if (Op == OO_New || Op == OO_Array_New) {
5150 const FunctionProtoType *Proto
5151 = FD->getType()->castAs<FunctionProtoType>();
5152 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
5153 CheckNonNullExpr(*this, RetValExp))
5154 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
5155 << FD << getLangOpts().CPlusPlus11;
5156 }
5157 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005158}
5159
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005160//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
5161
5162/// Check for comparisons of floating point operands using != and ==.
5163/// Issue a warning if these are no self-comparisons, as they are not likely
5164/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00005165void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00005166 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
5167 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005168
5169 // Special case: check for x == x (which is OK).
5170 // Do not emit warnings for such cases.
5171 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
5172 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
5173 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00005174 return;
Mike Stump11289f42009-09-09 15:08:12 +00005175
5176
Ted Kremenekeda40e22007-11-29 00:59:04 +00005177 // Special case: check for comparisons against literals that can be exactly
5178 // represented by APFloat. In such cases, do not emit a warning. This
5179 // is a heuristic: often comparison against such literals are used to
5180 // detect if a value in a variable has not changed. This clearly can
5181 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00005182 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
5183 if (FLL->isExact())
5184 return;
5185 } else
5186 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
5187 if (FLR->isExact())
5188 return;
Mike Stump11289f42009-09-09 15:08:12 +00005189
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005190 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00005191 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00005192 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00005193 return;
Mike Stump11289f42009-09-09 15:08:12 +00005194
David Blaikie1f4ff152012-07-16 20:47:22 +00005195 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00005196 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00005197 return;
Mike Stump11289f42009-09-09 15:08:12 +00005198
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005199 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00005200 Diag(Loc, diag::warn_floatingpoint_eq)
5201 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005202}
John McCallca01b222010-01-04 23:21:16 +00005203
John McCall70aa5392010-01-06 05:24:50 +00005204//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
5205//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00005206
John McCall70aa5392010-01-06 05:24:50 +00005207namespace {
John McCallca01b222010-01-04 23:21:16 +00005208
John McCall70aa5392010-01-06 05:24:50 +00005209/// Structure recording the 'active' range of an integer-valued
5210/// expression.
5211struct IntRange {
5212 /// The number of bits active in the int.
5213 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00005214
John McCall70aa5392010-01-06 05:24:50 +00005215 /// True if the int is known not to have negative values.
5216 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00005217
John McCall70aa5392010-01-06 05:24:50 +00005218 IntRange(unsigned Width, bool NonNegative)
5219 : Width(Width), NonNegative(NonNegative)
5220 {}
John McCallca01b222010-01-04 23:21:16 +00005221
John McCall817d4af2010-11-10 23:38:19 +00005222 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00005223 static IntRange forBoolType() {
5224 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00005225 }
5226
John McCall817d4af2010-11-10 23:38:19 +00005227 /// Returns the range of an opaque value of the given integral type.
5228 static IntRange forValueOfType(ASTContext &C, QualType T) {
5229 return forValueOfCanonicalType(C,
5230 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00005231 }
5232
John McCall817d4af2010-11-10 23:38:19 +00005233 /// Returns the range of an opaque value of a canonical integral type.
5234 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00005235 assert(T->isCanonicalUnqualified());
5236
5237 if (const VectorType *VT = dyn_cast<VectorType>(T))
5238 T = VT->getElementType().getTypePtr();
5239 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5240 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005241 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5242 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00005243
David Majnemer6a426652013-06-07 22:07:20 +00005244 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00005245 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00005246 EnumDecl *Enum = ET->getDecl();
5247 if (!Enum->isCompleteDefinition())
5248 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00005249
David Majnemer6a426652013-06-07 22:07:20 +00005250 unsigned NumPositive = Enum->getNumPositiveBits();
5251 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00005252
David Majnemer6a426652013-06-07 22:07:20 +00005253 if (NumNegative == 0)
5254 return IntRange(NumPositive, true/*NonNegative*/);
5255 else
5256 return IntRange(std::max(NumPositive + 1, NumNegative),
5257 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00005258 }
John McCall70aa5392010-01-06 05:24:50 +00005259
5260 const BuiltinType *BT = cast<BuiltinType>(T);
5261 assert(BT->isInteger());
5262
5263 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5264 }
5265
John McCall817d4af2010-11-10 23:38:19 +00005266 /// Returns the "target" range of a canonical integral type, i.e.
5267 /// the range of values expressible in the type.
5268 ///
5269 /// This matches forValueOfCanonicalType except that enums have the
5270 /// full range of their type, not the range of their enumerators.
5271 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
5272 assert(T->isCanonicalUnqualified());
5273
5274 if (const VectorType *VT = dyn_cast<VectorType>(T))
5275 T = VT->getElementType().getTypePtr();
5276 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5277 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005278 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5279 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00005280 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00005281 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00005282
5283 const BuiltinType *BT = cast<BuiltinType>(T);
5284 assert(BT->isInteger());
5285
5286 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5287 }
5288
5289 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00005290 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00005291 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00005292 L.NonNegative && R.NonNegative);
5293 }
5294
John McCall817d4af2010-11-10 23:38:19 +00005295 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00005296 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00005297 return IntRange(std::min(L.Width, R.Width),
5298 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00005299 }
5300};
5301
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005302static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
5303 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005304 if (value.isSigned() && value.isNegative())
5305 return IntRange(value.getMinSignedBits(), false);
5306
5307 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00005308 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00005309
5310 // isNonNegative() just checks the sign bit without considering
5311 // signedness.
5312 return IntRange(value.getActiveBits(), true);
5313}
5314
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005315static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
5316 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005317 if (result.isInt())
5318 return GetValueRange(C, result.getInt(), MaxWidth);
5319
5320 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00005321 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
5322 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
5323 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
5324 R = IntRange::join(R, El);
5325 }
John McCall70aa5392010-01-06 05:24:50 +00005326 return R;
5327 }
5328
5329 if (result.isComplexInt()) {
5330 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
5331 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
5332 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00005333 }
5334
5335 // This can happen with lossless casts to intptr_t of "based" lvalues.
5336 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00005337 // FIXME: The only reason we need to pass the type in here is to get
5338 // the sign right on this one case. It would be nice if APValue
5339 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005340 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00005341 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00005342}
John McCall70aa5392010-01-06 05:24:50 +00005343
Eli Friedmane6d33952013-07-08 20:20:06 +00005344static QualType GetExprType(Expr *E) {
5345 QualType Ty = E->getType();
5346 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
5347 Ty = AtomicRHS->getValueType();
5348 return Ty;
5349}
5350
John McCall70aa5392010-01-06 05:24:50 +00005351/// Pseudo-evaluate the given integer expression, estimating the
5352/// range of values it might take.
5353///
5354/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005355static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005356 E = E->IgnoreParens();
5357
5358 // Try a full evaluation first.
5359 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00005360 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00005361 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00005362
5363 // I think we only want to look through implicit casts here; if the
5364 // user has an explicit widening cast, we should treat the value as
5365 // being of the new, wider type.
5366 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00005367 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00005368 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
5369
Eli Friedmane6d33952013-07-08 20:20:06 +00005370 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00005371
John McCalle3027922010-08-25 11:45:40 +00005372 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall2ce81ad2010-01-06 22:07:33 +00005373
John McCall70aa5392010-01-06 05:24:50 +00005374 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00005375 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00005376 return OutputTypeRange;
5377
5378 IntRange SubRange
5379 = GetExprRange(C, CE->getSubExpr(),
5380 std::min(MaxWidth, OutputTypeRange.Width));
5381
5382 // Bail out if the subexpr's range is as wide as the cast type.
5383 if (SubRange.Width >= OutputTypeRange.Width)
5384 return OutputTypeRange;
5385
5386 // Otherwise, we take the smaller width, and we're non-negative if
5387 // either the output type or the subexpr is.
5388 return IntRange(SubRange.Width,
5389 SubRange.NonNegative || OutputTypeRange.NonNegative);
5390 }
5391
5392 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5393 // If we can fold the condition, just take that operand.
5394 bool CondResult;
5395 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
5396 return GetExprRange(C, CondResult ? CO->getTrueExpr()
5397 : CO->getFalseExpr(),
5398 MaxWidth);
5399
5400 // Otherwise, conservatively merge.
5401 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
5402 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
5403 return IntRange::join(L, R);
5404 }
5405
5406 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5407 switch (BO->getOpcode()) {
5408
5409 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00005410 case BO_LAnd:
5411 case BO_LOr:
5412 case BO_LT:
5413 case BO_GT:
5414 case BO_LE:
5415 case BO_GE:
5416 case BO_EQ:
5417 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00005418 return IntRange::forBoolType();
5419
John McCallc3688382011-07-13 06:35:24 +00005420 // The type of the assignments is the type of the LHS, so the RHS
5421 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00005422 case BO_MulAssign:
5423 case BO_DivAssign:
5424 case BO_RemAssign:
5425 case BO_AddAssign:
5426 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00005427 case BO_XorAssign:
5428 case BO_OrAssign:
5429 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00005430 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00005431
John McCallc3688382011-07-13 06:35:24 +00005432 // Simple assignments just pass through the RHS, which will have
5433 // been coerced to the LHS type.
5434 case BO_Assign:
5435 // TODO: bitfields?
5436 return GetExprRange(C, BO->getRHS(), MaxWidth);
5437
John McCall70aa5392010-01-06 05:24:50 +00005438 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005439 case BO_PtrMemD:
5440 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00005441 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005442
John McCall2ce81ad2010-01-06 22:07:33 +00005443 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00005444 case BO_And:
5445 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00005446 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
5447 GetExprRange(C, BO->getRHS(), MaxWidth));
5448
John McCall70aa5392010-01-06 05:24:50 +00005449 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00005450 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00005451 // ...except that we want to treat '1 << (blah)' as logically
5452 // positive. It's an important idiom.
5453 if (IntegerLiteral *I
5454 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
5455 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005456 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00005457 return IntRange(R.Width, /*NonNegative*/ true);
5458 }
5459 }
5460 // fallthrough
5461
John McCalle3027922010-08-25 11:45:40 +00005462 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00005463 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005464
John McCall2ce81ad2010-01-06 22:07:33 +00005465 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00005466 case BO_Shr:
5467 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00005468 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5469
5470 // If the shift amount is a positive constant, drop the width by
5471 // that much.
5472 llvm::APSInt shift;
5473 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
5474 shift.isNonNegative()) {
5475 unsigned zext = shift.getZExtValue();
5476 if (zext >= L.Width)
5477 L.Width = (L.NonNegative ? 0 : 1);
5478 else
5479 L.Width -= zext;
5480 }
5481
5482 return L;
5483 }
5484
5485 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00005486 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00005487 return GetExprRange(C, BO->getRHS(), MaxWidth);
5488
John McCall2ce81ad2010-01-06 22:07:33 +00005489 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00005490 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00005491 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00005492 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005493 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005494
John McCall51431812011-07-14 22:39:48 +00005495 // The width of a division result is mostly determined by the size
5496 // of the LHS.
5497 case BO_Div: {
5498 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005499 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005500 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5501
5502 // If the divisor is constant, use that.
5503 llvm::APSInt divisor;
5504 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
5505 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
5506 if (log2 >= L.Width)
5507 L.Width = (L.NonNegative ? 0 : 1);
5508 else
5509 L.Width = std::min(L.Width - log2, MaxWidth);
5510 return L;
5511 }
5512
5513 // Otherwise, just use the LHS's width.
5514 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5515 return IntRange(L.Width, L.NonNegative && R.NonNegative);
5516 }
5517
5518 // The result of a remainder can't be larger than the result of
5519 // either side.
5520 case BO_Rem: {
5521 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005522 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005523 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5524 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5525
5526 IntRange meet = IntRange::meet(L, R);
5527 meet.Width = std::min(meet.Width, MaxWidth);
5528 return meet;
5529 }
5530
5531 // The default behavior is okay for these.
5532 case BO_Mul:
5533 case BO_Add:
5534 case BO_Xor:
5535 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00005536 break;
5537 }
5538
John McCall51431812011-07-14 22:39:48 +00005539 // The default case is to treat the operation as if it were closed
5540 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00005541 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5542 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
5543 return IntRange::join(L, R);
5544 }
5545
5546 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5547 switch (UO->getOpcode()) {
5548 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00005549 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00005550 return IntRange::forBoolType();
5551
5552 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005553 case UO_Deref:
5554 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00005555 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005556
5557 default:
5558 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
5559 }
5560 }
5561
Ted Kremeneka553fbf2013-10-14 18:55:27 +00005562 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5563 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
5564
John McCalld25db7e2013-05-06 21:39:12 +00005565 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00005566 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00005567 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00005568
Eli Friedmane6d33952013-07-08 20:20:06 +00005569 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005570}
John McCall263a48b2010-01-04 23:31:57 +00005571
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005572static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005573 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00005574}
5575
John McCall263a48b2010-01-04 23:31:57 +00005576/// Checks whether the given value, which currently has the given
5577/// source semantics, has the same value when coerced through the
5578/// target semantics.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005579static bool IsSameFloatAfterCast(const llvm::APFloat &value,
5580 const llvm::fltSemantics &Src,
5581 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005582 llvm::APFloat truncated = value;
5583
5584 bool ignored;
5585 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
5586 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
5587
5588 return truncated.bitwiseIsEqual(value);
5589}
5590
5591/// Checks whether the given value, which currently has the given
5592/// source semantics, has the same value when coerced through the
5593/// target semantics.
5594///
5595/// The value might be a vector of floats (or a complex number).
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005596static bool IsSameFloatAfterCast(const APValue &value,
5597 const llvm::fltSemantics &Src,
5598 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005599 if (value.isFloat())
5600 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
5601
5602 if (value.isVector()) {
5603 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
5604 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
5605 return false;
5606 return true;
5607 }
5608
5609 assert(value.isComplexFloat());
5610 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
5611 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
5612}
5613
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005614static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005615
Ted Kremenek6274be42010-09-23 21:43:44 +00005616static bool IsZero(Sema &S, Expr *E) {
5617 // Suppress cases where we are comparing against an enum constant.
5618 if (const DeclRefExpr *DR =
5619 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
5620 if (isa<EnumConstantDecl>(DR->getDecl()))
5621 return false;
5622
5623 // Suppress cases where the '0' value is expanded from a macro.
5624 if (E->getLocStart().isMacroID())
5625 return false;
5626
John McCallcc7e5bf2010-05-06 08:58:33 +00005627 llvm::APSInt Value;
5628 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
5629}
5630
John McCall2551c1b2010-10-06 00:25:24 +00005631static bool HasEnumType(Expr *E) {
5632 // Strip off implicit integral promotions.
5633 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005634 if (ICE->getCastKind() != CK_IntegralCast &&
5635 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00005636 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005637 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00005638 }
5639
5640 return E->getType()->isEnumeralType();
5641}
5642
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005643static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00005644 // Disable warning in template instantiations.
5645 if (!S.ActiveTemplateInstantiations.empty())
5646 return;
5647
John McCalle3027922010-08-25 11:45:40 +00005648 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00005649 if (E->isValueDependent())
5650 return;
5651
John McCalle3027922010-08-25 11:45:40 +00005652 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005653 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005654 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005655 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005656 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005657 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005658 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005659 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005660 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005661 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005662 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005663 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005664 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005665 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005666 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005667 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5668 }
5669}
5670
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005671static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005672 Expr *Constant, Expr *Other,
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005673 llvm::APSInt Value,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005674 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00005675 // Disable warning in template instantiations.
5676 if (!S.ActiveTemplateInstantiations.empty())
5677 return;
5678
Richard Trieu0f097742014-04-04 04:13:47 +00005679 // TODO: Investigate using GetExprRange() to get tighter bounds
5680 // on the bit ranges.
5681 QualType OtherT = Other->getType();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005682 if (const AtomicType *AT = dyn_cast<AtomicType>(OtherT))
5683 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00005684 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
5685 unsigned OtherWidth = OtherRange.Width;
5686
5687 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
5688
Richard Trieu560910c2012-11-14 22:50:24 +00005689 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00005690 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00005691 return;
5692
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005693 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00005694 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00005695
Richard Trieu0f097742014-04-04 04:13:47 +00005696 // Used for diagnostic printout.
5697 enum {
5698 LiteralConstant = 0,
5699 CXXBoolLiteralTrue,
5700 CXXBoolLiteralFalse
5701 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00005702
Richard Trieu0f097742014-04-04 04:13:47 +00005703 if (!OtherIsBooleanType) {
5704 QualType ConstantT = Constant->getType();
5705 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00005706
Richard Trieu0f097742014-04-04 04:13:47 +00005707 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
5708 return;
5709 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
5710 "comparison with non-integer type");
5711
5712 bool ConstantSigned = ConstantT->isSignedIntegerType();
5713 bool CommonSigned = CommonT->isSignedIntegerType();
5714
5715 bool EqualityOnly = false;
5716
5717 if (CommonSigned) {
5718 // The common type is signed, therefore no signed to unsigned conversion.
5719 if (!OtherRange.NonNegative) {
5720 // Check that the constant is representable in type OtherT.
5721 if (ConstantSigned) {
5722 if (OtherWidth >= Value.getMinSignedBits())
5723 return;
5724 } else { // !ConstantSigned
5725 if (OtherWidth >= Value.getActiveBits() + 1)
5726 return;
5727 }
5728 } else { // !OtherSigned
5729 // Check that the constant is representable in type OtherT.
5730 // Negative values are out of range.
5731 if (ConstantSigned) {
5732 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
5733 return;
5734 } else { // !ConstantSigned
5735 if (OtherWidth >= Value.getActiveBits())
5736 return;
5737 }
Richard Trieu560910c2012-11-14 22:50:24 +00005738 }
Richard Trieu0f097742014-04-04 04:13:47 +00005739 } else { // !CommonSigned
5740 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00005741 if (OtherWidth >= Value.getActiveBits())
5742 return;
Craig Toppercf360162014-06-18 05:13:11 +00005743 } else { // OtherSigned
5744 assert(!ConstantSigned &&
5745 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00005746 // Check to see if the constant is representable in OtherT.
5747 if (OtherWidth > Value.getActiveBits())
5748 return;
5749 // Check to see if the constant is equivalent to a negative value
5750 // cast to CommonT.
5751 if (S.Context.getIntWidth(ConstantT) ==
5752 S.Context.getIntWidth(CommonT) &&
5753 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
5754 return;
5755 // The constant value rests between values that OtherT can represent
5756 // after conversion. Relational comparison still works, but equality
5757 // comparisons will be tautological.
5758 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00005759 }
5760 }
Richard Trieu0f097742014-04-04 04:13:47 +00005761
5762 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
5763
5764 if (op == BO_EQ || op == BO_NE) {
5765 IsTrue = op == BO_NE;
5766 } else if (EqualityOnly) {
5767 return;
5768 } else if (RhsConstant) {
5769 if (op == BO_GT || op == BO_GE)
5770 IsTrue = !PositiveConstant;
5771 else // op == BO_LT || op == BO_LE
5772 IsTrue = PositiveConstant;
5773 } else {
5774 if (op == BO_LT || op == BO_LE)
5775 IsTrue = !PositiveConstant;
5776 else // op == BO_GT || op == BO_GE
5777 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00005778 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005779 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00005780 // Other isKnownToHaveBooleanValue
5781 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
5782 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
5783 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
5784
5785 static const struct LinkedConditions {
5786 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
5787 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
5788 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
5789 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
5790 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
5791 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
5792
5793 } TruthTable = {
5794 // Constant on LHS. | Constant on RHS. |
5795 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
5796 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
5797 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
5798 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
5799 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
5800 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
5801 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
5802 };
5803
5804 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
5805
5806 enum ConstantValue ConstVal = Zero;
5807 if (Value.isUnsigned() || Value.isNonNegative()) {
5808 if (Value == 0) {
5809 LiteralOrBoolConstant =
5810 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
5811 ConstVal = Zero;
5812 } else if (Value == 1) {
5813 LiteralOrBoolConstant =
5814 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
5815 ConstVal = One;
5816 } else {
5817 LiteralOrBoolConstant = LiteralConstant;
5818 ConstVal = GT_One;
5819 }
5820 } else {
5821 ConstVal = LT_Zero;
5822 }
5823
5824 CompareBoolWithConstantResult CmpRes;
5825
5826 switch (op) {
5827 case BO_LT:
5828 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
5829 break;
5830 case BO_GT:
5831 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
5832 break;
5833 case BO_LE:
5834 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
5835 break;
5836 case BO_GE:
5837 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
5838 break;
5839 case BO_EQ:
5840 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
5841 break;
5842 case BO_NE:
5843 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
5844 break;
5845 default:
5846 CmpRes = Unkwn;
5847 break;
5848 }
5849
5850 if (CmpRes == AFals) {
5851 IsTrue = false;
5852 } else if (CmpRes == ATrue) {
5853 IsTrue = true;
5854 } else {
5855 return;
5856 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005857 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005858
5859 // If this is a comparison to an enum constant, include that
5860 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00005861 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005862 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
5863 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
5864
5865 SmallString<64> PrettySourceValue;
5866 llvm::raw_svector_ostream OS(PrettySourceValue);
5867 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00005868 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005869 else
5870 OS << Value;
5871
Richard Trieu0f097742014-04-04 04:13:47 +00005872 S.DiagRuntimeBehavior(
5873 E->getOperatorLoc(), E,
5874 S.PDiag(diag::warn_out_of_range_compare)
5875 << OS.str() << LiteralOrBoolConstant
5876 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
5877 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005878}
5879
John McCallcc7e5bf2010-05-06 08:58:33 +00005880/// Analyze the operands of the given comparison. Implements the
5881/// fallback case from AnalyzeComparison.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005882static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00005883 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5884 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00005885}
John McCall263a48b2010-01-04 23:31:57 +00005886
John McCallca01b222010-01-04 23:21:16 +00005887/// \brief Implements -Wsign-compare.
5888///
Richard Trieu82402a02011-09-15 21:56:47 +00005889/// \param E the binary operator to check for warnings
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005890static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005891 // The type the comparison is being performed in.
5892 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00005893
5894 // Only analyze comparison operators where both sides have been converted to
5895 // the same type.
5896 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
5897 return AnalyzeImpConvsInComparison(S, E);
5898
5899 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00005900 if (E->isValueDependent())
5901 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005902
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005903 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
5904 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005905
5906 bool IsComparisonConstant = false;
5907
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005908 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005909 // of 'true' or 'false'.
5910 if (T->isIntegralType(S.Context)) {
5911 llvm::APSInt RHSValue;
5912 bool IsRHSIntegralLiteral =
5913 RHS->isIntegerConstantExpr(RHSValue, S.Context);
5914 llvm::APSInt LHSValue;
5915 bool IsLHSIntegralLiteral =
5916 LHS->isIntegerConstantExpr(LHSValue, S.Context);
5917 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
5918 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
5919 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
5920 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
5921 else
5922 IsComparisonConstant =
5923 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005924 } else if (!T->hasUnsignedIntegerRepresentation())
5925 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005926
John McCallcc7e5bf2010-05-06 08:58:33 +00005927 // We don't do anything special if this isn't an unsigned integral
5928 // comparison: we're only interested in integral comparisons, and
5929 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00005930 //
5931 // We also don't care about value-dependent expressions or expressions
5932 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005933 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00005934 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005935
John McCallcc7e5bf2010-05-06 08:58:33 +00005936 // Check to see if one of the (unmodified) operands is of different
5937 // signedness.
5938 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00005939 if (LHS->getType()->hasSignedIntegerRepresentation()) {
5940 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00005941 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00005942 signedOperand = LHS;
5943 unsignedOperand = RHS;
5944 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
5945 signedOperand = RHS;
5946 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00005947 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00005948 CheckTrivialUnsignedComparison(S, E);
5949 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005950 }
5951
John McCallcc7e5bf2010-05-06 08:58:33 +00005952 // Otherwise, calculate the effective range of the signed operand.
5953 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00005954
John McCallcc7e5bf2010-05-06 08:58:33 +00005955 // Go ahead and analyze implicit conversions in the operands. Note
5956 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00005957 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
5958 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00005959
John McCallcc7e5bf2010-05-06 08:58:33 +00005960 // If the signed range is non-negative, -Wsign-compare won't fire,
5961 // but we should still check for comparisons which are always true
5962 // or false.
5963 if (signedRange.NonNegative)
5964 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005965
5966 // For (in)equality comparisons, if the unsigned operand is a
5967 // constant which cannot collide with a overflowed signed operand,
5968 // then reinterpreting the signed operand as unsigned will not
5969 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00005970 if (E->isEqualityOp()) {
5971 unsigned comparisonWidth = S.Context.getIntWidth(T);
5972 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00005973
John McCallcc7e5bf2010-05-06 08:58:33 +00005974 // We should never be unable to prove that the unsigned operand is
5975 // non-negative.
5976 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
5977
5978 if (unsignedRange.Width < comparisonWidth)
5979 return;
5980 }
5981
Douglas Gregorbfb4a212012-05-01 01:53:49 +00005982 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
5983 S.PDiag(diag::warn_mixed_sign_comparison)
5984 << LHS->getType() << RHS->getType()
5985 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00005986}
5987
John McCall1f425642010-11-11 03:21:53 +00005988/// Analyzes an attempt to assign the given value to a bitfield.
5989///
5990/// Returns true if there was something fishy about the attempt.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005991static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
5992 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00005993 assert(Bitfield->isBitField());
5994 if (Bitfield->isInvalidDecl())
5995 return false;
5996
John McCalldeebbcf2010-11-11 05:33:51 +00005997 // White-list bool bitfields.
5998 if (Bitfield->getType()->isBooleanType())
5999 return false;
6000
Douglas Gregor789adec2011-02-04 13:09:01 +00006001 // Ignore value- or type-dependent expressions.
6002 if (Bitfield->getBitWidth()->isValueDependent() ||
6003 Bitfield->getBitWidth()->isTypeDependent() ||
6004 Init->isValueDependent() ||
6005 Init->isTypeDependent())
6006 return false;
6007
John McCall1f425642010-11-11 03:21:53 +00006008 Expr *OriginalInit = Init->IgnoreParenImpCasts();
6009
Richard Smith5fab0c92011-12-28 19:48:30 +00006010 llvm::APSInt Value;
6011 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00006012 return false;
6013
John McCall1f425642010-11-11 03:21:53 +00006014 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00006015 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00006016
6017 if (OriginalWidth <= FieldWidth)
6018 return false;
6019
Eli Friedmanc267a322012-01-26 23:11:39 +00006020 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00006021 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00006022 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00006023
Eli Friedmanc267a322012-01-26 23:11:39 +00006024 // Check whether the stored value is equal to the original value.
6025 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00006026 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00006027 return false;
6028
Eli Friedmanc267a322012-01-26 23:11:39 +00006029 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00006030 // therefore don't strictly fit into a signed bitfield of width 1.
6031 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00006032 return false;
6033
John McCall1f425642010-11-11 03:21:53 +00006034 std::string PrettyValue = Value.toString(10);
6035 std::string PrettyTrunc = TruncatedValue.toString(10);
6036
6037 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
6038 << PrettyValue << PrettyTrunc << OriginalInit->getType()
6039 << Init->getSourceRange();
6040
6041 return true;
6042}
6043
John McCalld2a53122010-11-09 23:24:47 +00006044/// Analyze the given simple or compound assignment for warning-worthy
6045/// operations.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006046static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00006047 // Just recurse on the LHS.
6048 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6049
6050 // We want to recurse on the RHS as normal unless we're assigning to
6051 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00006052 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006053 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00006054 E->getOperatorLoc())) {
6055 // Recurse, ignoring any implicit conversions on the RHS.
6056 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
6057 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00006058 }
6059 }
6060
6061 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
6062}
6063
John McCall263a48b2010-01-04 23:31:57 +00006064/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006065static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00006066 SourceLocation CContext, unsigned diag,
6067 bool pruneControlFlow = false) {
6068 if (pruneControlFlow) {
6069 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6070 S.PDiag(diag)
6071 << SourceType << T << E->getSourceRange()
6072 << SourceRange(CContext));
6073 return;
6074 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00006075 S.Diag(E->getExprLoc(), diag)
6076 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
6077}
6078
Chandler Carruth7f3654f2011-04-05 06:47:57 +00006079/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006080static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00006081 SourceLocation CContext, unsigned diag,
6082 bool pruneControlFlow = false) {
6083 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00006084}
6085
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006086/// Diagnose an implicit cast from a literal expression. Does not warn when the
6087/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00006088void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
6089 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006090 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00006091 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006092 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00006093 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
6094 T->hasUnsignedIntegerRepresentation());
6095 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00006096 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006097 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00006098 return;
6099
Eli Friedman07185912013-08-29 23:44:43 +00006100 // FIXME: Force the precision of the source value down so we don't print
6101 // digits which are usually useless (we don't really care here if we
6102 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
6103 // would automatically print the shortest representation, but it's a bit
6104 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00006105 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00006106 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
6107 precision = (precision * 59 + 195) / 196;
6108 Value.toString(PrettySourceValue, precision);
6109
David Blaikie9b88cc02012-05-15 17:18:27 +00006110 SmallString<16> PrettyTargetValue;
David Blaikie7555b6a2012-05-15 16:56:36 +00006111 if (T->isSpecificBuiltinType(BuiltinType::Bool))
6112 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
6113 else
David Blaikie9b88cc02012-05-15 17:18:27 +00006114 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00006115
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006116 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikie7555b6a2012-05-15 16:56:36 +00006117 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
6118 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00006119}
6120
John McCall18a2c2c2010-11-09 22:22:12 +00006121std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
6122 if (!Range.Width) return "0";
6123
6124 llvm::APSInt ValueInRange = Value;
6125 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00006126 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00006127 return ValueInRange.toString(10);
6128}
6129
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006130static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
6131 if (!isa<ImplicitCastExpr>(Ex))
6132 return false;
6133
6134 Expr *InnerE = Ex->IgnoreParenImpCasts();
6135 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
6136 const Type *Source =
6137 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6138 if (Target->isDependentType())
6139 return false;
6140
6141 const BuiltinType *FloatCandidateBT =
6142 dyn_cast<BuiltinType>(ToBool ? Source : Target);
6143 const Type *BoolCandidateType = ToBool ? Target : Source;
6144
6145 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
6146 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
6147}
6148
6149void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
6150 SourceLocation CC) {
6151 unsigned NumArgs = TheCall->getNumArgs();
6152 for (unsigned i = 0; i < NumArgs; ++i) {
6153 Expr *CurrA = TheCall->getArg(i);
6154 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
6155 continue;
6156
6157 bool IsSwapped = ((i > 0) &&
6158 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
6159 IsSwapped |= ((i < (NumArgs - 1)) &&
6160 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
6161 if (IsSwapped) {
6162 // Warn on this floating-point to bool conversion.
6163 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
6164 CurrA->getType(), CC,
6165 diag::warn_impcast_floating_point_to_bool);
6166 }
6167 }
6168}
6169
John McCallcc7e5bf2010-05-06 08:58:33 +00006170void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00006171 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006172 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00006173
John McCallcc7e5bf2010-05-06 08:58:33 +00006174 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
6175 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
6176 if (Source == Target) return;
6177 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00006178
Chandler Carruthc22845a2011-07-26 05:40:03 +00006179 // If the conversion context location is invalid don't complain. We also
6180 // don't want to emit a warning if the issue occurs from the expansion of
6181 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
6182 // delay this check as long as possible. Once we detect we are in that
6183 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006184 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00006185 return;
6186
Richard Trieu021baa32011-09-23 20:10:00 +00006187 // Diagnose implicit casts to bool.
6188 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
6189 if (isa<StringLiteral>(E))
6190 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00006191 // and expressions, for instance, assert(0 && "error here"), are
6192 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00006193 return DiagnoseImpCast(S, E, T, CC,
6194 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00006195 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
6196 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
6197 // This covers the literal expressions that evaluate to Objective-C
6198 // objects.
6199 return DiagnoseImpCast(S, E, T, CC,
6200 diag::warn_impcast_objective_c_literal_to_bool);
6201 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00006202 if (Source->isPointerType() || Source->canDecayToPointerType()) {
6203 // Warn on pointer to bool conversion that is always true.
6204 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
6205 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00006206 }
Richard Trieu021baa32011-09-23 20:10:00 +00006207 }
John McCall263a48b2010-01-04 23:31:57 +00006208
6209 // Strip vector types.
6210 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006211 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006212 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006213 return;
John McCallacf0ee52010-10-08 02:01:28 +00006214 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006215 }
Chris Lattneree7286f2011-06-14 04:51:15 +00006216
6217 // If the vector cast is cast between two vectors of the same size, it is
6218 // a bitcast, not a conversion.
6219 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
6220 return;
John McCall263a48b2010-01-04 23:31:57 +00006221
6222 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
6223 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
6224 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00006225 if (auto VecTy = dyn_cast<VectorType>(Target))
6226 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00006227
6228 // Strip complex types.
6229 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006230 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006231 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006232 return;
6233
John McCallacf0ee52010-10-08 02:01:28 +00006234 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006235 }
John McCall263a48b2010-01-04 23:31:57 +00006236
6237 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
6238 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
6239 }
6240
6241 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
6242 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
6243
6244 // If the source is floating point...
6245 if (SourceBT && SourceBT->isFloatingPoint()) {
6246 // ...and the target is floating point...
6247 if (TargetBT && TargetBT->isFloatingPoint()) {
6248 // ...then warn if we're dropping FP rank.
6249
6250 // Builtin FP kinds are ordered by increasing FP rank.
6251 if (SourceBT->getKind() > TargetBT->getKind()) {
6252 // Don't warn about float constants that are precisely
6253 // representable in the target type.
6254 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00006255 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00006256 // Value might be a float, a float vector, or a float complex.
6257 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00006258 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
6259 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00006260 return;
6261 }
6262
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006263 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006264 return;
6265
John McCallacf0ee52010-10-08 02:01:28 +00006266 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall263a48b2010-01-04 23:31:57 +00006267 }
6268 return;
6269 }
6270
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006271 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00006272 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006273 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006274 return;
6275
Chandler Carruth22c7a792011-02-17 11:05:49 +00006276 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00006277 // We also want to warn on, e.g., "int i = -1.234"
6278 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
6279 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
6280 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
6281
Chandler Carruth016ef402011-04-10 08:36:24 +00006282 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
6283 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00006284 } else {
6285 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
6286 }
6287 }
John McCall263a48b2010-01-04 23:31:57 +00006288
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006289 // If the target is bool, warn if expr is a function or method call.
6290 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
6291 isa<CallExpr>(E)) {
6292 // Check last argument of function call to see if it is an
6293 // implicit cast from a type matching the type the result
6294 // is being cast to.
6295 CallExpr *CEx = cast<CallExpr>(E);
6296 unsigned NumArgs = CEx->getNumArgs();
6297 if (NumArgs > 0) {
6298 Expr *LastA = CEx->getArg(NumArgs - 1);
6299 Expr *InnerE = LastA->IgnoreParenImpCasts();
6300 const Type *InnerType =
6301 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6302 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
6303 // Warn on this floating-point to bool conversion
6304 DiagnoseImpCast(S, E, T, CC,
6305 diag::warn_impcast_floating_point_to_bool);
6306 }
6307 }
6308 }
John McCall263a48b2010-01-04 23:31:57 +00006309 return;
6310 }
6311
Richard Trieubeaf3452011-05-29 19:59:02 +00006312 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
David Blaikie9366d2b2012-06-19 21:19:06 +00006313 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
David Blaikiea1edff02012-11-08 00:41:20 +00006314 && !Target->isBlockPointerType() && !Target->isMemberPointerType()
David Blaikiebcd4b552013-02-16 00:56:22 +00006315 && Target->isScalarType() && !Target->isNullPtrType()) {
David Blaikieae12b182012-03-16 20:30:12 +00006316 SourceLocation Loc = E->getSourceRange().getBegin();
6317 if (Loc.isMacroID())
6318 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
David Blaikie18e9ac72012-05-15 21:57:38 +00006319 if (!Loc.isMacroID() || CC.isMacroID())
6320 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
6321 << T << clang::SourceRange(CC)
Richard Smithf7ec86a2013-09-20 00:27:40 +00006322 << FixItHint::CreateReplacement(Loc,
6323 S.getFixItZeroLiteralForType(T, Loc));
Richard Trieubeaf3452011-05-29 19:59:02 +00006324 }
6325
David Blaikie9366d2b2012-06-19 21:19:06 +00006326 if (!Source->isIntegerType() || !Target->isIntegerType())
6327 return;
6328
David Blaikie7555b6a2012-05-15 16:56:36 +00006329 // TODO: remove this early return once the false positives for constant->bool
6330 // in templates, macros, etc, are reduced or removed.
6331 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
6332 return;
6333
John McCallcc7e5bf2010-05-06 08:58:33 +00006334 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00006335 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00006336
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006337 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00006338 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006339 // TODO: this should happen for bitfield stores, too.
6340 llvm::APSInt Value(32);
6341 if (E->isIntegerConstantExpr(Value, S.Context)) {
6342 if (S.SourceMgr.isInSystemMacro(CC))
6343 return;
6344
John McCall18a2c2c2010-11-09 22:22:12 +00006345 std::string PrettySourceValue = Value.toString(10);
6346 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006347
Ted Kremenek33ba9952011-10-22 02:37:33 +00006348 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6349 S.PDiag(diag::warn_impcast_integer_precision_constant)
6350 << PrettySourceValue << PrettyTargetValue
6351 << E->getType() << T << E->getSourceRange()
6352 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00006353 return;
6354 }
6355
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006356 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
6357 if (S.SourceMgr.isInSystemMacro(CC))
6358 return;
6359
David Blaikie9455da02012-04-12 22:40:54 +00006360 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00006361 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
6362 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00006363 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00006364 }
6365
6366 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
6367 (!TargetRange.NonNegative && SourceRange.NonNegative &&
6368 SourceRange.Width == TargetRange.Width)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006369
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006370 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006371 return;
6372
John McCallcc7e5bf2010-05-06 08:58:33 +00006373 unsigned DiagID = diag::warn_impcast_integer_sign;
6374
6375 // Traditionally, gcc has warned about this under -Wsign-compare.
6376 // We also want to warn about it in -Wconversion.
6377 // So if -Wconversion is off, use a completely identical diagnostic
6378 // in the sign-compare group.
6379 // The conditional-checking code will
6380 if (ICContext) {
6381 DiagID = diag::warn_impcast_integer_sign_conditional;
6382 *ICContext = true;
6383 }
6384
John McCallacf0ee52010-10-08 02:01:28 +00006385 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00006386 }
6387
Douglas Gregora78f1932011-02-22 02:45:07 +00006388 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00006389 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
6390 // type, to give us better diagnostics.
6391 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00006392 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00006393 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6394 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
6395 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
6396 SourceType = S.Context.getTypeDeclType(Enum);
6397 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
6398 }
6399 }
6400
Douglas Gregora78f1932011-02-22 02:45:07 +00006401 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
6402 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00006403 if (SourceEnum->getDecl()->hasNameForLinkage() &&
6404 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006405 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006406 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006407 return;
6408
Douglas Gregor364f7db2011-03-12 00:14:31 +00006409 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00006410 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006411 }
Douglas Gregora78f1932011-02-22 02:45:07 +00006412
John McCall263a48b2010-01-04 23:31:57 +00006413 return;
6414}
6415
David Blaikie18e9ac72012-05-15 21:57:38 +00006416void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6417 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006418
6419void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00006420 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006421 E = E->IgnoreParenImpCasts();
6422
6423 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00006424 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006425
John McCallacf0ee52010-10-08 02:01:28 +00006426 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006427 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006428 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00006429 return;
6430}
6431
David Blaikie18e9ac72012-05-15 21:57:38 +00006432void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6433 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00006434 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00006435
6436 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00006437 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
6438 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006439
6440 // If -Wconversion would have warned about either of the candidates
6441 // for a signedness conversion to the context type...
6442 if (!Suspicious) return;
6443
6444 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006445 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00006446 return;
6447
John McCallcc7e5bf2010-05-06 08:58:33 +00006448 // ...then check whether it would have warned about either of the
6449 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00006450 if (E->getType() == T) return;
6451
6452 Suspicious = false;
6453 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
6454 E->getType(), CC, &Suspicious);
6455 if (!Suspicious)
6456 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00006457 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006458}
6459
6460/// AnalyzeImplicitConversions - Find and report any interesting
6461/// implicit conversions in the given expression. There are a couple
6462/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00006463void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00006464 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00006465 Expr *E = OrigE->IgnoreParenImpCasts();
6466
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00006467 if (E->isTypeDependent() || E->isValueDependent())
6468 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00006469
John McCallcc7e5bf2010-05-06 08:58:33 +00006470 // For conditional operators, we analyze the arguments as if they
6471 // were being fed directly into the output.
6472 if (isa<ConditionalOperator>(E)) {
6473 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00006474 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006475 return;
6476 }
6477
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006478 // Check implicit argument conversions for function calls.
6479 if (CallExpr *Call = dyn_cast<CallExpr>(E))
6480 CheckImplicitArgumentConversions(S, Call, CC);
6481
John McCallcc7e5bf2010-05-06 08:58:33 +00006482 // Go ahead and check any implicit conversions we might have skipped.
6483 // The non-canonical typecheck is just an optimization;
6484 // CheckImplicitConversion will filter out dead implicit conversions.
6485 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006486 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006487
6488 // Now continue drilling into this expression.
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006489
6490 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006491 if (POE->getResultExpr())
6492 E = POE->getResultExpr();
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006493 }
6494
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006495 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
6496 return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
6497
John McCallcc7e5bf2010-05-06 08:58:33 +00006498 // Skip past explicit casts.
6499 if (isa<ExplicitCastExpr>(E)) {
6500 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00006501 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006502 }
6503
John McCalld2a53122010-11-09 23:24:47 +00006504 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6505 // Do a somewhat different check with comparison operators.
6506 if (BO->isComparisonOp())
6507 return AnalyzeComparison(S, BO);
6508
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006509 // And with simple assignments.
6510 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00006511 return AnalyzeAssignment(S, BO);
6512 }
John McCallcc7e5bf2010-05-06 08:58:33 +00006513
6514 // These break the otherwise-useful invariant below. Fortunately,
6515 // we don't really need to recurse into them, because any internal
6516 // expressions should have been analyzed already when they were
6517 // built into statements.
6518 if (isa<StmtExpr>(E)) return;
6519
6520 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00006521 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00006522
6523 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00006524 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00006525 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00006526 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Richard Trieu021baa32011-09-23 20:10:00 +00006527 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor73456262012-02-09 10:18:50 +00006528 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00006529 if (!ChildExpr)
6530 continue;
6531
Richard Trieu955231d2014-01-25 01:10:35 +00006532 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00006533 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00006534 // Ignore checking string literals that are in logical and operators.
6535 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00006536 continue;
6537 AnalyzeImplicitConversions(S, ChildExpr, CC);
6538 }
John McCallcc7e5bf2010-05-06 08:58:33 +00006539}
6540
6541} // end anonymous namespace
6542
Richard Trieu3bb8b562014-02-26 02:36:06 +00006543enum {
6544 AddressOf,
6545 FunctionPointer,
6546 ArrayPointer
6547};
6548
Richard Trieuc1888e02014-06-28 23:25:37 +00006549// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
6550// Returns true when emitting a warning about taking the address of a reference.
6551static bool CheckForReference(Sema &SemaRef, const Expr *E,
6552 PartialDiagnostic PD) {
6553 E = E->IgnoreParenImpCasts();
6554
6555 const FunctionDecl *FD = nullptr;
6556
6557 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
6558 if (!DRE->getDecl()->getType()->isReferenceType())
6559 return false;
6560 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6561 if (!M->getMemberDecl()->getType()->isReferenceType())
6562 return false;
6563 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
6564 if (!Call->getCallReturnType()->isReferenceType())
6565 return false;
6566 FD = Call->getDirectCallee();
6567 } else {
6568 return false;
6569 }
6570
6571 SemaRef.Diag(E->getExprLoc(), PD);
6572
6573 // If possible, point to location of function.
6574 if (FD) {
6575 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
6576 }
6577
6578 return true;
6579}
6580
Richard Trieu4cbff5c2014-08-08 22:41:43 +00006581// Returns true if the SourceLocation is expanded from any macro body.
6582// Returns false if the SourceLocation is invalid, is from not in a macro
6583// expansion, or is from expanded from a top-level macro argument.
6584static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
6585 if (Loc.isInvalid())
6586 return false;
6587
6588 while (Loc.isMacroID()) {
6589 if (SM.isMacroBodyExpansion(Loc))
6590 return true;
6591 Loc = SM.getImmediateMacroCallerLoc(Loc);
6592 }
6593
6594 return false;
6595}
6596
Richard Trieu3bb8b562014-02-26 02:36:06 +00006597/// \brief Diagnose pointers that are always non-null.
6598/// \param E the expression containing the pointer
6599/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
6600/// compared to a null pointer
6601/// \param IsEqual True when the comparison is equal to a null pointer
6602/// \param Range Extra SourceRange to highlight in the diagnostic
6603void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
6604 Expr::NullPointerConstantKind NullKind,
6605 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00006606 if (!E)
6607 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006608
6609 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00006610 if (E->getExprLoc().isMacroID()) {
6611 const SourceManager &SM = getSourceManager();
6612 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
6613 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00006614 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00006615 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00006616 E = E->IgnoreImpCasts();
6617
6618 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
6619
Richard Trieuf7432752014-06-06 21:39:26 +00006620 if (isa<CXXThisExpr>(E)) {
6621 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
6622 : diag::warn_this_bool_conversion;
6623 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
6624 return;
6625 }
6626
Richard Trieu3bb8b562014-02-26 02:36:06 +00006627 bool IsAddressOf = false;
6628
6629 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6630 if (UO->getOpcode() != UO_AddrOf)
6631 return;
6632 IsAddressOf = true;
6633 E = UO->getSubExpr();
6634 }
6635
Richard Trieuc1888e02014-06-28 23:25:37 +00006636 if (IsAddressOf) {
6637 unsigned DiagID = IsCompare
6638 ? diag::warn_address_of_reference_null_compare
6639 : diag::warn_address_of_reference_bool_conversion;
6640 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
6641 << IsEqual;
6642 if (CheckForReference(*this, E, PD)) {
6643 return;
6644 }
6645 }
6646
Richard Trieu3bb8b562014-02-26 02:36:06 +00006647 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00006648 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006649 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
6650 D = R->getDecl();
6651 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6652 D = M->getMemberDecl();
6653 }
6654
6655 // Weak Decls can be null.
6656 if (!D || D->isWeak())
6657 return;
6658
6659 QualType T = D->getType();
6660 const bool IsArray = T->isArrayType();
6661 const bool IsFunction = T->isFunctionType();
6662
Richard Trieuc1888e02014-06-28 23:25:37 +00006663 // Address of function is used to silence the function warning.
6664 if (IsAddressOf && IsFunction) {
6665 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006666 }
6667
6668 // Found nothing.
6669 if (!IsAddressOf && !IsFunction && !IsArray)
6670 return;
6671
6672 // Pretty print the expression for the diagnostic.
6673 std::string Str;
6674 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00006675 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00006676
6677 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
6678 : diag::warn_impcast_pointer_to_bool;
6679 unsigned DiagType;
6680 if (IsAddressOf)
6681 DiagType = AddressOf;
6682 else if (IsFunction)
6683 DiagType = FunctionPointer;
6684 else if (IsArray)
6685 DiagType = ArrayPointer;
6686 else
6687 llvm_unreachable("Could not determine diagnostic.");
6688 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
6689 << Range << IsEqual;
6690
6691 if (!IsFunction)
6692 return;
6693
6694 // Suggest '&' to silence the function warning.
6695 Diag(E->getExprLoc(), diag::note_function_warning_silence)
6696 << FixItHint::CreateInsertion(E->getLocStart(), "&");
6697
6698 // Check to see if '()' fixit should be emitted.
6699 QualType ReturnType;
6700 UnresolvedSet<4> NonTemplateOverloads;
6701 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
6702 if (ReturnType.isNull())
6703 return;
6704
6705 if (IsCompare) {
6706 // There are two cases here. If there is null constant, the only suggest
6707 // for a pointer return type. If the null is 0, then suggest if the return
6708 // type is a pointer or an integer type.
6709 if (!ReturnType->isPointerType()) {
6710 if (NullKind == Expr::NPCK_ZeroExpression ||
6711 NullKind == Expr::NPCK_ZeroLiteral) {
6712 if (!ReturnType->isIntegerType())
6713 return;
6714 } else {
6715 return;
6716 }
6717 }
6718 } else { // !IsCompare
6719 // For function to bool, only suggest if the function pointer has bool
6720 // return type.
6721 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
6722 return;
6723 }
6724 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00006725 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00006726}
6727
6728
John McCallcc7e5bf2010-05-06 08:58:33 +00006729/// Diagnoses "dangerous" implicit conversions within the given
6730/// expression (which is a full expression). Implements -Wconversion
6731/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00006732///
6733/// \param CC the "context" location of the implicit conversion, i.e.
6734/// the most location of the syntactic entity requiring the implicit
6735/// conversion
6736void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006737 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00006738 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00006739 return;
6740
6741 // Don't diagnose for value- or type-dependent expressions.
6742 if (E->isTypeDependent() || E->isValueDependent())
6743 return;
6744
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006745 // Check for array bounds violations in cases where the check isn't triggered
6746 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
6747 // ArraySubscriptExpr is on the RHS of a variable initialization.
6748 CheckArrayAccess(E);
6749
John McCallacf0ee52010-10-08 02:01:28 +00006750 // This is not the right CC for (e.g.) a variable initialization.
6751 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006752}
6753
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006754/// Diagnose when expression is an integer constant expression and its evaluation
6755/// results in integer overflow
6756void Sema::CheckForIntOverflow (Expr *E) {
Fariborz Jahanianc694e692014-10-14 20:27:05 +00006757 if (isa<BinaryOperator>(E->IgnoreParenCasts()))
6758 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006759}
6760
Richard Smithc406cb72013-01-17 01:17:56 +00006761namespace {
6762/// \brief Visitor for expressions which looks for unsequenced operations on the
6763/// same object.
6764class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00006765 typedef EvaluatedExprVisitor<SequenceChecker> Base;
6766
Richard Smithc406cb72013-01-17 01:17:56 +00006767 /// \brief A tree of sequenced regions within an expression. Two regions are
6768 /// unsequenced if one is an ancestor or a descendent of the other. When we
6769 /// finish processing an expression with sequencing, such as a comma
6770 /// expression, we fold its tree nodes into its parent, since they are
6771 /// unsequenced with respect to nodes we will visit later.
6772 class SequenceTree {
6773 struct Value {
6774 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
6775 unsigned Parent : 31;
6776 bool Merged : 1;
6777 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006778 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00006779
6780 public:
6781 /// \brief A region within an expression which may be sequenced with respect
6782 /// to some other region.
6783 class Seq {
6784 explicit Seq(unsigned N) : Index(N) {}
6785 unsigned Index;
6786 friend class SequenceTree;
6787 public:
6788 Seq() : Index(0) {}
6789 };
6790
6791 SequenceTree() { Values.push_back(Value(0)); }
6792 Seq root() const { return Seq(0); }
6793
6794 /// \brief Create a new sequence of operations, which is an unsequenced
6795 /// subset of \p Parent. This sequence of operations is sequenced with
6796 /// respect to other children of \p Parent.
6797 Seq allocate(Seq Parent) {
6798 Values.push_back(Value(Parent.Index));
6799 return Seq(Values.size() - 1);
6800 }
6801
6802 /// \brief Merge a sequence of operations into its parent.
6803 void merge(Seq S) {
6804 Values[S.Index].Merged = true;
6805 }
6806
6807 /// \brief Determine whether two operations are unsequenced. This operation
6808 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
6809 /// should have been merged into its parent as appropriate.
6810 bool isUnsequenced(Seq Cur, Seq Old) {
6811 unsigned C = representative(Cur.Index);
6812 unsigned Target = representative(Old.Index);
6813 while (C >= Target) {
6814 if (C == Target)
6815 return true;
6816 C = Values[C].Parent;
6817 }
6818 return false;
6819 }
6820
6821 private:
6822 /// \brief Pick a representative for a sequence.
6823 unsigned representative(unsigned K) {
6824 if (Values[K].Merged)
6825 // Perform path compression as we go.
6826 return Values[K].Parent = representative(Values[K].Parent);
6827 return K;
6828 }
6829 };
6830
6831 /// An object for which we can track unsequenced uses.
6832 typedef NamedDecl *Object;
6833
6834 /// Different flavors of object usage which we track. We only track the
6835 /// least-sequenced usage of each kind.
6836 enum UsageKind {
6837 /// A read of an object. Multiple unsequenced reads are OK.
6838 UK_Use,
6839 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00006840 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00006841 UK_ModAsValue,
6842 /// A modification of an object which is not sequenced before the value
6843 /// computation of the expression, such as n++.
6844 UK_ModAsSideEffect,
6845
6846 UK_Count = UK_ModAsSideEffect + 1
6847 };
6848
6849 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00006850 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00006851 Expr *Use;
6852 SequenceTree::Seq Seq;
6853 };
6854
6855 struct UsageInfo {
6856 UsageInfo() : Diagnosed(false) {}
6857 Usage Uses[UK_Count];
6858 /// Have we issued a diagnostic for this variable already?
6859 bool Diagnosed;
6860 };
6861 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
6862
6863 Sema &SemaRef;
6864 /// Sequenced regions within the expression.
6865 SequenceTree Tree;
6866 /// Declaration modifications and references which we have seen.
6867 UsageInfoMap UsageMap;
6868 /// The region we are currently within.
6869 SequenceTree::Seq Region;
6870 /// Filled in with declarations which were modified as a side-effect
6871 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006872 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00006873 /// Expressions to check later. We defer checking these to reduce
6874 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006875 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00006876
6877 /// RAII object wrapping the visitation of a sequenced subexpression of an
6878 /// expression. At the end of this process, the side-effects of the evaluation
6879 /// become sequenced with respect to the value computation of the result, so
6880 /// we downgrade any UK_ModAsSideEffect within the evaluation to
6881 /// UK_ModAsValue.
6882 struct SequencedSubexpression {
6883 SequencedSubexpression(SequenceChecker &Self)
6884 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
6885 Self.ModAsSideEffect = &ModAsSideEffect;
6886 }
6887 ~SequencedSubexpression() {
6888 for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) {
6889 UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first];
6890 U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second;
6891 Self.addUsage(U, ModAsSideEffect[I].first,
6892 ModAsSideEffect[I].second.Use, UK_ModAsValue);
6893 }
6894 Self.ModAsSideEffect = OldModAsSideEffect;
6895 }
6896
6897 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006898 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
6899 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00006900 };
6901
Richard Smith40238f02013-06-20 22:21:56 +00006902 /// RAII object wrapping the visitation of a subexpression which we might
6903 /// choose to evaluate as a constant. If any subexpression is evaluated and
6904 /// found to be non-constant, this allows us to suppress the evaluation of
6905 /// the outer expression.
6906 class EvaluationTracker {
6907 public:
6908 EvaluationTracker(SequenceChecker &Self)
6909 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
6910 Self.EvalTracker = this;
6911 }
6912 ~EvaluationTracker() {
6913 Self.EvalTracker = Prev;
6914 if (Prev)
6915 Prev->EvalOK &= EvalOK;
6916 }
6917
6918 bool evaluate(const Expr *E, bool &Result) {
6919 if (!EvalOK || E->isValueDependent())
6920 return false;
6921 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
6922 return EvalOK;
6923 }
6924
6925 private:
6926 SequenceChecker &Self;
6927 EvaluationTracker *Prev;
6928 bool EvalOK;
6929 } *EvalTracker;
6930
Richard Smithc406cb72013-01-17 01:17:56 +00006931 /// \brief Find the object which is produced by the specified expression,
6932 /// if any.
6933 Object getObject(Expr *E, bool Mod) const {
6934 E = E->IgnoreParenCasts();
6935 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6936 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
6937 return getObject(UO->getSubExpr(), Mod);
6938 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6939 if (BO->getOpcode() == BO_Comma)
6940 return getObject(BO->getRHS(), Mod);
6941 if (Mod && BO->isAssignmentOp())
6942 return getObject(BO->getLHS(), Mod);
6943 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
6944 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
6945 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
6946 return ME->getMemberDecl();
6947 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6948 // FIXME: If this is a reference, map through to its value.
6949 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00006950 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00006951 }
6952
6953 /// \brief Note that an object was modified or used by an expression.
6954 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
6955 Usage &U = UI.Uses[UK];
6956 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
6957 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
6958 ModAsSideEffect->push_back(std::make_pair(O, U));
6959 U.Use = Ref;
6960 U.Seq = Region;
6961 }
6962 }
6963 /// \brief Check whether a modification or use conflicts with a prior usage.
6964 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
6965 bool IsModMod) {
6966 if (UI.Diagnosed)
6967 return;
6968
6969 const Usage &U = UI.Uses[OtherKind];
6970 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
6971 return;
6972
6973 Expr *Mod = U.Use;
6974 Expr *ModOrUse = Ref;
6975 if (OtherKind == UK_Use)
6976 std::swap(Mod, ModOrUse);
6977
6978 SemaRef.Diag(Mod->getExprLoc(),
6979 IsModMod ? diag::warn_unsequenced_mod_mod
6980 : diag::warn_unsequenced_mod_use)
6981 << O << SourceRange(ModOrUse->getExprLoc());
6982 UI.Diagnosed = true;
6983 }
6984
6985 void notePreUse(Object O, Expr *Use) {
6986 UsageInfo &U = UsageMap[O];
6987 // Uses conflict with other modifications.
6988 checkUsage(O, U, Use, UK_ModAsValue, false);
6989 }
6990 void notePostUse(Object O, Expr *Use) {
6991 UsageInfo &U = UsageMap[O];
6992 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
6993 addUsage(U, O, Use, UK_Use);
6994 }
6995
6996 void notePreMod(Object O, Expr *Mod) {
6997 UsageInfo &U = UsageMap[O];
6998 // Modifications conflict with other modifications and with uses.
6999 checkUsage(O, U, Mod, UK_ModAsValue, true);
7000 checkUsage(O, U, Mod, UK_Use, false);
7001 }
7002 void notePostMod(Object O, Expr *Use, UsageKind UK) {
7003 UsageInfo &U = UsageMap[O];
7004 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
7005 addUsage(U, O, Use, UK);
7006 }
7007
7008public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007009 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00007010 : Base(S.Context), SemaRef(S), Region(Tree.root()),
7011 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00007012 Visit(E);
7013 }
7014
7015 void VisitStmt(Stmt *S) {
7016 // Skip all statements which aren't expressions for now.
7017 }
7018
7019 void VisitExpr(Expr *E) {
7020 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00007021 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00007022 }
7023
7024 void VisitCastExpr(CastExpr *E) {
7025 Object O = Object();
7026 if (E->getCastKind() == CK_LValueToRValue)
7027 O = getObject(E->getSubExpr(), false);
7028
7029 if (O)
7030 notePreUse(O, E);
7031 VisitExpr(E);
7032 if (O)
7033 notePostUse(O, E);
7034 }
7035
7036 void VisitBinComma(BinaryOperator *BO) {
7037 // C++11 [expr.comma]p1:
7038 // Every value computation and side effect associated with the left
7039 // expression is sequenced before every value computation and side
7040 // effect associated with the right expression.
7041 SequenceTree::Seq LHS = Tree.allocate(Region);
7042 SequenceTree::Seq RHS = Tree.allocate(Region);
7043 SequenceTree::Seq OldRegion = Region;
7044
7045 {
7046 SequencedSubexpression SeqLHS(*this);
7047 Region = LHS;
7048 Visit(BO->getLHS());
7049 }
7050
7051 Region = RHS;
7052 Visit(BO->getRHS());
7053
7054 Region = OldRegion;
7055
7056 // Forget that LHS and RHS are sequenced. They are both unsequenced
7057 // with respect to other stuff.
7058 Tree.merge(LHS);
7059 Tree.merge(RHS);
7060 }
7061
7062 void VisitBinAssign(BinaryOperator *BO) {
7063 // The modification is sequenced after the value computation of the LHS
7064 // and RHS, so check it before inspecting the operands and update the
7065 // map afterwards.
7066 Object O = getObject(BO->getLHS(), true);
7067 if (!O)
7068 return VisitExpr(BO);
7069
7070 notePreMod(O, BO);
7071
7072 // C++11 [expr.ass]p7:
7073 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
7074 // only once.
7075 //
7076 // Therefore, for a compound assignment operator, O is considered used
7077 // everywhere except within the evaluation of E1 itself.
7078 if (isa<CompoundAssignOperator>(BO))
7079 notePreUse(O, BO);
7080
7081 Visit(BO->getLHS());
7082
7083 if (isa<CompoundAssignOperator>(BO))
7084 notePostUse(O, BO);
7085
7086 Visit(BO->getRHS());
7087
Richard Smith83e37bee2013-06-26 23:16:51 +00007088 // C++11 [expr.ass]p1:
7089 // the assignment is sequenced [...] before the value computation of the
7090 // assignment expression.
7091 // C11 6.5.16/3 has no such rule.
7092 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7093 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00007094 }
7095 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
7096 VisitBinAssign(CAO);
7097 }
7098
7099 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7100 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7101 void VisitUnaryPreIncDec(UnaryOperator *UO) {
7102 Object O = getObject(UO->getSubExpr(), true);
7103 if (!O)
7104 return VisitExpr(UO);
7105
7106 notePreMod(O, UO);
7107 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00007108 // C++11 [expr.pre.incr]p1:
7109 // the expression ++x is equivalent to x+=1
7110 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7111 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00007112 }
7113
7114 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7115 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7116 void VisitUnaryPostIncDec(UnaryOperator *UO) {
7117 Object O = getObject(UO->getSubExpr(), true);
7118 if (!O)
7119 return VisitExpr(UO);
7120
7121 notePreMod(O, UO);
7122 Visit(UO->getSubExpr());
7123 notePostMod(O, UO, UK_ModAsSideEffect);
7124 }
7125
7126 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
7127 void VisitBinLOr(BinaryOperator *BO) {
7128 // The side-effects of the LHS of an '&&' are sequenced before the
7129 // value computation of the RHS, and hence before the value computation
7130 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
7131 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00007132 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00007133 {
7134 SequencedSubexpression Sequenced(*this);
7135 Visit(BO->getLHS());
7136 }
7137
7138 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007139 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00007140 if (!Result)
7141 Visit(BO->getRHS());
7142 } else {
7143 // Check for unsequenced operations in the RHS, treating it as an
7144 // entirely separate evaluation.
7145 //
7146 // FIXME: If there are operations in the RHS which are unsequenced
7147 // with respect to operations outside the RHS, and those operations
7148 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00007149 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00007150 }
Richard Smithc406cb72013-01-17 01:17:56 +00007151 }
7152 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00007153 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00007154 {
7155 SequencedSubexpression Sequenced(*this);
7156 Visit(BO->getLHS());
7157 }
7158
7159 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007160 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00007161 if (Result)
7162 Visit(BO->getRHS());
7163 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00007164 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00007165 }
Richard Smithc406cb72013-01-17 01:17:56 +00007166 }
7167
7168 // Only visit the condition, unless we can be sure which subexpression will
7169 // be chosen.
7170 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00007171 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00007172 {
7173 SequencedSubexpression Sequenced(*this);
7174 Visit(CO->getCond());
7175 }
Richard Smithc406cb72013-01-17 01:17:56 +00007176
7177 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007178 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00007179 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00007180 else {
Richard Smithd33f5202013-01-17 23:18:09 +00007181 WorkList.push_back(CO->getTrueExpr());
7182 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00007183 }
Richard Smithc406cb72013-01-17 01:17:56 +00007184 }
7185
Richard Smithe3dbfe02013-06-30 10:40:20 +00007186 void VisitCallExpr(CallExpr *CE) {
7187 // C++11 [intro.execution]p15:
7188 // When calling a function [...], every value computation and side effect
7189 // associated with any argument expression, or with the postfix expression
7190 // designating the called function, is sequenced before execution of every
7191 // expression or statement in the body of the function [and thus before
7192 // the value computation of its result].
7193 SequencedSubexpression Sequenced(*this);
7194 Base::VisitCallExpr(CE);
7195
7196 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
7197 }
7198
Richard Smithc406cb72013-01-17 01:17:56 +00007199 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00007200 // This is a call, so all subexpressions are sequenced before the result.
7201 SequencedSubexpression Sequenced(*this);
7202
Richard Smithc406cb72013-01-17 01:17:56 +00007203 if (!CCE->isListInitialization())
7204 return VisitExpr(CCE);
7205
7206 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007207 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00007208 SequenceTree::Seq Parent = Region;
7209 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
7210 E = CCE->arg_end();
7211 I != E; ++I) {
7212 Region = Tree.allocate(Parent);
7213 Elts.push_back(Region);
7214 Visit(*I);
7215 }
7216
7217 // Forget that the initializers are sequenced.
7218 Region = Parent;
7219 for (unsigned I = 0; I < Elts.size(); ++I)
7220 Tree.merge(Elts[I]);
7221 }
7222
7223 void VisitInitListExpr(InitListExpr *ILE) {
7224 if (!SemaRef.getLangOpts().CPlusPlus11)
7225 return VisitExpr(ILE);
7226
7227 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007228 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00007229 SequenceTree::Seq Parent = Region;
7230 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
7231 Expr *E = ILE->getInit(I);
7232 if (!E) continue;
7233 Region = Tree.allocate(Parent);
7234 Elts.push_back(Region);
7235 Visit(E);
7236 }
7237
7238 // Forget that the initializers are sequenced.
7239 Region = Parent;
7240 for (unsigned I = 0; I < Elts.size(); ++I)
7241 Tree.merge(Elts[I]);
7242 }
7243};
7244}
7245
7246void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007247 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00007248 WorkList.push_back(E);
7249 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00007250 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00007251 SequenceChecker(*this, Item, WorkList);
7252 }
Richard Smithc406cb72013-01-17 01:17:56 +00007253}
7254
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007255void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
7256 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00007257 CheckImplicitConversions(E, CheckLoc);
7258 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007259 if (!IsConstexpr && !E->isValueDependent())
7260 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00007261}
7262
John McCall1f425642010-11-11 03:21:53 +00007263void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
7264 FieldDecl *BitField,
7265 Expr *Init) {
7266 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
7267}
7268
Mike Stump0c2ec772010-01-21 03:59:47 +00007269/// CheckParmsForFunctionDef - Check that the parameters of the given
7270/// function are appropriate for the definition of a function. This
7271/// takes care of any checks that cannot be performed on the
7272/// declaration itself, e.g., that the types of each of the function
7273/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00007274bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
7275 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00007276 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00007277 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00007278 for (; P != PEnd; ++P) {
7279 ParmVarDecl *Param = *P;
7280
Mike Stump0c2ec772010-01-21 03:59:47 +00007281 // C99 6.7.5.3p4: the parameters in a parameter type list in a
7282 // function declarator that is part of a function definition of
7283 // that function shall not have incomplete type.
7284 //
7285 // This is also C++ [dcl.fct]p6.
7286 if (!Param->isInvalidDecl() &&
7287 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00007288 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00007289 Param->setInvalidDecl();
7290 HasInvalidParm = true;
7291 }
7292
7293 // C99 6.9.1p5: If the declarator includes a parameter type list, the
7294 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00007295 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00007296 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00007297 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00007298 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00007299 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00007300
7301 // C99 6.7.5.3p12:
7302 // If the function declarator is not part of a definition of that
7303 // function, parameters may have incomplete type and may use the [*]
7304 // notation in their sequences of declarator specifiers to specify
7305 // variable length array types.
7306 QualType PType = Param->getOriginalType();
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007307 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigdeb55d52010-02-01 05:02:49 +00007308 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitb3318502013-03-01 21:41:22 +00007309 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigdeb55d52010-02-01 05:02:49 +00007310 // information is added for it.
7311 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007312 break;
Sam Weinigdeb55d52010-02-01 05:02:49 +00007313 }
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007314 PType= AT->getElementType();
Sam Weinigdeb55d52010-02-01 05:02:49 +00007315 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00007316
7317 // MSVC destroys objects passed by value in the callee. Therefore a
7318 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00007319 // object's destructor. However, we don't perform any direct access check
7320 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00007321 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
7322 .getCXXABI()
7323 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00007324 if (!Param->isInvalidDecl()) {
7325 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
7326 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
7327 if (!ClassDecl->isInvalidDecl() &&
7328 !ClassDecl->hasIrrelevantDestructor() &&
7329 !ClassDecl->isDependentContext()) {
7330 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
7331 MarkFunctionReferenced(Param->getLocation(), Destructor);
7332 DiagnoseUseOfDecl(Destructor, Param->getLocation());
7333 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00007334 }
7335 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00007336 }
Mike Stump0c2ec772010-01-21 03:59:47 +00007337 }
7338
7339 return HasInvalidParm;
7340}
John McCall2b5c1b22010-08-12 21:44:57 +00007341
7342/// CheckCastAlign - Implements -Wcast-align, which warns when a
7343/// pointer cast increases the alignment requirements.
7344void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
7345 // This is actually a lot of work to potentially be doing on every
7346 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007347 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00007348 return;
7349
7350 // Ignore dependent types.
7351 if (T->isDependentType() || Op->getType()->isDependentType())
7352 return;
7353
7354 // Require that the destination be a pointer type.
7355 const PointerType *DestPtr = T->getAs<PointerType>();
7356 if (!DestPtr) return;
7357
7358 // If the destination has alignment 1, we're done.
7359 QualType DestPointee = DestPtr->getPointeeType();
7360 if (DestPointee->isIncompleteType()) return;
7361 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
7362 if (DestAlign.isOne()) return;
7363
7364 // Require that the source be a pointer type.
7365 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
7366 if (!SrcPtr) return;
7367 QualType SrcPointee = SrcPtr->getPointeeType();
7368
7369 // Whitelist casts from cv void*. We already implicitly
7370 // whitelisted casts to cv void*, since they have alignment 1.
7371 // Also whitelist casts involving incomplete types, which implicitly
7372 // includes 'void'.
7373 if (SrcPointee->isIncompleteType()) return;
7374
7375 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
7376 if (SrcAlign >= DestAlign) return;
7377
7378 Diag(TRange.getBegin(), diag::warn_cast_align)
7379 << Op->getType() << T
7380 << static_cast<unsigned>(SrcAlign.getQuantity())
7381 << static_cast<unsigned>(DestAlign.getQuantity())
7382 << TRange << Op->getSourceRange();
7383}
7384
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007385static const Type* getElementType(const Expr *BaseExpr) {
7386 const Type* EltType = BaseExpr->getType().getTypePtr();
7387 if (EltType->isAnyPointerType())
7388 return EltType->getPointeeType().getTypePtr();
7389 else if (EltType->isArrayType())
7390 return EltType->getBaseElementTypeUnsafe();
7391 return EltType;
7392}
7393
Chandler Carruth28389f02011-08-05 09:10:50 +00007394/// \brief Check whether this array fits the idiom of a size-one tail padded
7395/// array member of a struct.
7396///
7397/// We avoid emitting out-of-bounds access warnings for such arrays as they are
7398/// commonly used to emulate flexible arrays in C89 code.
7399static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
7400 const NamedDecl *ND) {
7401 if (Size != 1 || !ND) return false;
7402
7403 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
7404 if (!FD) return false;
7405
7406 // Don't consider sizes resulting from macro expansions or template argument
7407 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00007408
7409 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007410 while (TInfo) {
7411 TypeLoc TL = TInfo->getTypeLoc();
7412 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00007413 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
7414 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007415 TInfo = TDL->getTypeSourceInfo();
7416 continue;
7417 }
David Blaikie6adc78e2013-02-18 22:06:02 +00007418 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
7419 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00007420 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
7421 return false;
7422 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007423 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00007424 }
Chandler Carruth28389f02011-08-05 09:10:50 +00007425
7426 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00007427 if (!RD) return false;
7428 if (RD->isUnion()) return false;
7429 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
7430 if (!CRD->isStandardLayout()) return false;
7431 }
Chandler Carruth28389f02011-08-05 09:10:50 +00007432
Benjamin Kramer8c543672011-08-06 03:04:42 +00007433 // See if this is the last field decl in the record.
7434 const Decl *D = FD;
7435 while ((D = D->getNextDeclInContext()))
7436 if (isa<FieldDecl>(D))
7437 return false;
7438 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00007439}
7440
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007441void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007442 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00007443 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007444 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007445 if (IndexExpr->isValueDependent())
7446 return;
7447
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00007448 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007449 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007450 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007451 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007452 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00007453 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00007454
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007455 llvm::APSInt index;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007456 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremenek64699be2011-02-16 01:57:07 +00007457 return;
Richard Smith13f67182011-12-16 19:31:14 +00007458 if (IndexNegated)
7459 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00007460
Craig Topperc3ec1492014-05-26 06:22:03 +00007461 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00007462 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7463 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00007464 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00007465 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00007466
Ted Kremeneke4b316c2011-02-23 23:06:04 +00007467 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007468 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00007469 if (!size.isStrictlyPositive())
7470 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007471
7472 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00007473 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007474 // Make sure we're comparing apples to apples when comparing index to size
7475 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
7476 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00007477 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00007478 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007479 if (ptrarith_typesize != array_typesize) {
7480 // There's a cast to a different size type involved
7481 uint64_t ratio = array_typesize / ptrarith_typesize;
7482 // TODO: Be smarter about handling cases where array_typesize is not a
7483 // multiple of ptrarith_typesize
7484 if (ptrarith_typesize * ratio == array_typesize)
7485 size *= llvm::APInt(size.getBitWidth(), ratio);
7486 }
7487 }
7488
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007489 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007490 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007491 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007492 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007493
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007494 // For array subscripting the index must be less than size, but for pointer
7495 // arithmetic also allow the index (offset) to be equal to size since
7496 // computing the next address after the end of the array is legal and
7497 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007498 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00007499 return;
7500
7501 // Also don't warn for arrays of size 1 which are members of some
7502 // structure. These are often used to approximate flexible arrays in C89
7503 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007504 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00007505 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007506
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007507 // Suppress the warning if the subscript expression (as identified by the
7508 // ']' location) and the index expression are both from macro expansions
7509 // within a system header.
7510 if (ASE) {
7511 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
7512 ASE->getRBracketLoc());
7513 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
7514 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
7515 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00007516 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007517 return;
7518 }
7519 }
7520
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007521 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007522 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007523 DiagID = diag::warn_array_index_exceeds_bounds;
7524
7525 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7526 PDiag(DiagID) << index.toString(10, true)
7527 << size.toString(10, true)
7528 << (unsigned)size.getLimitedValue(~0U)
7529 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007530 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007531 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007532 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007533 DiagID = diag::warn_ptr_arith_precedes_bounds;
7534 if (index.isNegative()) index = -index;
7535 }
7536
7537 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7538 PDiag(DiagID) << index.toString(10, true)
7539 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00007540 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00007541
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00007542 if (!ND) {
7543 // Try harder to find a NamedDecl to point at in the note.
7544 while (const ArraySubscriptExpr *ASE =
7545 dyn_cast<ArraySubscriptExpr>(BaseExpr))
7546 BaseExpr = ASE->getBase()->IgnoreParenCasts();
7547 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7548 ND = dyn_cast<NamedDecl>(DRE->getDecl());
7549 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
7550 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
7551 }
7552
Chandler Carruth1af88f12011-02-17 21:10:52 +00007553 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007554 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
7555 PDiag(diag::note_array_index_out_of_bounds)
7556 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00007557}
7558
Ted Kremenekdf26df72011-03-01 18:41:00 +00007559void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007560 int AllowOnePastEnd = 0;
7561 while (expr) {
7562 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00007563 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007564 case Stmt::ArraySubscriptExprClass: {
7565 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007566 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007567 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00007568 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007569 }
7570 case Stmt::UnaryOperatorClass: {
7571 // Only unwrap the * and & unary operators
7572 const UnaryOperator *UO = cast<UnaryOperator>(expr);
7573 expr = UO->getSubExpr();
7574 switch (UO->getOpcode()) {
7575 case UO_AddrOf:
7576 AllowOnePastEnd++;
7577 break;
7578 case UO_Deref:
7579 AllowOnePastEnd--;
7580 break;
7581 default:
7582 return;
7583 }
7584 break;
7585 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007586 case Stmt::ConditionalOperatorClass: {
7587 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
7588 if (const Expr *lhs = cond->getLHS())
7589 CheckArrayAccess(lhs);
7590 if (const Expr *rhs = cond->getRHS())
7591 CheckArrayAccess(rhs);
7592 return;
7593 }
7594 default:
7595 return;
7596 }
Peter Collingbourne91147592011-04-15 00:35:48 +00007597 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007598}
John McCall31168b02011-06-15 23:02:42 +00007599
7600//===--- CHECK: Objective-C retain cycles ----------------------------------//
7601
7602namespace {
7603 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00007604 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00007605 VarDecl *Variable;
7606 SourceRange Range;
7607 SourceLocation Loc;
7608 bool Indirect;
7609
7610 void setLocsFrom(Expr *e) {
7611 Loc = e->getExprLoc();
7612 Range = e->getSourceRange();
7613 }
7614 };
7615}
7616
7617/// Consider whether capturing the given variable can possibly lead to
7618/// a retain cycle.
7619static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00007620 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00007621 // lifetime. In MRR, it's captured strongly if the variable is
7622 // __block and has an appropriate type.
7623 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7624 return false;
7625
7626 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007627 if (ref)
7628 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00007629 return true;
7630}
7631
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007632static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00007633 while (true) {
7634 e = e->IgnoreParens();
7635 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
7636 switch (cast->getCastKind()) {
7637 case CK_BitCast:
7638 case CK_LValueBitCast:
7639 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00007640 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00007641 e = cast->getSubExpr();
7642 continue;
7643
John McCall31168b02011-06-15 23:02:42 +00007644 default:
7645 return false;
7646 }
7647 }
7648
7649 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
7650 ObjCIvarDecl *ivar = ref->getDecl();
7651 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7652 return false;
7653
7654 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007655 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00007656 return false;
7657
7658 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
7659 owner.Indirect = true;
7660 return true;
7661 }
7662
7663 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
7664 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
7665 if (!var) return false;
7666 return considerVariable(var, ref, owner);
7667 }
7668
John McCall31168b02011-06-15 23:02:42 +00007669 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
7670 if (member->isArrow()) return false;
7671
7672 // Don't count this as an indirect ownership.
7673 e = member->getBase();
7674 continue;
7675 }
7676
John McCallfe96e0b2011-11-06 09:01:30 +00007677 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
7678 // Only pay attention to pseudo-objects on property references.
7679 ObjCPropertyRefExpr *pre
7680 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
7681 ->IgnoreParens());
7682 if (!pre) return false;
7683 if (pre->isImplicitProperty()) return false;
7684 ObjCPropertyDecl *property = pre->getExplicitProperty();
7685 if (!property->isRetaining() &&
7686 !(property->getPropertyIvarDecl() &&
7687 property->getPropertyIvarDecl()->getType()
7688 .getObjCLifetime() == Qualifiers::OCL_Strong))
7689 return false;
7690
7691 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007692 if (pre->isSuperReceiver()) {
7693 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
7694 if (!owner.Variable)
7695 return false;
7696 owner.Loc = pre->getLocation();
7697 owner.Range = pre->getSourceRange();
7698 return true;
7699 }
John McCallfe96e0b2011-11-06 09:01:30 +00007700 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
7701 ->getSourceExpr());
7702 continue;
7703 }
7704
John McCall31168b02011-06-15 23:02:42 +00007705 // Array ivars?
7706
7707 return false;
7708 }
7709}
7710
7711namespace {
7712 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
7713 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
7714 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00007715 Context(Context), Variable(variable), Capturer(nullptr),
7716 VarWillBeReased(false) {}
7717 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +00007718 VarDecl *Variable;
7719 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00007720 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +00007721
7722 void VisitDeclRefExpr(DeclRefExpr *ref) {
7723 if (ref->getDecl() == Variable && !Capturer)
7724 Capturer = ref;
7725 }
7726
John McCall31168b02011-06-15 23:02:42 +00007727 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
7728 if (Capturer) return;
7729 Visit(ref->getBase());
7730 if (Capturer && ref->isFreeIvar())
7731 Capturer = ref;
7732 }
7733
7734 void VisitBlockExpr(BlockExpr *block) {
7735 // Look inside nested blocks
7736 if (block->getBlockDecl()->capturesVariable(Variable))
7737 Visit(block->getBlockDecl()->getBody());
7738 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00007739
7740 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
7741 if (Capturer) return;
7742 if (OVE->getSourceExpr())
7743 Visit(OVE->getSourceExpr());
7744 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00007745 void VisitBinaryOperator(BinaryOperator *BinOp) {
7746 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
7747 return;
7748 Expr *LHS = BinOp->getLHS();
7749 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
7750 if (DRE->getDecl() != Variable)
7751 return;
7752 if (Expr *RHS = BinOp->getRHS()) {
7753 RHS = RHS->IgnoreParenCasts();
7754 llvm::APSInt Value;
7755 VarWillBeReased =
7756 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
7757 }
7758 }
7759 }
John McCall31168b02011-06-15 23:02:42 +00007760 };
7761}
7762
7763/// Check whether the given argument is a block which captures a
7764/// variable.
7765static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
7766 assert(owner.Variable && owner.Loc.isValid());
7767
7768 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00007769
7770 // Look through [^{...} copy] and Block_copy(^{...}).
7771 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
7772 Selector Cmd = ME->getSelector();
7773 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
7774 e = ME->getInstanceReceiver();
7775 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +00007776 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +00007777 e = e->IgnoreParenCasts();
7778 }
7779 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
7780 if (CE->getNumArgs() == 1) {
7781 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00007782 if (Fn) {
7783 const IdentifierInfo *FnI = Fn->getIdentifier();
7784 if (FnI && FnI->isStr("_Block_copy")) {
7785 e = CE->getArg(0)->IgnoreParenCasts();
7786 }
7787 }
Jordan Rose67e887c2012-09-17 17:54:30 +00007788 }
7789 }
7790
John McCall31168b02011-06-15 23:02:42 +00007791 BlockExpr *block = dyn_cast<BlockExpr>(e);
7792 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +00007793 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00007794
7795 FindCaptureVisitor visitor(S.Context, owner.Variable);
7796 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00007797 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +00007798}
7799
7800static void diagnoseRetainCycle(Sema &S, Expr *capturer,
7801 RetainCycleOwner &owner) {
7802 assert(capturer);
7803 assert(owner.Variable && owner.Loc.isValid());
7804
7805 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
7806 << owner.Variable << capturer->getSourceRange();
7807 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
7808 << owner.Indirect << owner.Range;
7809}
7810
7811/// Check for a keyword selector that starts with the word 'add' or
7812/// 'set'.
7813static bool isSetterLikeSelector(Selector sel) {
7814 if (sel.isUnarySelector()) return false;
7815
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007816 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00007817 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00007818 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00007819 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00007820 else if (str.startswith("add")) {
7821 // Specially whitelist 'addOperationWithBlock:'.
7822 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
7823 return false;
7824 str = str.substr(3);
7825 }
John McCall31168b02011-06-15 23:02:42 +00007826 else
7827 return false;
7828
7829 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00007830 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00007831}
7832
7833/// Check a message send to see if it's likely to cause a retain cycle.
7834void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
7835 // Only check instance methods whose selector looks like a setter.
7836 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
7837 return;
7838
7839 // Try to find a variable that the receiver is strongly owned by.
7840 RetainCycleOwner owner;
7841 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007842 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00007843 return;
7844 } else {
7845 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
7846 owner.Variable = getCurMethodDecl()->getSelfDecl();
7847 owner.Loc = msg->getSuperLoc();
7848 owner.Range = msg->getSuperLoc();
7849 }
7850
7851 // Check whether the receiver is captured by any of the arguments.
7852 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
7853 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
7854 return diagnoseRetainCycle(*this, capturer, owner);
7855}
7856
7857/// Check a property assign to see if it's likely to cause a retain cycle.
7858void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
7859 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007860 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00007861 return;
7862
7863 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
7864 diagnoseRetainCycle(*this, capturer, owner);
7865}
7866
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007867void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
7868 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +00007869 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007870 return;
7871
7872 // Because we don't have an expression for the variable, we have to set the
7873 // location explicitly here.
7874 Owner.Loc = Var->getLocation();
7875 Owner.Range = Var->getSourceRange();
7876
7877 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
7878 diagnoseRetainCycle(*this, Capturer, Owner);
7879}
7880
Ted Kremenek9304da92012-12-21 08:04:28 +00007881static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
7882 Expr *RHS, bool isProperty) {
7883 // Check if RHS is an Objective-C object literal, which also can get
7884 // immediately zapped in a weak reference. Note that we explicitly
7885 // allow ObjCStringLiterals, since those are designed to never really die.
7886 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00007887
Ted Kremenek64873352012-12-21 22:46:35 +00007888 // This enum needs to match with the 'select' in
7889 // warn_objc_arc_literal_assign (off-by-1).
7890 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
7891 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
7892 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00007893
7894 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00007895 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00007896 << (isProperty ? 0 : 1)
7897 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00007898
7899 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00007900}
7901
Ted Kremenekc1f014a2012-12-21 19:45:30 +00007902static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
7903 Qualifiers::ObjCLifetime LT,
7904 Expr *RHS, bool isProperty) {
7905 // Strip off any implicit cast added to get to the one ARC-specific.
7906 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
7907 if (cast->getCastKind() == CK_ARCConsumeObject) {
7908 S.Diag(Loc, diag::warn_arc_retained_assign)
7909 << (LT == Qualifiers::OCL_ExplicitNone)
7910 << (isProperty ? 0 : 1)
7911 << RHS->getSourceRange();
7912 return true;
7913 }
7914 RHS = cast->getSubExpr();
7915 }
7916
7917 if (LT == Qualifiers::OCL_Weak &&
7918 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
7919 return true;
7920
7921 return false;
7922}
7923
Ted Kremenekb36234d2012-12-21 08:04:20 +00007924bool Sema::checkUnsafeAssigns(SourceLocation Loc,
7925 QualType LHS, Expr *RHS) {
7926 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
7927
7928 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
7929 return false;
7930
7931 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
7932 return true;
7933
7934 return false;
7935}
7936
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007937void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
7938 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007939 QualType LHSType;
7940 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00007941 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007942 ObjCPropertyRefExpr *PRE
7943 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
7944 if (PRE && !PRE->isImplicitProperty()) {
7945 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
7946 if (PD)
7947 LHSType = PD->getType();
7948 }
7949
7950 if (LHSType.isNull())
7951 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00007952
7953 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
7954
7955 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007956 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +00007957 getCurFunction()->markSafeWeakUse(LHS);
7958 }
7959
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007960 if (checkUnsafeAssigns(Loc, LHSType, RHS))
7961 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00007962
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007963 // FIXME. Check for other life times.
7964 if (LT != Qualifiers::OCL_None)
7965 return;
7966
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007967 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007968 if (PRE->isImplicitProperty())
7969 return;
7970 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
7971 if (!PD)
7972 return;
7973
Bill Wendling44426052012-12-20 19:22:21 +00007974 unsigned Attributes = PD->getPropertyAttributes();
7975 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007976 // when 'assign' attribute was not explicitly specified
7977 // by user, ignore it and rely on property type itself
7978 // for lifetime info.
7979 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
7980 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
7981 LHSType->isObjCRetainableType())
7982 return;
7983
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007984 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00007985 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007986 Diag(Loc, diag::warn_arc_retained_property_assign)
7987 << RHS->getSourceRange();
7988 return;
7989 }
7990 RHS = cast->getSubExpr();
7991 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007992 }
Bill Wendling44426052012-12-20 19:22:21 +00007993 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00007994 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
7995 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00007996 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007997 }
7998}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00007999
8000//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
8001
8002namespace {
8003bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
8004 SourceLocation StmtLoc,
8005 const NullStmt *Body) {
8006 // Do not warn if the body is a macro that expands to nothing, e.g:
8007 //
8008 // #define CALL(x)
8009 // if (condition)
8010 // CALL(0);
8011 //
8012 if (Body->hasLeadingEmptyMacro())
8013 return false;
8014
8015 // Get line numbers of statement and body.
8016 bool StmtLineInvalid;
8017 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
8018 &StmtLineInvalid);
8019 if (StmtLineInvalid)
8020 return false;
8021
8022 bool BodyLineInvalid;
8023 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
8024 &BodyLineInvalid);
8025 if (BodyLineInvalid)
8026 return false;
8027
8028 // Warn if null statement and body are on the same line.
8029 if (StmtLine != BodyLine)
8030 return false;
8031
8032 return true;
8033}
8034} // Unnamed namespace
8035
8036void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
8037 const Stmt *Body,
8038 unsigned DiagID) {
8039 // Since this is a syntactic check, don't emit diagnostic for template
8040 // instantiations, this just adds noise.
8041 if (CurrentInstantiationScope)
8042 return;
8043
8044 // The body should be a null statement.
8045 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
8046 if (!NBody)
8047 return;
8048
8049 // Do the usual checks.
8050 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
8051 return;
8052
8053 Diag(NBody->getSemiLoc(), DiagID);
8054 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
8055}
8056
8057void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
8058 const Stmt *PossibleBody) {
8059 assert(!CurrentInstantiationScope); // Ensured by caller
8060
8061 SourceLocation StmtLoc;
8062 const Stmt *Body;
8063 unsigned DiagID;
8064 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
8065 StmtLoc = FS->getRParenLoc();
8066 Body = FS->getBody();
8067 DiagID = diag::warn_empty_for_body;
8068 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
8069 StmtLoc = WS->getCond()->getSourceRange().getEnd();
8070 Body = WS->getBody();
8071 DiagID = diag::warn_empty_while_body;
8072 } else
8073 return; // Neither `for' nor `while'.
8074
8075 // The body should be a null statement.
8076 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
8077 if (!NBody)
8078 return;
8079
8080 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008081 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00008082 return;
8083
8084 // Do the usual checks.
8085 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
8086 return;
8087
8088 // `for(...);' and `while(...);' are popular idioms, so in order to keep
8089 // noise level low, emit diagnostics only if for/while is followed by a
8090 // CompoundStmt, e.g.:
8091 // for (int i = 0; i < n; i++);
8092 // {
8093 // a(i);
8094 // }
8095 // or if for/while is followed by a statement with more indentation
8096 // than for/while itself:
8097 // for (int i = 0; i < n; i++);
8098 // a(i);
8099 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
8100 if (!ProbableTypo) {
8101 bool BodyColInvalid;
8102 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
8103 PossibleBody->getLocStart(),
8104 &BodyColInvalid);
8105 if (BodyColInvalid)
8106 return;
8107
8108 bool StmtColInvalid;
8109 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
8110 S->getLocStart(),
8111 &StmtColInvalid);
8112 if (StmtColInvalid)
8113 return;
8114
8115 if (BodyCol > StmtCol)
8116 ProbableTypo = true;
8117 }
8118
8119 if (ProbableTypo) {
8120 Diag(NBody->getSemiLoc(), DiagID);
8121 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
8122 }
8123}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008124
8125//===--- Layout compatibility ----------------------------------------------//
8126
8127namespace {
8128
8129bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
8130
8131/// \brief Check if two enumeration types are layout-compatible.
8132bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
8133 // C++11 [dcl.enum] p8:
8134 // Two enumeration types are layout-compatible if they have the same
8135 // underlying type.
8136 return ED1->isComplete() && ED2->isComplete() &&
8137 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
8138}
8139
8140/// \brief Check if two fields are layout-compatible.
8141bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
8142 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
8143 return false;
8144
8145 if (Field1->isBitField() != Field2->isBitField())
8146 return false;
8147
8148 if (Field1->isBitField()) {
8149 // Make sure that the bit-fields are the same length.
8150 unsigned Bits1 = Field1->getBitWidthValue(C);
8151 unsigned Bits2 = Field2->getBitWidthValue(C);
8152
8153 if (Bits1 != Bits2)
8154 return false;
8155 }
8156
8157 return true;
8158}
8159
8160/// \brief Check if two standard-layout structs are layout-compatible.
8161/// (C++11 [class.mem] p17)
8162bool isLayoutCompatibleStruct(ASTContext &C,
8163 RecordDecl *RD1,
8164 RecordDecl *RD2) {
8165 // If both records are C++ classes, check that base classes match.
8166 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
8167 // If one of records is a CXXRecordDecl we are in C++ mode,
8168 // thus the other one is a CXXRecordDecl, too.
8169 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
8170 // Check number of base classes.
8171 if (D1CXX->getNumBases() != D2CXX->getNumBases())
8172 return false;
8173
8174 // Check the base classes.
8175 for (CXXRecordDecl::base_class_const_iterator
8176 Base1 = D1CXX->bases_begin(),
8177 BaseEnd1 = D1CXX->bases_end(),
8178 Base2 = D2CXX->bases_begin();
8179 Base1 != BaseEnd1;
8180 ++Base1, ++Base2) {
8181 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
8182 return false;
8183 }
8184 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
8185 // If only RD2 is a C++ class, it should have zero base classes.
8186 if (D2CXX->getNumBases() > 0)
8187 return false;
8188 }
8189
8190 // Check the fields.
8191 RecordDecl::field_iterator Field2 = RD2->field_begin(),
8192 Field2End = RD2->field_end(),
8193 Field1 = RD1->field_begin(),
8194 Field1End = RD1->field_end();
8195 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
8196 if (!isLayoutCompatible(C, *Field1, *Field2))
8197 return false;
8198 }
8199 if (Field1 != Field1End || Field2 != Field2End)
8200 return false;
8201
8202 return true;
8203}
8204
8205/// \brief Check if two standard-layout unions are layout-compatible.
8206/// (C++11 [class.mem] p18)
8207bool isLayoutCompatibleUnion(ASTContext &C,
8208 RecordDecl *RD1,
8209 RecordDecl *RD2) {
8210 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008211 for (auto *Field2 : RD2->fields())
8212 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008213
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008214 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008215 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
8216 I = UnmatchedFields.begin(),
8217 E = UnmatchedFields.end();
8218
8219 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008220 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008221 bool Result = UnmatchedFields.erase(*I);
8222 (void) Result;
8223 assert(Result);
8224 break;
8225 }
8226 }
8227 if (I == E)
8228 return false;
8229 }
8230
8231 return UnmatchedFields.empty();
8232}
8233
8234bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
8235 if (RD1->isUnion() != RD2->isUnion())
8236 return false;
8237
8238 if (RD1->isUnion())
8239 return isLayoutCompatibleUnion(C, RD1, RD2);
8240 else
8241 return isLayoutCompatibleStruct(C, RD1, RD2);
8242}
8243
8244/// \brief Check if two types are layout-compatible in C++11 sense.
8245bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
8246 if (T1.isNull() || T2.isNull())
8247 return false;
8248
8249 // C++11 [basic.types] p11:
8250 // If two types T1 and T2 are the same type, then T1 and T2 are
8251 // layout-compatible types.
8252 if (C.hasSameType(T1, T2))
8253 return true;
8254
8255 T1 = T1.getCanonicalType().getUnqualifiedType();
8256 T2 = T2.getCanonicalType().getUnqualifiedType();
8257
8258 const Type::TypeClass TC1 = T1->getTypeClass();
8259 const Type::TypeClass TC2 = T2->getTypeClass();
8260
8261 if (TC1 != TC2)
8262 return false;
8263
8264 if (TC1 == Type::Enum) {
8265 return isLayoutCompatible(C,
8266 cast<EnumType>(T1)->getDecl(),
8267 cast<EnumType>(T2)->getDecl());
8268 } else if (TC1 == Type::Record) {
8269 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
8270 return false;
8271
8272 return isLayoutCompatible(C,
8273 cast<RecordType>(T1)->getDecl(),
8274 cast<RecordType>(T2)->getDecl());
8275 }
8276
8277 return false;
8278}
8279}
8280
8281//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
8282
8283namespace {
8284/// \brief Given a type tag expression find the type tag itself.
8285///
8286/// \param TypeExpr Type tag expression, as it appears in user's code.
8287///
8288/// \param VD Declaration of an identifier that appears in a type tag.
8289///
8290/// \param MagicValue Type tag magic value.
8291bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
8292 const ValueDecl **VD, uint64_t *MagicValue) {
8293 while(true) {
8294 if (!TypeExpr)
8295 return false;
8296
8297 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
8298
8299 switch (TypeExpr->getStmtClass()) {
8300 case Stmt::UnaryOperatorClass: {
8301 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
8302 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
8303 TypeExpr = UO->getSubExpr();
8304 continue;
8305 }
8306 return false;
8307 }
8308
8309 case Stmt::DeclRefExprClass: {
8310 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
8311 *VD = DRE->getDecl();
8312 return true;
8313 }
8314
8315 case Stmt::IntegerLiteralClass: {
8316 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
8317 llvm::APInt MagicValueAPInt = IL->getValue();
8318 if (MagicValueAPInt.getActiveBits() <= 64) {
8319 *MagicValue = MagicValueAPInt.getZExtValue();
8320 return true;
8321 } else
8322 return false;
8323 }
8324
8325 case Stmt::BinaryConditionalOperatorClass:
8326 case Stmt::ConditionalOperatorClass: {
8327 const AbstractConditionalOperator *ACO =
8328 cast<AbstractConditionalOperator>(TypeExpr);
8329 bool Result;
8330 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
8331 if (Result)
8332 TypeExpr = ACO->getTrueExpr();
8333 else
8334 TypeExpr = ACO->getFalseExpr();
8335 continue;
8336 }
8337 return false;
8338 }
8339
8340 case Stmt::BinaryOperatorClass: {
8341 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
8342 if (BO->getOpcode() == BO_Comma) {
8343 TypeExpr = BO->getRHS();
8344 continue;
8345 }
8346 return false;
8347 }
8348
8349 default:
8350 return false;
8351 }
8352 }
8353}
8354
8355/// \brief Retrieve the C type corresponding to type tag TypeExpr.
8356///
8357/// \param TypeExpr Expression that specifies a type tag.
8358///
8359/// \param MagicValues Registered magic values.
8360///
8361/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
8362/// kind.
8363///
8364/// \param TypeInfo Information about the corresponding C type.
8365///
8366/// \returns true if the corresponding C type was found.
8367bool GetMatchingCType(
8368 const IdentifierInfo *ArgumentKind,
8369 const Expr *TypeExpr, const ASTContext &Ctx,
8370 const llvm::DenseMap<Sema::TypeTagMagicValue,
8371 Sema::TypeTagData> *MagicValues,
8372 bool &FoundWrongKind,
8373 Sema::TypeTagData &TypeInfo) {
8374 FoundWrongKind = false;
8375
8376 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +00008377 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008378
8379 uint64_t MagicValue;
8380
8381 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
8382 return false;
8383
8384 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +00008385 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008386 if (I->getArgumentKind() != ArgumentKind) {
8387 FoundWrongKind = true;
8388 return false;
8389 }
8390 TypeInfo.Type = I->getMatchingCType();
8391 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
8392 TypeInfo.MustBeNull = I->getMustBeNull();
8393 return true;
8394 }
8395 return false;
8396 }
8397
8398 if (!MagicValues)
8399 return false;
8400
8401 llvm::DenseMap<Sema::TypeTagMagicValue,
8402 Sema::TypeTagData>::const_iterator I =
8403 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
8404 if (I == MagicValues->end())
8405 return false;
8406
8407 TypeInfo = I->second;
8408 return true;
8409}
8410} // unnamed namespace
8411
8412void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
8413 uint64_t MagicValue, QualType Type,
8414 bool LayoutCompatible,
8415 bool MustBeNull) {
8416 if (!TypeTagForDatatypeMagicValues)
8417 TypeTagForDatatypeMagicValues.reset(
8418 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
8419
8420 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
8421 (*TypeTagForDatatypeMagicValues)[Magic] =
8422 TypeTagData(Type, LayoutCompatible, MustBeNull);
8423}
8424
8425namespace {
8426bool IsSameCharType(QualType T1, QualType T2) {
8427 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
8428 if (!BT1)
8429 return false;
8430
8431 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
8432 if (!BT2)
8433 return false;
8434
8435 BuiltinType::Kind T1Kind = BT1->getKind();
8436 BuiltinType::Kind T2Kind = BT2->getKind();
8437
8438 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
8439 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
8440 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
8441 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
8442}
8443} // unnamed namespace
8444
8445void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
8446 const Expr * const *ExprArgs) {
8447 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
8448 bool IsPointerAttr = Attr->getIsPointer();
8449
8450 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
8451 bool FoundWrongKind;
8452 TypeTagData TypeInfo;
8453 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
8454 TypeTagForDatatypeMagicValues.get(),
8455 FoundWrongKind, TypeInfo)) {
8456 if (FoundWrongKind)
8457 Diag(TypeTagExpr->getExprLoc(),
8458 diag::warn_type_tag_for_datatype_wrong_kind)
8459 << TypeTagExpr->getSourceRange();
8460 return;
8461 }
8462
8463 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
8464 if (IsPointerAttr) {
8465 // Skip implicit cast of pointer to `void *' (as a function argument).
8466 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +00008467 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +00008468 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008469 ArgumentExpr = ICE->getSubExpr();
8470 }
8471 QualType ArgumentType = ArgumentExpr->getType();
8472
8473 // Passing a `void*' pointer shouldn't trigger a warning.
8474 if (IsPointerAttr && ArgumentType->isVoidPointerType())
8475 return;
8476
8477 if (TypeInfo.MustBeNull) {
8478 // Type tag with matching void type requires a null pointer.
8479 if (!ArgumentExpr->isNullPointerConstant(Context,
8480 Expr::NPC_ValueDependentIsNotNull)) {
8481 Diag(ArgumentExpr->getExprLoc(),
8482 diag::warn_type_safety_null_pointer_required)
8483 << ArgumentKind->getName()
8484 << ArgumentExpr->getSourceRange()
8485 << TypeTagExpr->getSourceRange();
8486 }
8487 return;
8488 }
8489
8490 QualType RequiredType = TypeInfo.Type;
8491 if (IsPointerAttr)
8492 RequiredType = Context.getPointerType(RequiredType);
8493
8494 bool mismatch = false;
8495 if (!TypeInfo.LayoutCompatible) {
8496 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
8497
8498 // C++11 [basic.fundamental] p1:
8499 // Plain char, signed char, and unsigned char are three distinct types.
8500 //
8501 // But we treat plain `char' as equivalent to `signed char' or `unsigned
8502 // char' depending on the current char signedness mode.
8503 if (mismatch)
8504 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
8505 RequiredType->getPointeeType())) ||
8506 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
8507 mismatch = false;
8508 } else
8509 if (IsPointerAttr)
8510 mismatch = !isLayoutCompatible(Context,
8511 ArgumentType->getPointeeType(),
8512 RequiredType->getPointeeType());
8513 else
8514 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
8515
8516 if (mismatch)
8517 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +00008518 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008519 << TypeInfo.LayoutCompatible << RequiredType
8520 << ArgumentExpr->getSourceRange()
8521 << TypeTagExpr->getSourceRange();
8522}
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008523