blob: 89e5e3e5af193a9508ac08ab32e79e06bdfb749d [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"
Alexey Bataev1a3320e2015-08-25 14:24:04 +000024#include "clang/AST/ExprOpenMP.h"
Mike Stump0c2ec772010-01-21 03:59:47 +000025#include "clang/AST/StmtCXX.h"
26#include "clang/AST/StmtObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000027#include "clang/Analysis/Analyses/FormatString.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000028#include "clang/Basic/CharInfo.h"
Eric Christopher8d0c6212010-04-17 02:26:23 +000029#include "clang/Basic/TargetBuiltins.h"
Nate Begeman4904e322010-06-08 02:47:44 +000030#include "clang/Basic/TargetInfo.h"
Alp Tokerb6cc5922014-05-03 03:45:55 +000031#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "clang/Sema/Initialization.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000033#include "clang/Sema/Lookup.h"
34#include "clang/Sema/ScopeInfo.h"
35#include "clang/Sema/Sema.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000036#include "llvm/ADT/STLExtras.h"
Richard Smithd7293d72013-08-05 18:49:43 +000037#include "llvm/ADT/SmallBitVector.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000038#include "llvm/ADT/SmallString.h"
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +000039#include "llvm/Support/Format.h"
40#include "llvm/Support/Locale.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000041#include "llvm/Support/ConvertUTF.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000042#include "llvm/Support/raw_ostream.h"
Zhongxing Xu050379b2009-05-20 01:55:10 +000043#include <limits>
Eugene Zelenko1ced5092016-02-12 22:53:10 +000044
Chris Lattnerb87b1b32007-08-10 20:18:51 +000045using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000046using namespace sema;
Chris Lattnerb87b1b32007-08-10 20:18:51 +000047
Chris Lattnera26fb342009-02-18 17:49:48 +000048SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
49 unsigned ByteNo) const {
Alp Tokerb6cc5922014-05-03 03:45:55 +000050 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
51 Context.getTargetInfo());
Chris Lattnera26fb342009-02-18 17:49:48 +000052}
53
John McCallbebede42011-02-26 05:39:39 +000054/// Checks that a call expression's argument count is the desired number.
55/// This is useful when doing custom type-checking. Returns true on error.
56static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
57 unsigned argCount = call->getNumArgs();
58 if (argCount == desiredArgCount) return false;
59
60 if (argCount < desiredArgCount)
61 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
62 << 0 /*function call*/ << desiredArgCount << argCount
63 << call->getSourceRange();
64
65 // Highlight all the excess arguments.
66 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
67 call->getArg(argCount - 1)->getLocEnd());
68
69 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
70 << 0 /*function call*/ << desiredArgCount << argCount
71 << call->getArg(1)->getSourceRange();
72}
73
Julien Lerouge4a5b4442012-04-28 17:39:16 +000074/// Check that the first argument to __builtin_annotation is an integer
75/// and the second argument is a non-wide string literal.
76static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
77 if (checkArgCount(S, TheCall, 2))
78 return true;
79
80 // First argument should be an integer.
81 Expr *ValArg = TheCall->getArg(0);
82 QualType Ty = ValArg->getType();
83 if (!Ty->isIntegerType()) {
84 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
85 << ValArg->getSourceRange();
Julien Lerouge5a6b6982011-09-09 22:41:49 +000086 return true;
87 }
Julien Lerouge4a5b4442012-04-28 17:39:16 +000088
89 // Second argument should be a constant string.
90 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
91 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
92 if (!Literal || !Literal->isAscii()) {
93 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
94 << StrArg->getSourceRange();
95 return true;
96 }
97
98 TheCall->setType(Ty);
Julien Lerouge5a6b6982011-09-09 22:41:49 +000099 return false;
100}
101
Richard Smith6cbd65d2013-07-11 02:27:57 +0000102/// Check that the argument to __builtin_addressof is a glvalue, and set the
103/// result type to the corresponding pointer type.
104static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
105 if (checkArgCount(S, TheCall, 1))
106 return true;
107
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000108 ExprResult Arg(TheCall->getArg(0));
Richard Smith6cbd65d2013-07-11 02:27:57 +0000109 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
110 if (ResultType.isNull())
111 return true;
112
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000113 TheCall->setArg(0, Arg.get());
Richard Smith6cbd65d2013-07-11 02:27:57 +0000114 TheCall->setType(ResultType);
115 return false;
116}
117
John McCall03107a42015-10-29 20:48:01 +0000118static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
119 if (checkArgCount(S, TheCall, 3))
120 return true;
121
122 // First two arguments should be integers.
123 for (unsigned I = 0; I < 2; ++I) {
124 Expr *Arg = TheCall->getArg(I);
125 QualType Ty = Arg->getType();
126 if (!Ty->isIntegerType()) {
127 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
128 << Ty << Arg->getSourceRange();
129 return true;
130 }
131 }
132
133 // Third argument should be a pointer to a non-const integer.
134 // IRGen correctly handles volatile, restrict, and address spaces, and
135 // the other qualifiers aren't possible.
136 {
137 Expr *Arg = TheCall->getArg(2);
138 QualType Ty = Arg->getType();
139 const auto *PtrTy = Ty->getAs<PointerType>();
140 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
141 !PtrTy->getPointeeType().isConstQualified())) {
142 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
143 << Ty << Arg->getSourceRange();
144 return true;
145 }
146 }
147
148 return false;
149}
150
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000151static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
152 CallExpr *TheCall, unsigned SizeIdx,
153 unsigned DstSizeIdx) {
154 if (TheCall->getNumArgs() <= SizeIdx ||
155 TheCall->getNumArgs() <= DstSizeIdx)
156 return;
157
158 const Expr *SizeArg = TheCall->getArg(SizeIdx);
159 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
160
161 llvm::APSInt Size, DstSize;
162
163 // find out if both sizes are known at compile time
164 if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
165 !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
166 return;
167
168 if (Size.ule(DstSize))
169 return;
170
171 // confirmed overflow so generate the diagnostic.
172 IdentifierInfo *FnName = FDecl->getIdentifier();
173 SourceLocation SL = TheCall->getLocStart();
174 SourceRange SR = TheCall->getSourceRange();
175
176 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
177}
178
Peter Collingbournef7706832014-12-12 23:41:25 +0000179static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
180 if (checkArgCount(S, BuiltinCall, 2))
181 return true;
182
183 SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
184 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
185 Expr *Call = BuiltinCall->getArg(0);
186 Expr *Chain = BuiltinCall->getArg(1);
187
188 if (Call->getStmtClass() != Stmt::CallExprClass) {
189 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
190 << Call->getSourceRange();
191 return true;
192 }
193
194 auto CE = cast<CallExpr>(Call);
195 if (CE->getCallee()->getType()->isBlockPointerType()) {
196 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
197 << Call->getSourceRange();
198 return true;
199 }
200
201 const Decl *TargetDecl = CE->getCalleeDecl();
202 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
203 if (FD->getBuiltinID()) {
204 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
205 << Call->getSourceRange();
206 return true;
207 }
208
209 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
210 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
211 << Call->getSourceRange();
212 return true;
213 }
214
215 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
216 if (ChainResult.isInvalid())
217 return true;
218 if (!ChainResult.get()->getType()->isPointerType()) {
219 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
220 << Chain->getSourceRange();
221 return true;
222 }
223
David Majnemerced8bdf2015-02-25 17:36:15 +0000224 QualType ReturnTy = CE->getCallReturnType(S.Context);
Peter Collingbournef7706832014-12-12 23:41:25 +0000225 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
226 QualType BuiltinTy = S.Context.getFunctionType(
227 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
228 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
229
230 Builtin =
231 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
232
233 BuiltinCall->setType(CE->getType());
234 BuiltinCall->setValueKind(CE->getValueKind());
235 BuiltinCall->setObjectKind(CE->getObjectKind());
236 BuiltinCall->setCallee(Builtin);
237 BuiltinCall->setArg(1, ChainResult.get());
238
239 return false;
240}
241
Reid Kleckner1d59f992015-01-22 01:36:17 +0000242static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
243 Scope::ScopeFlags NeededScopeFlags,
244 unsigned DiagID) {
245 // Scopes aren't available during instantiation. Fortunately, builtin
246 // functions cannot be template args so they cannot be formed through template
247 // instantiation. Therefore checking once during the parse is sufficient.
248 if (!SemaRef.ActiveTemplateInstantiations.empty())
249 return false;
250
251 Scope *S = SemaRef.getCurScope();
252 while (S && !S->isSEHExceptScope())
253 S = S->getParent();
254 if (!S || !(S->getFlags() & NeededScopeFlags)) {
255 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
256 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
257 << DRE->getDecl()->getIdentifier();
258 return true;
259 }
260
261 return false;
262}
263
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000264/// Returns OpenCL access qual.
Xiuli Pan11e13f62016-02-26 03:13:03 +0000265static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
Xiuli Pan11e13f62016-02-26 03:13:03 +0000266 return D->getAttr<OpenCLAccessAttr>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000267}
268
269/// Returns true if pipe element type is different from the pointer.
270static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
271 const Expr *Arg0 = Call->getArg(0);
272 // First argument type should always be pipe.
273 if (!Arg0->getType()->isPipeType()) {
274 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000275 << Call->getDirectCallee() << Arg0->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000276 return true;
277 }
Xiuli Pan11e13f62016-02-26 03:13:03 +0000278 OpenCLAccessAttr *AccessQual =
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000279 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
280 // Validates the access qualifier is compatible with the call.
281 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
282 // read_only and write_only, and assumed to be read_only if no qualifier is
283 // specified.
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000284 switch (Call->getDirectCallee()->getBuiltinID()) {
285 case Builtin::BIread_pipe:
286 case Builtin::BIreserve_read_pipe:
287 case Builtin::BIcommit_read_pipe:
288 case Builtin::BIwork_group_reserve_read_pipe:
289 case Builtin::BIsub_group_reserve_read_pipe:
290 case Builtin::BIwork_group_commit_read_pipe:
291 case Builtin::BIsub_group_commit_read_pipe:
292 if (!(!AccessQual || AccessQual->isReadOnly())) {
293 S.Diag(Arg0->getLocStart(),
294 diag::err_opencl_builtin_pipe_invalid_access_modifier)
295 << "read_only" << Arg0->getSourceRange();
296 return true;
297 }
298 break;
299 case Builtin::BIwrite_pipe:
300 case Builtin::BIreserve_write_pipe:
301 case Builtin::BIcommit_write_pipe:
302 case Builtin::BIwork_group_reserve_write_pipe:
303 case Builtin::BIsub_group_reserve_write_pipe:
304 case Builtin::BIwork_group_commit_write_pipe:
305 case Builtin::BIsub_group_commit_write_pipe:
306 if (!(AccessQual && AccessQual->isWriteOnly())) {
307 S.Diag(Arg0->getLocStart(),
308 diag::err_opencl_builtin_pipe_invalid_access_modifier)
309 << "write_only" << Arg0->getSourceRange();
310 return true;
311 }
312 break;
313 default:
314 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000315 }
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000316 return false;
317}
318
319/// Returns true if pipe element type is different from the pointer.
320static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
321 const Expr *Arg0 = Call->getArg(0);
322 const Expr *ArgIdx = Call->getArg(Idx);
323 const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000324 const QualType EltTy = PipeTy->getElementType();
325 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000326 // The Idx argument should be a pointer and the type of the pointer and
327 // the type of pipe element should also be the same.
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000328 if (!ArgTy ||
329 !S.Context.hasSameType(
330 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000331 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000332 << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000333 << ArgIdx->getType() << ArgIdx->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000334 return true;
335 }
336 return false;
337}
338
339// \brief Performs semantic analysis for the read/write_pipe call.
340// \param S Reference to the semantic analyzer.
341// \param Call A pointer to the builtin call.
342// \return True if a semantic error has been found, false otherwise.
343static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000344 // OpenCL v2.0 s6.13.16.2 - The built-in read/write
345 // functions have two forms.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000346 switch (Call->getNumArgs()) {
347 case 2: {
348 if (checkOpenCLPipeArg(S, Call))
349 return true;
350 // The call with 2 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000351 // read/write_pipe(pipe T, T*).
352 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000353 if (checkOpenCLPipePacketType(S, Call, 1))
354 return true;
355 } break;
356
357 case 4: {
358 if (checkOpenCLPipeArg(S, Call))
359 return true;
360 // The call with 4 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000361 // read/write_pipe(pipe T, reserve_id_t, uint, T*).
362 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000363 if (!Call->getArg(1)->getType()->isReserveIDT()) {
364 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000365 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000366 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000367 return true;
368 }
369
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000370 // Check the index.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000371 const Expr *Arg2 = Call->getArg(2);
372 if (!Arg2->getType()->isIntegerType() &&
373 !Arg2->getType()->isUnsignedIntegerType()) {
374 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000375 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000376 << Arg2->getType() << Arg2->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000377 return true;
378 }
379
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000380 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000381 if (checkOpenCLPipePacketType(S, Call, 3))
382 return true;
383 } break;
384 default:
385 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000386 << Call->getDirectCallee() << Call->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000387 return true;
388 }
389
390 return false;
391}
392
393// \brief Performs a semantic analysis on the {work_group_/sub_group_
394// /_}reserve_{read/write}_pipe
395// \param S Reference to the semantic analyzer.
396// \param Call The call to the builtin function to be analyzed.
397// \return True if a semantic error was found, false otherwise.
398static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
399 if (checkArgCount(S, Call, 2))
400 return true;
401
402 if (checkOpenCLPipeArg(S, Call))
403 return true;
404
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000405 // Check the reserve size.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000406 if (!Call->getArg(1)->getType()->isIntegerType() &&
407 !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
408 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000409 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000410 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000411 return true;
412 }
413
414 return false;
415}
416
417// \brief Performs a semantic analysis on {work_group_/sub_group_
418// /_}commit_{read/write}_pipe
419// \param S Reference to the semantic analyzer.
420// \param Call The call to the builtin function to be analyzed.
421// \return True if a semantic error was found, false otherwise.
422static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
423 if (checkArgCount(S, Call, 2))
424 return true;
425
426 if (checkOpenCLPipeArg(S, Call))
427 return true;
428
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000429 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000430 if (!Call->getArg(1)->getType()->isReserveIDT()) {
431 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000432 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000433 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000434 return true;
435 }
436
437 return false;
438}
439
440// \brief Performs a semantic analysis on the call to built-in Pipe
441// Query Functions.
442// \param S Reference to the semantic analyzer.
443// \param Call The call to the builtin function to be analyzed.
444// \return True if a semantic error was found, false otherwise.
445static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
446 if (checkArgCount(S, Call, 1))
447 return true;
448
449 if (!Call->getArg(0)->getType()->isPipeType()) {
450 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000451 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000452 return true;
453 }
454
455 return false;
456}
457
Yaxun Liuf7449a12016-05-20 19:54:38 +0000458// \brief Performs semantic analysis for the to_global/local/private call.
459// \param S Reference to the semantic analyzer.
460// \param BuiltinID ID of the builtin function.
461// \param Call A pointer to the builtin call.
462// \return True if a semantic error has been found, false otherwise.
463static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
464 CallExpr *Call) {
465 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
466 if (S.getLangOpts().OpenCLVersion < 200) {
467 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_requires_version)
468 << Call->getDirectCallee() << "2.0" << 1 << Call->getSourceRange();
469 return true;
470 }
471
472 if (Call->getNumArgs() != 1) {
473 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
474 << Call->getDirectCallee() << Call->getSourceRange();
475 return true;
476 }
477
478 auto RT = Call->getArg(0)->getType();
479 if (!RT->isPointerType() || RT->getPointeeType()
480 .getAddressSpace() == LangAS::opencl_constant) {
481 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
482 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
483 return true;
484 }
485
486 RT = RT->getPointeeType();
487 auto Qual = RT.getQualifiers();
488 switch (BuiltinID) {
489 case Builtin::BIto_global:
490 Qual.setAddressSpace(LangAS::opencl_global);
491 break;
492 case Builtin::BIto_local:
493 Qual.setAddressSpace(LangAS::opencl_local);
494 break;
495 default:
496 Qual.removeAddressSpace();
497 }
498 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
499 RT.getUnqualifiedType(), Qual)));
500
501 return false;
502}
503
John McCalldadc5752010-08-24 06:29:42 +0000504ExprResult
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000505Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
506 CallExpr *TheCall) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000507 ExprResult TheCallResult(TheCall);
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000508
Chris Lattner3be167f2010-10-01 23:23:24 +0000509 // Find out if any arguments are required to be integer constant expressions.
510 unsigned ICEArguments = 0;
511 ASTContext::GetBuiltinTypeError Error;
512 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
513 if (Error != ASTContext::GE_None)
514 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
515
516 // If any arguments are required to be ICE's, check and diagnose.
517 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
518 // Skip arguments not required to be ICE's.
519 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
520
521 llvm::APSInt Result;
522 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
523 return true;
524 ICEArguments &= ~(1 << ArgNo);
525 }
526
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000527 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000528 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000529 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000530 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000531 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000532 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000533 break;
Ted Kremeneka174c522008-07-09 17:58:53 +0000534 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000535 case Builtin::BI__builtin_va_start:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000536 if (SemaBuiltinVAStart(TheCall))
537 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000538 break;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000539 case Builtin::BI__va_start: {
540 switch (Context.getTargetInfo().getTriple().getArch()) {
541 case llvm::Triple::arm:
542 case llvm::Triple::thumb:
543 if (SemaBuiltinVAStartARM(TheCall))
544 return ExprError();
545 break;
546 default:
547 if (SemaBuiltinVAStart(TheCall))
548 return ExprError();
549 break;
550 }
551 break;
552 }
Chris Lattner2da14fb2007-12-20 00:26:33 +0000553 case Builtin::BI__builtin_isgreater:
554 case Builtin::BI__builtin_isgreaterequal:
555 case Builtin::BI__builtin_isless:
556 case Builtin::BI__builtin_islessequal:
557 case Builtin::BI__builtin_islessgreater:
558 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000559 if (SemaBuiltinUnorderedCompare(TheCall))
560 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000561 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000562 case Builtin::BI__builtin_fpclassify:
563 if (SemaBuiltinFPClassification(TheCall, 6))
564 return ExprError();
565 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000566 case Builtin::BI__builtin_isfinite:
567 case Builtin::BI__builtin_isinf:
568 case Builtin::BI__builtin_isinf_sign:
569 case Builtin::BI__builtin_isnan:
570 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000571 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000572 return ExprError();
573 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000574 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000575 return SemaBuiltinShuffleVector(TheCall);
576 // TheCall will be freed by the smart pointer here, but that's fine, since
577 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000578 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000579 if (SemaBuiltinPrefetch(TheCall))
580 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000581 break;
Hal Finkelf0417332014-07-17 14:25:55 +0000582 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +0000583 case Builtin::BI__builtin_assume:
Hal Finkelf0417332014-07-17 14:25:55 +0000584 if (SemaBuiltinAssume(TheCall))
585 return ExprError();
586 break;
Hal Finkelbcc06082014-09-07 22:58:14 +0000587 case Builtin::BI__builtin_assume_aligned:
588 if (SemaBuiltinAssumeAligned(TheCall))
589 return ExprError();
590 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000591 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000592 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000593 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000594 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000595 case Builtin::BI__builtin_longjmp:
596 if (SemaBuiltinLongjmp(TheCall))
597 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000598 break;
Joerg Sonnenberger27173282015-03-11 23:46:32 +0000599 case Builtin::BI__builtin_setjmp:
600 if (SemaBuiltinSetjmp(TheCall))
601 return ExprError();
602 break;
David Majnemerc403a1c2015-03-20 17:03:35 +0000603 case Builtin::BI_setjmp:
604 case Builtin::BI_setjmpex:
605 if (checkArgCount(*this, TheCall, 1))
606 return true;
607 break;
John McCallbebede42011-02-26 05:39:39 +0000608
609 case Builtin::BI__builtin_classify_type:
610 if (checkArgCount(*this, TheCall, 1)) return true;
611 TheCall->setType(Context.IntTy);
612 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000613 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000614 if (checkArgCount(*this, TheCall, 1)) return true;
615 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000616 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000617 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000618 case Builtin::BI__sync_fetch_and_add_1:
619 case Builtin::BI__sync_fetch_and_add_2:
620 case Builtin::BI__sync_fetch_and_add_4:
621 case Builtin::BI__sync_fetch_and_add_8:
622 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000623 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000624 case Builtin::BI__sync_fetch_and_sub_1:
625 case Builtin::BI__sync_fetch_and_sub_2:
626 case Builtin::BI__sync_fetch_and_sub_4:
627 case Builtin::BI__sync_fetch_and_sub_8:
628 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000629 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000630 case Builtin::BI__sync_fetch_and_or_1:
631 case Builtin::BI__sync_fetch_and_or_2:
632 case Builtin::BI__sync_fetch_and_or_4:
633 case Builtin::BI__sync_fetch_and_or_8:
634 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000635 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000636 case Builtin::BI__sync_fetch_and_and_1:
637 case Builtin::BI__sync_fetch_and_and_2:
638 case Builtin::BI__sync_fetch_and_and_4:
639 case Builtin::BI__sync_fetch_and_and_8:
640 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000641 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000642 case Builtin::BI__sync_fetch_and_xor_1:
643 case Builtin::BI__sync_fetch_and_xor_2:
644 case Builtin::BI__sync_fetch_and_xor_4:
645 case Builtin::BI__sync_fetch_and_xor_8:
646 case Builtin::BI__sync_fetch_and_xor_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000647 case Builtin::BI__sync_fetch_and_nand:
648 case Builtin::BI__sync_fetch_and_nand_1:
649 case Builtin::BI__sync_fetch_and_nand_2:
650 case Builtin::BI__sync_fetch_and_nand_4:
651 case Builtin::BI__sync_fetch_and_nand_8:
652 case Builtin::BI__sync_fetch_and_nand_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000653 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000654 case Builtin::BI__sync_add_and_fetch_1:
655 case Builtin::BI__sync_add_and_fetch_2:
656 case Builtin::BI__sync_add_and_fetch_4:
657 case Builtin::BI__sync_add_and_fetch_8:
658 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000659 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000660 case Builtin::BI__sync_sub_and_fetch_1:
661 case Builtin::BI__sync_sub_and_fetch_2:
662 case Builtin::BI__sync_sub_and_fetch_4:
663 case Builtin::BI__sync_sub_and_fetch_8:
664 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000665 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000666 case Builtin::BI__sync_and_and_fetch_1:
667 case Builtin::BI__sync_and_and_fetch_2:
668 case Builtin::BI__sync_and_and_fetch_4:
669 case Builtin::BI__sync_and_and_fetch_8:
670 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000671 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000672 case Builtin::BI__sync_or_and_fetch_1:
673 case Builtin::BI__sync_or_and_fetch_2:
674 case Builtin::BI__sync_or_and_fetch_4:
675 case Builtin::BI__sync_or_and_fetch_8:
676 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000677 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000678 case Builtin::BI__sync_xor_and_fetch_1:
679 case Builtin::BI__sync_xor_and_fetch_2:
680 case Builtin::BI__sync_xor_and_fetch_4:
681 case Builtin::BI__sync_xor_and_fetch_8:
682 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000683 case Builtin::BI__sync_nand_and_fetch:
684 case Builtin::BI__sync_nand_and_fetch_1:
685 case Builtin::BI__sync_nand_and_fetch_2:
686 case Builtin::BI__sync_nand_and_fetch_4:
687 case Builtin::BI__sync_nand_and_fetch_8:
688 case Builtin::BI__sync_nand_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000689 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000690 case Builtin::BI__sync_val_compare_and_swap_1:
691 case Builtin::BI__sync_val_compare_and_swap_2:
692 case Builtin::BI__sync_val_compare_and_swap_4:
693 case Builtin::BI__sync_val_compare_and_swap_8:
694 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000695 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000696 case Builtin::BI__sync_bool_compare_and_swap_1:
697 case Builtin::BI__sync_bool_compare_and_swap_2:
698 case Builtin::BI__sync_bool_compare_and_swap_4:
699 case Builtin::BI__sync_bool_compare_and_swap_8:
700 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000701 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000702 case Builtin::BI__sync_lock_test_and_set_1:
703 case Builtin::BI__sync_lock_test_and_set_2:
704 case Builtin::BI__sync_lock_test_and_set_4:
705 case Builtin::BI__sync_lock_test_and_set_8:
706 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000707 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000708 case Builtin::BI__sync_lock_release_1:
709 case Builtin::BI__sync_lock_release_2:
710 case Builtin::BI__sync_lock_release_4:
711 case Builtin::BI__sync_lock_release_8:
712 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000713 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000714 case Builtin::BI__sync_swap_1:
715 case Builtin::BI__sync_swap_2:
716 case Builtin::BI__sync_swap_4:
717 case Builtin::BI__sync_swap_8:
718 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000719 return SemaBuiltinAtomicOverloaded(TheCallResult);
Michael Zolotukhin84df1232015-09-08 23:52:33 +0000720 case Builtin::BI__builtin_nontemporal_load:
721 case Builtin::BI__builtin_nontemporal_store:
722 return SemaBuiltinNontemporalOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +0000723#define BUILTIN(ID, TYPE, ATTRS)
724#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
725 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000726 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +0000727#include "clang/Basic/Builtins.def"
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000728 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000729 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000730 return ExprError();
731 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +0000732 case Builtin::BI__builtin_addressof:
733 if (SemaBuiltinAddressof(*this, TheCall))
734 return ExprError();
735 break;
John McCall03107a42015-10-29 20:48:01 +0000736 case Builtin::BI__builtin_add_overflow:
737 case Builtin::BI__builtin_sub_overflow:
738 case Builtin::BI__builtin_mul_overflow:
Craig Toppera86e70d2015-11-07 06:16:14 +0000739 if (SemaBuiltinOverflow(*this, TheCall))
740 return ExprError();
741 break;
Richard Smith760520b2014-06-03 23:27:44 +0000742 case Builtin::BI__builtin_operator_new:
743 case Builtin::BI__builtin_operator_delete:
744 if (!getLangOpts().CPlusPlus) {
745 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
746 << (BuiltinID == Builtin::BI__builtin_operator_new
747 ? "__builtin_operator_new"
748 : "__builtin_operator_delete")
749 << "C++";
750 return ExprError();
751 }
752 // CodeGen assumes it can find the global new and delete to call,
753 // so ensure that they are declared.
754 DeclareGlobalNewDelete();
755 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000756
757 // check secure string manipulation functions where overflows
758 // are detectable at compile time
759 case Builtin::BI__builtin___memcpy_chk:
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000760 case Builtin::BI__builtin___memmove_chk:
761 case Builtin::BI__builtin___memset_chk:
762 case Builtin::BI__builtin___strlcat_chk:
763 case Builtin::BI__builtin___strlcpy_chk:
764 case Builtin::BI__builtin___strncat_chk:
765 case Builtin::BI__builtin___strncpy_chk:
766 case Builtin::BI__builtin___stpncpy_chk:
767 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
768 break;
Steven Wu566c14e2014-09-24 04:37:33 +0000769 case Builtin::BI__builtin___memccpy_chk:
770 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
771 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000772 case Builtin::BI__builtin___snprintf_chk:
773 case Builtin::BI__builtin___vsnprintf_chk:
774 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
775 break;
Peter Collingbournef7706832014-12-12 23:41:25 +0000776 case Builtin::BI__builtin_call_with_static_chain:
777 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
778 return ExprError();
779 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000780 case Builtin::BI__exception_code:
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000781 case Builtin::BI_exception_code:
Reid Kleckner1d59f992015-01-22 01:36:17 +0000782 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
783 diag::err_seh___except_block))
784 return ExprError();
785 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000786 case Builtin::BI__exception_info:
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000787 case Builtin::BI_exception_info:
Reid Kleckner1d59f992015-01-22 01:36:17 +0000788 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
789 diag::err_seh___except_filter))
790 return ExprError();
791 break;
David Majnemerba3e5ec2015-03-13 18:26:17 +0000792 case Builtin::BI__GetExceptionInfo:
793 if (checkArgCount(*this, TheCall, 1))
794 return ExprError();
795
796 if (CheckCXXThrowOperand(
797 TheCall->getLocStart(),
798 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
799 TheCall))
800 return ExprError();
801
802 TheCall->setType(Context.VoidPtrTy);
803 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000804 case Builtin::BIread_pipe:
805 case Builtin::BIwrite_pipe:
806 // Since those two functions are declared with var args, we need a semantic
807 // check for the argument.
808 if (SemaBuiltinRWPipe(*this, TheCall))
809 return ExprError();
810 break;
811 case Builtin::BIreserve_read_pipe:
812 case Builtin::BIreserve_write_pipe:
813 case Builtin::BIwork_group_reserve_read_pipe:
814 case Builtin::BIwork_group_reserve_write_pipe:
815 case Builtin::BIsub_group_reserve_read_pipe:
816 case Builtin::BIsub_group_reserve_write_pipe:
817 if (SemaBuiltinReserveRWPipe(*this, TheCall))
818 return ExprError();
819 // Since return type of reserve_read/write_pipe built-in function is
820 // reserve_id_t, which is not defined in the builtin def file , we used int
821 // as return type and need to override the return type of these functions.
822 TheCall->setType(Context.OCLReserveIDTy);
823 break;
824 case Builtin::BIcommit_read_pipe:
825 case Builtin::BIcommit_write_pipe:
826 case Builtin::BIwork_group_commit_read_pipe:
827 case Builtin::BIwork_group_commit_write_pipe:
828 case Builtin::BIsub_group_commit_read_pipe:
829 case Builtin::BIsub_group_commit_write_pipe:
830 if (SemaBuiltinCommitRWPipe(*this, TheCall))
831 return ExprError();
832 break;
833 case Builtin::BIget_pipe_num_packets:
834 case Builtin::BIget_pipe_max_packets:
835 if (SemaBuiltinPipePackets(*this, TheCall))
836 return ExprError();
837 break;
Yaxun Liuf7449a12016-05-20 19:54:38 +0000838 case Builtin::BIto_global:
839 case Builtin::BIto_local:
840 case Builtin::BIto_private:
841 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
842 return ExprError();
843 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000844 }
Richard Smith760520b2014-06-03 23:27:44 +0000845
Nate Begeman4904e322010-06-08 02:47:44 +0000846 // Since the target specific builtins for each arch overlap, only check those
847 // of the arch we are compiling for.
Artem Belevich9674a642015-09-22 17:23:05 +0000848 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000849 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +0000850 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000851 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000852 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000853 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000854 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
855 return ExprError();
856 break;
Tim Northover25e8a672014-05-24 12:51:25 +0000857 case llvm::Triple::aarch64:
858 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +0000859 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +0000860 return ExprError();
861 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000862 case llvm::Triple::mips:
863 case llvm::Triple::mipsel:
864 case llvm::Triple::mips64:
865 case llvm::Triple::mips64el:
866 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
867 return ExprError();
868 break;
Ulrich Weigand3a610eb2015-04-01 12:54:25 +0000869 case llvm::Triple::systemz:
870 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
871 return ExprError();
872 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000873 case llvm::Triple::x86:
874 case llvm::Triple::x86_64:
875 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
876 return ExprError();
877 break;
Kit Bartone50adcb2015-03-30 19:40:59 +0000878 case llvm::Triple::ppc:
879 case llvm::Triple::ppc64:
880 case llvm::Triple::ppc64le:
881 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
882 return ExprError();
883 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000884 default:
885 break;
886 }
887 }
888
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000889 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +0000890}
891
Nate Begeman91e1fea2010-06-14 05:21:25 +0000892// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +0000893static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +0000894 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +0000895 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +0000896 switch (Type.getEltType()) {
897 case NeonTypeFlags::Int8:
898 case NeonTypeFlags::Poly8:
899 return shift ? 7 : (8 << IsQuad) - 1;
900 case NeonTypeFlags::Int16:
901 case NeonTypeFlags::Poly16:
902 return shift ? 15 : (4 << IsQuad) - 1;
903 case NeonTypeFlags::Int32:
904 return shift ? 31 : (2 << IsQuad) - 1;
905 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +0000906 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +0000907 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000908 case NeonTypeFlags::Poly128:
909 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +0000910 case NeonTypeFlags::Float16:
911 assert(!shift && "cannot shift float types!");
912 return (4 << IsQuad) - 1;
913 case NeonTypeFlags::Float32:
914 assert(!shift && "cannot shift float types!");
915 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000916 case NeonTypeFlags::Float64:
917 assert(!shift && "cannot shift float types!");
918 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000919 }
David Blaikie8a40f702012-01-17 06:56:22 +0000920 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +0000921}
922
Bob Wilsone4d77232011-11-08 05:04:11 +0000923/// getNeonEltType - Return the QualType corresponding to the elements of
924/// the vector type specified by the NeonTypeFlags. This is used to check
925/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +0000926static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +0000927 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +0000928 switch (Flags.getEltType()) {
929 case NeonTypeFlags::Int8:
930 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
931 case NeonTypeFlags::Int16:
932 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
933 case NeonTypeFlags::Int32:
934 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
935 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +0000936 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +0000937 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
938 else
939 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
940 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000941 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +0000942 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000943 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +0000944 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +0000945 case NeonTypeFlags::Poly64:
Kevin Qin78b86532015-05-14 08:18:05 +0000946 if (IsInt64Long)
947 return Context.UnsignedLongTy;
948 else
949 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000950 case NeonTypeFlags::Poly128:
951 break;
Bob Wilsone4d77232011-11-08 05:04:11 +0000952 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +0000953 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000954 case NeonTypeFlags::Float32:
955 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +0000956 case NeonTypeFlags::Float64:
957 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000958 }
David Blaikie8a40f702012-01-17 06:56:22 +0000959 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +0000960}
961
Tim Northover12670412014-02-19 10:37:05 +0000962bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +0000963 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +0000964 uint64_t mask = 0;
965 unsigned TV = 0;
966 int PtrArgNum = -1;
967 bool HasConstPtr = false;
968 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +0000969#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000970#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000971#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000972 }
973
974 // For NEON intrinsics which are overloaded on vector element type, validate
975 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +0000976 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000977 if (mask) {
978 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
979 return true;
980
981 TV = Result.getLimitedValue(64);
982 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
983 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +0000984 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +0000985 }
986
987 if (PtrArgNum >= 0) {
988 // Check that pointer arguments have the specified type.
989 Expr *Arg = TheCall->getArg(PtrArgNum);
990 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
991 Arg = ICE->getSubExpr();
992 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
993 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +0000994
Tim Northovera2ee4332014-03-29 15:09:45 +0000995 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Tim Northover40956e62014-07-23 12:32:58 +0000996 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
Tim Northovera2ee4332014-03-29 15:09:45 +0000997 bool IsInt64Long =
998 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
999 QualType EltTy =
1000 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +00001001 if (HasConstPtr)
1002 EltTy = EltTy.withConst();
1003 QualType LHSTy = Context.getPointerType(EltTy);
1004 AssignConvertType ConvTy;
1005 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1006 if (RHS.isInvalid())
1007 return true;
1008 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1009 RHS.get(), AA_Assigning))
1010 return true;
1011 }
1012
1013 // For NEON intrinsics which take an immediate value as part of the
1014 // instruction, range check them here.
1015 unsigned i = 0, l = 0, u = 0;
1016 switch (BuiltinID) {
1017 default:
1018 return false;
Tim Northover12670412014-02-19 10:37:05 +00001019#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001020#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +00001021#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001022 }
Tim Northover2fe823a2013-08-01 09:23:19 +00001023
Richard Sandiford28940af2014-04-16 08:47:51 +00001024 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +00001025}
1026
Tim Northovera2ee4332014-03-29 15:09:45 +00001027bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1028 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +00001029 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001030 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +00001031 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001032 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +00001033 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001034 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1035 BuiltinID == AArch64::BI__builtin_arm_strex ||
1036 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +00001037 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +00001038 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001039 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1040 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1041 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +00001042
1043 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1044
1045 // Ensure that we have the proper number of arguments.
1046 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1047 return true;
1048
1049 // Inspect the pointer argument of the atomic builtin. This should always be
1050 // a pointer type, whose element is an integral scalar or pointer type.
1051 // Because it is a pointer type, we don't have to worry about any implicit
1052 // casts here.
1053 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1054 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1055 if (PointerArgRes.isInvalid())
1056 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001057 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001058
1059 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1060 if (!pointerType) {
1061 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1062 << PointerArg->getType() << PointerArg->getSourceRange();
1063 return true;
1064 }
1065
1066 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1067 // task is to insert the appropriate casts into the AST. First work out just
1068 // what the appropriate type is.
1069 QualType ValType = pointerType->getPointeeType();
1070 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1071 if (IsLdrex)
1072 AddrType.addConst();
1073
1074 // Issue a warning if the cast is dodgy.
1075 CastKind CastNeeded = CK_NoOp;
1076 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1077 CastNeeded = CK_BitCast;
1078 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1079 << PointerArg->getType()
1080 << Context.getPointerType(AddrType)
1081 << AA_Passing << PointerArg->getSourceRange();
1082 }
1083
1084 // Finally, do the cast and replace the argument with the corrected version.
1085 AddrType = Context.getPointerType(AddrType);
1086 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1087 if (PointerArgRes.isInvalid())
1088 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001089 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001090
1091 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1092
1093 // In general, we allow ints, floats and pointers to be loaded and stored.
1094 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1095 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1096 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1097 << PointerArg->getType() << PointerArg->getSourceRange();
1098 return true;
1099 }
1100
1101 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +00001102 if (Context.getTypeSize(ValType) > MaxWidth) {
1103 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +00001104 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1105 << PointerArg->getType() << PointerArg->getSourceRange();
1106 return true;
1107 }
1108
1109 switch (ValType.getObjCLifetime()) {
1110 case Qualifiers::OCL_None:
1111 case Qualifiers::OCL_ExplicitNone:
1112 // okay
1113 break;
1114
1115 case Qualifiers::OCL_Weak:
1116 case Qualifiers::OCL_Strong:
1117 case Qualifiers::OCL_Autoreleasing:
1118 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1119 << ValType << PointerArg->getSourceRange();
1120 return true;
1121 }
1122
Tim Northover6aacd492013-07-16 09:47:53 +00001123 if (IsLdrex) {
1124 TheCall->setType(ValType);
1125 return false;
1126 }
1127
1128 // Initialize the argument to be stored.
1129 ExprResult ValArg = TheCall->getArg(0);
1130 InitializedEntity Entity = InitializedEntity::InitializeParameter(
1131 Context, ValType, /*consume*/ false);
1132 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1133 if (ValArg.isInvalid())
1134 return true;
Tim Northover6aacd492013-07-16 09:47:53 +00001135 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +00001136
1137 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1138 // but the custom checker bypasses all default analysis.
1139 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +00001140 return false;
1141}
1142
Nate Begeman4904e322010-06-08 02:47:44 +00001143bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +00001144 llvm::APSInt Result;
1145
Tim Northover6aacd492013-07-16 09:47:53 +00001146 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001147 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1148 BuiltinID == ARM::BI__builtin_arm_strex ||
1149 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001150 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +00001151 }
1152
Yi Kong26d104a2014-08-13 19:18:14 +00001153 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1154 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1155 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1156 }
1157
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001158 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1159 BuiltinID == ARM::BI__builtin_arm_wsr64)
1160 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1161
1162 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1163 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1164 BuiltinID == ARM::BI__builtin_arm_wsr ||
1165 BuiltinID == ARM::BI__builtin_arm_wsrp)
1166 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1167
Tim Northover12670412014-02-19 10:37:05 +00001168 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1169 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +00001170
Yi Kong4efadfb2014-07-03 16:01:25 +00001171 // For intrinsics which take an immediate value as part of the instruction,
1172 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +00001173 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +00001174 switch (BuiltinID) {
1175 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +00001176 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
1177 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +00001178 case ARM::BI__builtin_arm_vcvtr_f:
1179 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +00001180 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +00001181 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +00001182 case ARM::BI__builtin_arm_isb:
1183 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001184 }
Nate Begemand773fe62010-06-13 04:47:52 +00001185
Nate Begemanf568b072010-08-03 21:32:34 +00001186 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +00001187 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001188}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001189
Tim Northover573cbee2014-05-24 12:52:07 +00001190bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +00001191 CallExpr *TheCall) {
1192 llvm::APSInt Result;
1193
Tim Northover573cbee2014-05-24 12:52:07 +00001194 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001195 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1196 BuiltinID == AArch64::BI__builtin_arm_strex ||
1197 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001198 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1199 }
1200
Yi Konga5548432014-08-13 19:18:20 +00001201 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1202 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1203 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1204 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1205 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1206 }
1207
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001208 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1209 BuiltinID == AArch64::BI__builtin_arm_wsr64)
Tim Northover54e50002016-04-13 17:08:55 +00001210 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001211
1212 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1213 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1214 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1215 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1216 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1217
Tim Northovera2ee4332014-03-29 15:09:45 +00001218 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1219 return true;
1220
Yi Kong19a29ac2014-07-17 10:52:06 +00001221 // For intrinsics which take an immediate value as part of the instruction,
1222 // range check them here.
1223 unsigned i = 0, l = 0, u = 0;
1224 switch (BuiltinID) {
1225 default: return false;
1226 case AArch64::BI__builtin_arm_dmb:
1227 case AArch64::BI__builtin_arm_dsb:
1228 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1229 }
1230
Yi Kong19a29ac2014-07-17 10:52:06 +00001231 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +00001232}
1233
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001234bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1235 unsigned i = 0, l = 0, u = 0;
1236 switch (BuiltinID) {
1237 default: return false;
1238 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1239 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +00001240 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1241 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1242 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1243 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1244 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001245 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001246
Richard Sandiford28940af2014-04-16 08:47:51 +00001247 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001248}
1249
Kit Bartone50adcb2015-03-30 19:40:59 +00001250bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1251 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00001252 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1253 BuiltinID == PPC::BI__builtin_divdeu ||
1254 BuiltinID == PPC::BI__builtin_bpermd;
1255 bool IsTarget64Bit = Context.getTargetInfo()
1256 .getTypeWidth(Context
1257 .getTargetInfo()
1258 .getIntPtrType()) == 64;
1259 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1260 BuiltinID == PPC::BI__builtin_divweu ||
1261 BuiltinID == PPC::BI__builtin_divde ||
1262 BuiltinID == PPC::BI__builtin_divdeu;
1263
1264 if (Is64BitBltin && !IsTarget64Bit)
1265 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1266 << TheCall->getSourceRange();
1267
1268 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1269 (BuiltinID == PPC::BI__builtin_bpermd &&
1270 !Context.getTargetInfo().hasFeature("bpermd")))
1271 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1272 << TheCall->getSourceRange();
1273
Kit Bartone50adcb2015-03-30 19:40:59 +00001274 switch (BuiltinID) {
1275 default: return false;
1276 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1277 case PPC::BI__builtin_altivec_crypto_vshasigmad:
1278 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1279 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1280 case PPC::BI__builtin_tbegin:
1281 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1282 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1283 case PPC::BI__builtin_tabortwc:
1284 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1285 case PPC::BI__builtin_tabortwci:
1286 case PPC::BI__builtin_tabortdci:
1287 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1288 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1289 }
1290 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1291}
1292
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001293bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1294 CallExpr *TheCall) {
1295 if (BuiltinID == SystemZ::BI__builtin_tabort) {
1296 Expr *Arg = TheCall->getArg(0);
1297 llvm::APSInt AbortCode(32);
1298 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1299 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1300 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1301 << Arg->getSourceRange();
1302 }
1303
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001304 // For intrinsics which take an immediate value as part of the instruction,
1305 // range check them here.
1306 unsigned i = 0, l = 0, u = 0;
1307 switch (BuiltinID) {
1308 default: return false;
1309 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1310 case SystemZ::BI__builtin_s390_verimb:
1311 case SystemZ::BI__builtin_s390_verimh:
1312 case SystemZ::BI__builtin_s390_verimf:
1313 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1314 case SystemZ::BI__builtin_s390_vfaeb:
1315 case SystemZ::BI__builtin_s390_vfaeh:
1316 case SystemZ::BI__builtin_s390_vfaef:
1317 case SystemZ::BI__builtin_s390_vfaebs:
1318 case SystemZ::BI__builtin_s390_vfaehs:
1319 case SystemZ::BI__builtin_s390_vfaefs:
1320 case SystemZ::BI__builtin_s390_vfaezb:
1321 case SystemZ::BI__builtin_s390_vfaezh:
1322 case SystemZ::BI__builtin_s390_vfaezf:
1323 case SystemZ::BI__builtin_s390_vfaezbs:
1324 case SystemZ::BI__builtin_s390_vfaezhs:
1325 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1326 case SystemZ::BI__builtin_s390_vfidb:
1327 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1328 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1329 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1330 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1331 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1332 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1333 case SystemZ::BI__builtin_s390_vstrcb:
1334 case SystemZ::BI__builtin_s390_vstrch:
1335 case SystemZ::BI__builtin_s390_vstrcf:
1336 case SystemZ::BI__builtin_s390_vstrczb:
1337 case SystemZ::BI__builtin_s390_vstrczh:
1338 case SystemZ::BI__builtin_s390_vstrczf:
1339 case SystemZ::BI__builtin_s390_vstrcbs:
1340 case SystemZ::BI__builtin_s390_vstrchs:
1341 case SystemZ::BI__builtin_s390_vstrcfs:
1342 case SystemZ::BI__builtin_s390_vstrczbs:
1343 case SystemZ::BI__builtin_s390_vstrczhs:
1344 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1345 }
1346 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001347}
1348
Craig Topper5ba2c502015-11-07 08:08:31 +00001349/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1350/// This checks that the target supports __builtin_cpu_supports and
1351/// that the string argument is constant and valid.
1352static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1353 Expr *Arg = TheCall->getArg(0);
1354
1355 // Check if the argument is a string literal.
1356 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1357 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1358 << Arg->getSourceRange();
1359
1360 // Check the contents of the string.
1361 StringRef Feature =
1362 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1363 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1364 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1365 << Arg->getSourceRange();
1366 return false;
1367}
1368
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001369bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Craig Topper39c87102016-05-18 03:18:12 +00001370 int i = 0, l = 0, u = 0;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001371 switch (BuiltinID) {
Richard Trieucc3949d2016-02-18 22:34:54 +00001372 default:
1373 return false;
Eric Christopherd9832702015-06-29 21:00:05 +00001374 case X86::BI__builtin_cpu_supports:
Craig Topper5ba2c502015-11-07 08:08:31 +00001375 return SemaBuiltinCpuSupports(*this, TheCall);
Charles Davisc7d5c942015-09-17 20:55:33 +00001376 case X86::BI__builtin_ms_va_start:
1377 return SemaBuiltinMSVAStart(TheCall);
Craig Topper39c87102016-05-18 03:18:12 +00001378 case X86::BI__builtin_ia32_extractf64x4_mask:
1379 case X86::BI__builtin_ia32_extracti64x4_mask:
1380 case X86::BI__builtin_ia32_extractf32x8_mask:
1381 case X86::BI__builtin_ia32_extracti32x8_mask:
1382 case X86::BI__builtin_ia32_extractf64x2_256_mask:
1383 case X86::BI__builtin_ia32_extracti64x2_256_mask:
1384 case X86::BI__builtin_ia32_extractf32x4_256_mask:
1385 case X86::BI__builtin_ia32_extracti32x4_256_mask:
1386 i = 1; l = 0; u = 1;
1387 break;
Richard Trieucc3949d2016-02-18 22:34:54 +00001388 case X86::BI_mm_prefetch:
Craig Topper39c87102016-05-18 03:18:12 +00001389 case X86::BI__builtin_ia32_extractf32x4_mask:
1390 case X86::BI__builtin_ia32_extracti32x4_mask:
Craig Topper39c87102016-05-18 03:18:12 +00001391 case X86::BI__builtin_ia32_extractf64x2_512_mask:
1392 case X86::BI__builtin_ia32_extracti64x2_512_mask:
1393 i = 1; l = 0; u = 3;
1394 break;
1395 case X86::BI__builtin_ia32_insertf32x8_mask:
1396 case X86::BI__builtin_ia32_inserti32x8_mask:
1397 case X86::BI__builtin_ia32_insertf64x4_mask:
1398 case X86::BI__builtin_ia32_inserti64x4_mask:
1399 case X86::BI__builtin_ia32_insertf64x2_256_mask:
1400 case X86::BI__builtin_ia32_inserti64x2_256_mask:
1401 case X86::BI__builtin_ia32_insertf32x4_256_mask:
1402 case X86::BI__builtin_ia32_inserti32x4_256_mask:
1403 i = 2; l = 0; u = 1;
Richard Trieucc3949d2016-02-18 22:34:54 +00001404 break;
1405 case X86::BI__builtin_ia32_sha1rnds4:
Craig Topper39c87102016-05-18 03:18:12 +00001406 case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
1407 case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
1408 case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
1409 case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
1410 case X86::BI__builtin_ia32_shufpd128_mask:
1411 case X86::BI__builtin_ia32_insertf64x2_512_mask:
1412 case X86::BI__builtin_ia32_inserti64x2_512_mask:
1413 case X86::BI__builtin_ia32_insertf32x4_mask:
1414 case X86::BI__builtin_ia32_inserti32x4_mask:
1415 i = 2; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00001416 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00001417 case X86::BI__builtin_ia32_vpermil2pd:
1418 case X86::BI__builtin_ia32_vpermil2pd256:
1419 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00001420 case X86::BI__builtin_ia32_vpermil2ps256:
Craig Topper39c87102016-05-18 03:18:12 +00001421 i = 3; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00001422 break;
Craig Topper95b0d732015-01-25 23:30:05 +00001423 case X86::BI__builtin_ia32_cmpb128_mask:
1424 case X86::BI__builtin_ia32_cmpw128_mask:
1425 case X86::BI__builtin_ia32_cmpd128_mask:
1426 case X86::BI__builtin_ia32_cmpq128_mask:
1427 case X86::BI__builtin_ia32_cmpb256_mask:
1428 case X86::BI__builtin_ia32_cmpw256_mask:
1429 case X86::BI__builtin_ia32_cmpd256_mask:
1430 case X86::BI__builtin_ia32_cmpq256_mask:
1431 case X86::BI__builtin_ia32_cmpb512_mask:
1432 case X86::BI__builtin_ia32_cmpw512_mask:
1433 case X86::BI__builtin_ia32_cmpd512_mask:
1434 case X86::BI__builtin_ia32_cmpq512_mask:
1435 case X86::BI__builtin_ia32_ucmpb128_mask:
1436 case X86::BI__builtin_ia32_ucmpw128_mask:
1437 case X86::BI__builtin_ia32_ucmpd128_mask:
1438 case X86::BI__builtin_ia32_ucmpq128_mask:
1439 case X86::BI__builtin_ia32_ucmpb256_mask:
1440 case X86::BI__builtin_ia32_ucmpw256_mask:
1441 case X86::BI__builtin_ia32_ucmpd256_mask:
1442 case X86::BI__builtin_ia32_ucmpq256_mask:
1443 case X86::BI__builtin_ia32_ucmpb512_mask:
1444 case X86::BI__builtin_ia32_ucmpw512_mask:
1445 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00001446 case X86::BI__builtin_ia32_ucmpq512_mask:
Craig Topper8dd7d0d2015-02-13 06:04:48 +00001447 case X86::BI__builtin_ia32_vpcomub:
1448 case X86::BI__builtin_ia32_vpcomuw:
1449 case X86::BI__builtin_ia32_vpcomud:
1450 case X86::BI__builtin_ia32_vpcomuq:
1451 case X86::BI__builtin_ia32_vpcomb:
1452 case X86::BI__builtin_ia32_vpcomw:
1453 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00001454 case X86::BI__builtin_ia32_vpcomq:
Craig Topper39c87102016-05-18 03:18:12 +00001455 i = 2; l = 0; u = 7;
1456 break;
1457 case X86::BI__builtin_ia32_roundps:
1458 case X86::BI__builtin_ia32_roundpd:
1459 case X86::BI__builtin_ia32_roundps256:
1460 case X86::BI__builtin_ia32_roundpd256:
Craig Topper39c87102016-05-18 03:18:12 +00001461 i = 1; l = 0; u = 15;
1462 break;
1463 case X86::BI__builtin_ia32_roundss:
1464 case X86::BI__builtin_ia32_roundsd:
1465 case X86::BI__builtin_ia32_rangepd128_mask:
1466 case X86::BI__builtin_ia32_rangepd256_mask:
1467 case X86::BI__builtin_ia32_rangepd512_mask:
1468 case X86::BI__builtin_ia32_rangeps128_mask:
1469 case X86::BI__builtin_ia32_rangeps256_mask:
1470 case X86::BI__builtin_ia32_rangeps512_mask:
1471 case X86::BI__builtin_ia32_getmantsd_round_mask:
1472 case X86::BI__builtin_ia32_getmantss_round_mask:
1473 case X86::BI__builtin_ia32_shufpd256_mask:
1474 i = 2; l = 0; u = 15;
1475 break;
1476 case X86::BI__builtin_ia32_cmpps:
1477 case X86::BI__builtin_ia32_cmpss:
1478 case X86::BI__builtin_ia32_cmppd:
1479 case X86::BI__builtin_ia32_cmpsd:
1480 case X86::BI__builtin_ia32_cmpps256:
1481 case X86::BI__builtin_ia32_cmppd256:
1482 case X86::BI__builtin_ia32_cmpps128_mask:
1483 case X86::BI__builtin_ia32_cmppd128_mask:
1484 case X86::BI__builtin_ia32_cmpps256_mask:
1485 case X86::BI__builtin_ia32_cmppd256_mask:
1486 case X86::BI__builtin_ia32_cmpps512_mask:
1487 case X86::BI__builtin_ia32_cmppd512_mask:
1488 case X86::BI__builtin_ia32_cmpsd_mask:
1489 case X86::BI__builtin_ia32_cmpss_mask:
1490 i = 2; l = 0; u = 31;
1491 break;
1492 case X86::BI__builtin_ia32_xabort:
1493 i = 0; l = -128; u = 255;
1494 break;
1495 case X86::BI__builtin_ia32_pshufw:
1496 case X86::BI__builtin_ia32_aeskeygenassist128:
1497 i = 1; l = -128; u = 255;
1498 break;
1499 case X86::BI__builtin_ia32_vcvtps2ph:
1500 case X86::BI__builtin_ia32_vcvtps2ph256:
1501 case X86::BI__builtin_ia32_vcvtps2ph512:
1502 case X86::BI__builtin_ia32_rndscaleps_128_mask:
1503 case X86::BI__builtin_ia32_rndscalepd_128_mask:
1504 case X86::BI__builtin_ia32_rndscaleps_256_mask:
1505 case X86::BI__builtin_ia32_rndscalepd_256_mask:
1506 case X86::BI__builtin_ia32_rndscaleps_mask:
1507 case X86::BI__builtin_ia32_rndscalepd_mask:
1508 case X86::BI__builtin_ia32_reducepd128_mask:
1509 case X86::BI__builtin_ia32_reducepd256_mask:
1510 case X86::BI__builtin_ia32_reducepd512_mask:
1511 case X86::BI__builtin_ia32_reduceps128_mask:
1512 case X86::BI__builtin_ia32_reduceps256_mask:
1513 case X86::BI__builtin_ia32_reduceps512_mask:
1514 case X86::BI__builtin_ia32_prold512_mask:
1515 case X86::BI__builtin_ia32_prolq512_mask:
1516 case X86::BI__builtin_ia32_prold128_mask:
1517 case X86::BI__builtin_ia32_prold256_mask:
1518 case X86::BI__builtin_ia32_prolq128_mask:
1519 case X86::BI__builtin_ia32_prolq256_mask:
1520 case X86::BI__builtin_ia32_prord128_mask:
1521 case X86::BI__builtin_ia32_prord256_mask:
1522 case X86::BI__builtin_ia32_prorq128_mask:
1523 case X86::BI__builtin_ia32_prorq256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00001524 case X86::BI__builtin_ia32_psllwi512_mask:
1525 case X86::BI__builtin_ia32_psllwi128_mask:
1526 case X86::BI__builtin_ia32_psllwi256_mask:
1527 case X86::BI__builtin_ia32_psrldi128_mask:
1528 case X86::BI__builtin_ia32_psrldi256_mask:
1529 case X86::BI__builtin_ia32_psrldi512_mask:
1530 case X86::BI__builtin_ia32_psrlqi128_mask:
1531 case X86::BI__builtin_ia32_psrlqi256_mask:
1532 case X86::BI__builtin_ia32_psrlqi512_mask:
1533 case X86::BI__builtin_ia32_psrawi512_mask:
1534 case X86::BI__builtin_ia32_psrawi128_mask:
1535 case X86::BI__builtin_ia32_psrawi256_mask:
1536 case X86::BI__builtin_ia32_psrlwi512_mask:
1537 case X86::BI__builtin_ia32_psrlwi128_mask:
1538 case X86::BI__builtin_ia32_psrlwi256_mask:
1539 case X86::BI__builtin_ia32_vpermilpd512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00001540 case X86::BI__builtin_ia32_psradi128_mask:
1541 case X86::BI__builtin_ia32_psradi256_mask:
1542 case X86::BI__builtin_ia32_psradi512_mask:
1543 case X86::BI__builtin_ia32_psraqi128_mask:
1544 case X86::BI__builtin_ia32_psraqi256_mask:
1545 case X86::BI__builtin_ia32_psraqi512_mask:
1546 case X86::BI__builtin_ia32_pslldi128_mask:
1547 case X86::BI__builtin_ia32_pslldi256_mask:
1548 case X86::BI__builtin_ia32_pslldi512_mask:
1549 case X86::BI__builtin_ia32_psllqi128_mask:
1550 case X86::BI__builtin_ia32_psllqi256_mask:
1551 case X86::BI__builtin_ia32_psllqi512_mask:
1552 case X86::BI__builtin_ia32_permdf512_mask:
1553 case X86::BI__builtin_ia32_permdi512_mask:
1554 case X86::BI__builtin_ia32_permdf256_mask:
1555 case X86::BI__builtin_ia32_permdi256_mask:
1556 case X86::BI__builtin_ia32_fpclasspd128_mask:
1557 case X86::BI__builtin_ia32_fpclasspd256_mask:
1558 case X86::BI__builtin_ia32_fpclassps128_mask:
1559 case X86::BI__builtin_ia32_fpclassps256_mask:
1560 case X86::BI__builtin_ia32_fpclassps512_mask:
1561 case X86::BI__builtin_ia32_fpclasspd512_mask:
1562 case X86::BI__builtin_ia32_fpclasssd_mask:
1563 case X86::BI__builtin_ia32_fpclassss_mask:
Michael Zuckerman5486eab2016-06-30 12:12:20 +00001564 case X86::BI__builtin_ia32_vpermilps512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00001565 i = 1; l = 0; u = 255;
1566 break;
1567 case X86::BI__builtin_ia32_palignr:
1568 case X86::BI__builtin_ia32_insertps128:
1569 case X86::BI__builtin_ia32_dpps:
1570 case X86::BI__builtin_ia32_dppd:
1571 case X86::BI__builtin_ia32_dpps256:
1572 case X86::BI__builtin_ia32_mpsadbw128:
1573 case X86::BI__builtin_ia32_mpsadbw256:
1574 case X86::BI__builtin_ia32_pcmpistrm128:
1575 case X86::BI__builtin_ia32_pcmpistri128:
1576 case X86::BI__builtin_ia32_pcmpistria128:
1577 case X86::BI__builtin_ia32_pcmpistric128:
1578 case X86::BI__builtin_ia32_pcmpistrio128:
1579 case X86::BI__builtin_ia32_pcmpistris128:
1580 case X86::BI__builtin_ia32_pcmpistriz128:
1581 case X86::BI__builtin_ia32_pclmulqdq128:
1582 case X86::BI__builtin_ia32_vperm2f128_pd256:
1583 case X86::BI__builtin_ia32_vperm2f128_ps256:
1584 case X86::BI__builtin_ia32_vperm2f128_si256:
1585 case X86::BI__builtin_ia32_permti256:
1586 i = 2; l = -128; u = 255;
1587 break;
1588 case X86::BI__builtin_ia32_palignr128:
1589 case X86::BI__builtin_ia32_palignr256:
1590 case X86::BI__builtin_ia32_palignr128_mask:
1591 case X86::BI__builtin_ia32_palignr256_mask:
1592 case X86::BI__builtin_ia32_palignr512_mask:
1593 case X86::BI__builtin_ia32_alignq512_mask:
1594 case X86::BI__builtin_ia32_alignd512_mask:
1595 case X86::BI__builtin_ia32_alignd128_mask:
1596 case X86::BI__builtin_ia32_alignd256_mask:
1597 case X86::BI__builtin_ia32_alignq128_mask:
1598 case X86::BI__builtin_ia32_alignq256_mask:
1599 case X86::BI__builtin_ia32_vcomisd:
1600 case X86::BI__builtin_ia32_vcomiss:
1601 case X86::BI__builtin_ia32_shuf_f32x4_mask:
1602 case X86::BI__builtin_ia32_shuf_f64x2_mask:
1603 case X86::BI__builtin_ia32_shuf_i32x4_mask:
1604 case X86::BI__builtin_ia32_shuf_i64x2_mask:
1605 case X86::BI__builtin_ia32_shufpd512_mask:
1606 case X86::BI__builtin_ia32_shufps128_mask:
1607 case X86::BI__builtin_ia32_shufps256_mask:
1608 case X86::BI__builtin_ia32_shufps512_mask:
1609 case X86::BI__builtin_ia32_dbpsadbw128_mask:
1610 case X86::BI__builtin_ia32_dbpsadbw256_mask:
1611 case X86::BI__builtin_ia32_dbpsadbw512_mask:
1612 i = 2; l = 0; u = 255;
1613 break;
1614 case X86::BI__builtin_ia32_fixupimmpd512_mask:
1615 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
1616 case X86::BI__builtin_ia32_fixupimmps512_mask:
1617 case X86::BI__builtin_ia32_fixupimmps512_maskz:
1618 case X86::BI__builtin_ia32_fixupimmsd_mask:
1619 case X86::BI__builtin_ia32_fixupimmsd_maskz:
1620 case X86::BI__builtin_ia32_fixupimmss_mask:
1621 case X86::BI__builtin_ia32_fixupimmss_maskz:
1622 case X86::BI__builtin_ia32_fixupimmpd128_mask:
1623 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
1624 case X86::BI__builtin_ia32_fixupimmpd256_mask:
1625 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
1626 case X86::BI__builtin_ia32_fixupimmps128_mask:
1627 case X86::BI__builtin_ia32_fixupimmps128_maskz:
1628 case X86::BI__builtin_ia32_fixupimmps256_mask:
1629 case X86::BI__builtin_ia32_fixupimmps256_maskz:
1630 case X86::BI__builtin_ia32_pternlogd512_mask:
1631 case X86::BI__builtin_ia32_pternlogd512_maskz:
1632 case X86::BI__builtin_ia32_pternlogq512_mask:
1633 case X86::BI__builtin_ia32_pternlogq512_maskz:
1634 case X86::BI__builtin_ia32_pternlogd128_mask:
1635 case X86::BI__builtin_ia32_pternlogd128_maskz:
1636 case X86::BI__builtin_ia32_pternlogd256_mask:
1637 case X86::BI__builtin_ia32_pternlogd256_maskz:
1638 case X86::BI__builtin_ia32_pternlogq128_mask:
1639 case X86::BI__builtin_ia32_pternlogq128_maskz:
1640 case X86::BI__builtin_ia32_pternlogq256_mask:
1641 case X86::BI__builtin_ia32_pternlogq256_maskz:
1642 i = 3; l = 0; u = 255;
1643 break;
1644 case X86::BI__builtin_ia32_pcmpestrm128:
1645 case X86::BI__builtin_ia32_pcmpestri128:
1646 case X86::BI__builtin_ia32_pcmpestria128:
1647 case X86::BI__builtin_ia32_pcmpestric128:
1648 case X86::BI__builtin_ia32_pcmpestrio128:
1649 case X86::BI__builtin_ia32_pcmpestris128:
1650 case X86::BI__builtin_ia32_pcmpestriz128:
1651 i = 4; l = -128; u = 255;
1652 break;
1653 case X86::BI__builtin_ia32_rndscalesd_round_mask:
1654 case X86::BI__builtin_ia32_rndscaless_round_mask:
1655 i = 4; l = 0; u = 255;
Richard Trieucc3949d2016-02-18 22:34:54 +00001656 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001657 }
Craig Topperdd84ec52014-12-27 07:00:08 +00001658 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001659}
1660
Richard Smith55ce3522012-06-25 20:30:08 +00001661/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
1662/// parameter with the FormatAttr's correct format_idx and firstDataArg.
1663/// Returns true when the format fits the function and the FormatStringInfo has
1664/// been populated.
1665bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
1666 FormatStringInfo *FSI) {
1667 FSI->HasVAListArg = Format->getFirstArg() == 0;
1668 FSI->FormatIdx = Format->getFormatIdx() - 1;
1669 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001670
Richard Smith55ce3522012-06-25 20:30:08 +00001671 // The way the format attribute works in GCC, the implicit this argument
1672 // of member functions is counted. However, it doesn't appear in our own
1673 // lists, so decrement format_idx in that case.
1674 if (IsCXXMember) {
1675 if(FSI->FormatIdx == 0)
1676 return false;
1677 --FSI->FormatIdx;
1678 if (FSI->FirstDataArg != 0)
1679 --FSI->FirstDataArg;
1680 }
1681 return true;
1682}
Mike Stump11289f42009-09-09 15:08:12 +00001683
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001684/// Checks if a the given expression evaluates to null.
1685///
1686/// \brief Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00001687static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001688 // If the expression has non-null type, it doesn't evaluate to null.
1689 if (auto nullability
1690 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
1691 if (*nullability == NullabilityKind::NonNull)
1692 return false;
1693 }
1694
Ted Kremeneka146db32014-01-17 06:24:47 +00001695 // As a special case, transparent unions initialized with zero are
1696 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001697 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00001698 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
1699 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001700 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00001701 if (const InitListExpr *ILE =
1702 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001703 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00001704 }
1705
1706 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00001707 return (!Expr->isValueDependent() &&
1708 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
1709 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001710}
1711
1712static void CheckNonNullArgument(Sema &S,
1713 const Expr *ArgExpr,
1714 SourceLocation CallSiteLoc) {
1715 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00001716 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
1717 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00001718}
1719
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001720bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
1721 FormatStringInfo FSI;
1722 if ((GetFormatStringType(Format) == FST_NSString) &&
1723 getFormatStringInfo(Format, false, &FSI)) {
1724 Idx = FSI.FormatIdx;
1725 return true;
1726 }
1727 return false;
1728}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001729/// \brief Diagnose use of %s directive in an NSString which is being passed
1730/// as formatting string to formatting method.
1731static void
1732DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
1733 const NamedDecl *FDecl,
1734 Expr **Args,
1735 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001736 unsigned Idx = 0;
1737 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001738 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
1739 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001740 Idx = 2;
1741 Format = true;
1742 }
1743 else
1744 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
1745 if (S.GetFormatNSStringIdx(I, Idx)) {
1746 Format = true;
1747 break;
1748 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001749 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001750 if (!Format || NumArgs <= Idx)
1751 return;
1752 const Expr *FormatExpr = Args[Idx];
1753 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
1754 FormatExpr = CSCE->getSubExpr();
1755 const StringLiteral *FormatString;
1756 if (const ObjCStringLiteral *OSL =
1757 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
1758 FormatString = OSL->getString();
1759 else
1760 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
1761 if (!FormatString)
1762 return;
1763 if (S.FormatStringHasSArg(FormatString)) {
1764 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
1765 << "%s" << 1 << 1;
1766 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
1767 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001768 }
1769}
1770
Douglas Gregorb4866e82015-06-19 18:13:19 +00001771/// Determine whether the given type has a non-null nullability annotation.
1772static bool isNonNullType(ASTContext &ctx, QualType type) {
1773 if (auto nullability = type->getNullability(ctx))
1774 return *nullability == NullabilityKind::NonNull;
1775
1776 return false;
1777}
1778
Ted Kremenek2bc73332014-01-17 06:24:43 +00001779static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00001780 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00001781 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00001782 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00001783 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001784 assert((FDecl || Proto) && "Need a function declaration or prototype");
1785
Ted Kremenek9aedc152014-01-17 06:24:56 +00001786 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00001787 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00001788 if (FDecl) {
1789 // Handle the nonnull attribute on the function/method declaration itself.
1790 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
1791 if (!NonNull->args_size()) {
1792 // Easy case: all pointer arguments are nonnull.
1793 for (const auto *Arg : Args)
1794 if (S.isValidPointerAttrType(Arg->getType()))
1795 CheckNonNullArgument(S, Arg, CallSiteLoc);
1796 return;
1797 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001798
Douglas Gregorb4866e82015-06-19 18:13:19 +00001799 for (unsigned Val : NonNull->args()) {
1800 if (Val >= Args.size())
1801 continue;
1802 if (NonNullArgs.empty())
1803 NonNullArgs.resize(Args.size());
1804 NonNullArgs.set(Val);
1805 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001806 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00001807 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00001808
Douglas Gregorb4866e82015-06-19 18:13:19 +00001809 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
1810 // Handle the nonnull attribute on the parameters of the
1811 // function/method.
1812 ArrayRef<ParmVarDecl*> parms;
1813 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
1814 parms = FD->parameters();
1815 else
1816 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
1817
1818 unsigned ParamIndex = 0;
1819 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
1820 I != E; ++I, ++ParamIndex) {
1821 const ParmVarDecl *PVD = *I;
1822 if (PVD->hasAttr<NonNullAttr>() ||
1823 isNonNullType(S.Context, PVD->getType())) {
1824 if (NonNullArgs.empty())
1825 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00001826
Douglas Gregorb4866e82015-06-19 18:13:19 +00001827 NonNullArgs.set(ParamIndex);
1828 }
1829 }
1830 } else {
1831 // If we have a non-function, non-method declaration but no
1832 // function prototype, try to dig out the function prototype.
1833 if (!Proto) {
1834 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
1835 QualType type = VD->getType().getNonReferenceType();
1836 if (auto pointerType = type->getAs<PointerType>())
1837 type = pointerType->getPointeeType();
1838 else if (auto blockType = type->getAs<BlockPointerType>())
1839 type = blockType->getPointeeType();
1840 // FIXME: data member pointers?
1841
1842 // Dig out the function prototype, if there is one.
1843 Proto = type->getAs<FunctionProtoType>();
1844 }
1845 }
1846
1847 // Fill in non-null argument information from the nullability
1848 // information on the parameter types (if we have them).
1849 if (Proto) {
1850 unsigned Index = 0;
1851 for (auto paramType : Proto->getParamTypes()) {
1852 if (isNonNullType(S.Context, paramType)) {
1853 if (NonNullArgs.empty())
1854 NonNullArgs.resize(Args.size());
1855
1856 NonNullArgs.set(Index);
1857 }
1858
1859 ++Index;
1860 }
1861 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00001862 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001863
Douglas Gregorb4866e82015-06-19 18:13:19 +00001864 // Check for non-null arguments.
1865 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
1866 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00001867 if (NonNullArgs[ArgIndex])
1868 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00001869 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00001870}
1871
Richard Smith55ce3522012-06-25 20:30:08 +00001872/// Handles the checks for format strings, non-POD arguments to vararg
1873/// functions, and NULL arguments passed to non-NULL parameters.
Douglas Gregorb4866e82015-06-19 18:13:19 +00001874void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
1875 ArrayRef<const Expr *> Args, bool IsMemberFunction,
Alp Toker9cacbab2014-01-20 20:26:09 +00001876 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +00001877 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00001878 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00001879 if (CurContext->isDependentContext())
1880 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001881
Ted Kremenekb8176da2010-09-09 04:33:05 +00001882 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00001883 llvm::SmallBitVector CheckedVarArgs;
1884 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001885 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001886 // Only create vector if there are format attributes.
1887 CheckedVarArgs.resize(Args.size());
1888
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001889 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00001890 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001891 }
Richard Smithd7293d72013-08-05 18:49:43 +00001892 }
Richard Smith55ce3522012-06-25 20:30:08 +00001893
1894 // Refuse POD arguments that weren't caught by the format string
1895 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +00001896 if (CallType != VariadicDoesNotApply) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001897 unsigned NumParams = Proto ? Proto->getNumParams()
1898 : FDecl && isa<FunctionDecl>(FDecl)
1899 ? cast<FunctionDecl>(FDecl)->getNumParams()
1900 : FDecl && isa<ObjCMethodDecl>(FDecl)
1901 ? cast<ObjCMethodDecl>(FDecl)->param_size()
1902 : 0;
1903
Alp Toker9cacbab2014-01-20 20:26:09 +00001904 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001905 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00001906 if (const Expr *Arg = Args[ArgIdx]) {
1907 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
1908 checkVariadicArgument(Arg, CallType);
1909 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001910 }
Richard Smithd7293d72013-08-05 18:49:43 +00001911 }
Mike Stump11289f42009-09-09 15:08:12 +00001912
Douglas Gregorb4866e82015-06-19 18:13:19 +00001913 if (FDecl || Proto) {
1914 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001915
Richard Trieu41bc0992013-06-22 00:20:41 +00001916 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00001917 if (FDecl) {
1918 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
1919 CheckArgumentWithTypeTag(I, Args.data());
1920 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001921 }
Richard Smith55ce3522012-06-25 20:30:08 +00001922}
1923
1924/// CheckConstructorCall - Check a constructor call for correctness and safety
1925/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00001926void Sema::CheckConstructorCall(FunctionDecl *FDecl,
1927 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00001928 const FunctionProtoType *Proto,
1929 SourceLocation Loc) {
1930 VariadicCallType CallType =
1931 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Douglas Gregorb4866e82015-06-19 18:13:19 +00001932 checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(),
1933 CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00001934}
1935
1936/// CheckFunctionCall - Check a direct function call for various correctness
1937/// and safety properties not strictly enforced by the C type system.
1938bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
1939 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001940 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
1941 isa<CXXMethodDecl>(FDecl);
1942 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
1943 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00001944 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
1945 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00001946 Expr** Args = TheCall->getArgs();
1947 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +00001948 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001949 // If this is a call to a member operator, hide the first argument
1950 // from checkCall.
1951 // FIXME: Our choice of AST representation here is less than ideal.
1952 ++Args;
1953 --NumArgs;
1954 }
Douglas Gregorb4866e82015-06-19 18:13:19 +00001955 checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00001956 IsMemberFunction, TheCall->getRParenLoc(),
1957 TheCall->getCallee()->getSourceRange(), CallType);
1958
1959 IdentifierInfo *FnInfo = FDecl->getIdentifier();
1960 // None of the checks below are needed for functions that don't have
1961 // simple names (e.g., C++ conversion functions).
1962 if (!FnInfo)
1963 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001964
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001965 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001966 if (getLangOpts().ObjC1)
1967 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001968
Anna Zaks22122702012-01-17 00:37:07 +00001969 unsigned CMId = FDecl->getMemoryFunctionKind();
1970 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00001971 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00001972
Anna Zaks201d4892012-01-13 21:52:01 +00001973 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00001974 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00001975 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00001976 else if (CMId == Builtin::BIstrncat)
1977 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00001978 else
Anna Zaks22122702012-01-17 00:37:07 +00001979 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00001980
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001981 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00001982}
1983
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001984bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00001985 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00001986 VariadicCallType CallType =
1987 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001988
Douglas Gregorb4866e82015-06-19 18:13:19 +00001989 checkCall(Method, nullptr, Args,
1990 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
1991 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001992
1993 return false;
1994}
1995
Richard Trieu664c4c62013-06-20 21:03:13 +00001996bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
1997 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00001998 QualType Ty;
1999 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002000 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002001 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002002 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002003 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002004 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002005
Douglas Gregorb4866e82015-06-19 18:13:19 +00002006 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2007 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002008 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002009
Richard Trieu664c4c62013-06-20 21:03:13 +00002010 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00002011 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00002012 CallType = VariadicDoesNotApply;
2013 } else if (Ty->isBlockPointerType()) {
2014 CallType = VariadicBlock;
2015 } else { // Ty->isFunctionPointerType()
2016 CallType = VariadicFunction;
2017 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002018
Douglas Gregorb4866e82015-06-19 18:13:19 +00002019 checkCall(NDecl, Proto,
2020 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2021 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00002022 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00002023
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002024 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00002025}
2026
Richard Trieu41bc0992013-06-22 00:20:41 +00002027/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2028/// such as function pointers returned from functions.
2029bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002030 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00002031 TheCall->getCallee());
Douglas Gregorb4866e82015-06-19 18:13:19 +00002032 checkCall(/*FDecl=*/nullptr, Proto,
Craig Topper8c2a2a02014-08-30 16:55:39 +00002033 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00002034 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00002035 TheCall->getCallee()->getSourceRange(), CallType);
2036
2037 return false;
2038}
2039
Tim Northovere94a34c2014-03-11 10:49:14 +00002040static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
JF Bastiendda2cb12016-04-18 18:01:49 +00002041 if (!llvm::isValidAtomicOrderingCABI(Ordering))
Tim Northovere94a34c2014-03-11 10:49:14 +00002042 return false;
2043
JF Bastiendda2cb12016-04-18 18:01:49 +00002044 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
Tim Northovere94a34c2014-03-11 10:49:14 +00002045 switch (Op) {
2046 case AtomicExpr::AO__c11_atomic_init:
2047 llvm_unreachable("There is no ordering argument for an init");
2048
2049 case AtomicExpr::AO__c11_atomic_load:
2050 case AtomicExpr::AO__atomic_load_n:
2051 case AtomicExpr::AO__atomic_load:
JF Bastiendda2cb12016-04-18 18:01:49 +00002052 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2053 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002054
2055 case AtomicExpr::AO__c11_atomic_store:
2056 case AtomicExpr::AO__atomic_store:
2057 case AtomicExpr::AO__atomic_store_n:
JF Bastiendda2cb12016-04-18 18:01:49 +00002058 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2059 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2060 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002061
2062 default:
2063 return true;
2064 }
2065}
2066
Richard Smithfeea8832012-04-12 05:08:17 +00002067ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2068 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002069 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2070 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002071
Richard Smithfeea8832012-04-12 05:08:17 +00002072 // All these operations take one of the following forms:
2073 enum {
2074 // C __c11_atomic_init(A *, C)
2075 Init,
2076 // C __c11_atomic_load(A *, int)
2077 Load,
2078 // void __atomic_load(A *, CP, int)
Eric Fiselier8d662442016-03-30 23:39:56 +00002079 LoadCopy,
2080 // void __atomic_store(A *, CP, int)
Richard Smithfeea8832012-04-12 05:08:17 +00002081 Copy,
2082 // C __c11_atomic_add(A *, M, int)
2083 Arithmetic,
2084 // C __atomic_exchange_n(A *, CP, int)
2085 Xchg,
2086 // void __atomic_exchange(A *, C *, CP, int)
2087 GNUXchg,
2088 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2089 C11CmpXchg,
2090 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2091 GNUCmpXchg
2092 } Form = Init;
Eric Fiselier8d662442016-03-30 23:39:56 +00002093 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2094 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
Richard Smithfeea8832012-04-12 05:08:17 +00002095 // where:
2096 // C is an appropriate type,
2097 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2098 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2099 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2100 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002101
Gabor Horvath98bd0982015-03-16 09:59:54 +00002102 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2103 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2104 AtomicExpr::AO__atomic_load,
2105 "need to update code for modified C11 atomics");
Richard Smithfeea8832012-04-12 05:08:17 +00002106 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
2107 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
2108 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2109 Op == AtomicExpr::AO__atomic_store_n ||
2110 Op == AtomicExpr::AO__atomic_exchange_n ||
2111 Op == AtomicExpr::AO__atomic_compare_exchange_n;
2112 bool IsAddSub = false;
2113
2114 switch (Op) {
2115 case AtomicExpr::AO__c11_atomic_init:
2116 Form = Init;
2117 break;
2118
2119 case AtomicExpr::AO__c11_atomic_load:
2120 case AtomicExpr::AO__atomic_load_n:
2121 Form = Load;
2122 break;
2123
Richard Smithfeea8832012-04-12 05:08:17 +00002124 case AtomicExpr::AO__atomic_load:
Eric Fiselier8d662442016-03-30 23:39:56 +00002125 Form = LoadCopy;
2126 break;
2127
2128 case AtomicExpr::AO__c11_atomic_store:
Richard Smithfeea8832012-04-12 05:08:17 +00002129 case AtomicExpr::AO__atomic_store:
2130 case AtomicExpr::AO__atomic_store_n:
2131 Form = Copy;
2132 break;
2133
2134 case AtomicExpr::AO__c11_atomic_fetch_add:
2135 case AtomicExpr::AO__c11_atomic_fetch_sub:
2136 case AtomicExpr::AO__atomic_fetch_add:
2137 case AtomicExpr::AO__atomic_fetch_sub:
2138 case AtomicExpr::AO__atomic_add_fetch:
2139 case AtomicExpr::AO__atomic_sub_fetch:
2140 IsAddSub = true;
2141 // Fall through.
2142 case AtomicExpr::AO__c11_atomic_fetch_and:
2143 case AtomicExpr::AO__c11_atomic_fetch_or:
2144 case AtomicExpr::AO__c11_atomic_fetch_xor:
2145 case AtomicExpr::AO__atomic_fetch_and:
2146 case AtomicExpr::AO__atomic_fetch_or:
2147 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00002148 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00002149 case AtomicExpr::AO__atomic_and_fetch:
2150 case AtomicExpr::AO__atomic_or_fetch:
2151 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00002152 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00002153 Form = Arithmetic;
2154 break;
2155
2156 case AtomicExpr::AO__c11_atomic_exchange:
2157 case AtomicExpr::AO__atomic_exchange_n:
2158 Form = Xchg;
2159 break;
2160
2161 case AtomicExpr::AO__atomic_exchange:
2162 Form = GNUXchg;
2163 break;
2164
2165 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
2166 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
2167 Form = C11CmpXchg;
2168 break;
2169
2170 case AtomicExpr::AO__atomic_compare_exchange:
2171 case AtomicExpr::AO__atomic_compare_exchange_n:
2172 Form = GNUCmpXchg;
2173 break;
2174 }
2175
2176 // Check we have the right number of arguments.
2177 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002178 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00002179 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002180 << TheCall->getCallee()->getSourceRange();
2181 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00002182 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
2183 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002184 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00002185 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002186 << TheCall->getCallee()->getSourceRange();
2187 return ExprError();
2188 }
2189
Richard Smithfeea8832012-04-12 05:08:17 +00002190 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002191 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002192 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
2193 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
2194 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00002195 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002196 << Ptr->getType() << Ptr->getSourceRange();
2197 return ExprError();
2198 }
2199
Richard Smithfeea8832012-04-12 05:08:17 +00002200 // For a __c11 builtin, this should be a pointer to an _Atomic type.
2201 QualType AtomTy = pointerType->getPointeeType(); // 'A'
2202 QualType ValType = AtomTy; // 'C'
2203 if (IsC11) {
2204 if (!AtomTy->isAtomicType()) {
2205 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
2206 << Ptr->getType() << Ptr->getSourceRange();
2207 return ExprError();
2208 }
Richard Smithe00921a2012-09-15 06:09:58 +00002209 if (AtomTy.isConstQualified()) {
2210 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
2211 << Ptr->getType() << Ptr->getSourceRange();
2212 return ExprError();
2213 }
Richard Smithfeea8832012-04-12 05:08:17 +00002214 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiselier8d662442016-03-30 23:39:56 +00002215 } else if (Form != Load && Form != LoadCopy) {
Eric Fiseliera3a7c562015-10-04 00:11:02 +00002216 if (ValType.isConstQualified()) {
2217 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
2218 << Ptr->getType() << Ptr->getSourceRange();
2219 return ExprError();
2220 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002221 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002222
Richard Smithfeea8832012-04-12 05:08:17 +00002223 // For an arithmetic operation, the implied arithmetic must be well-formed.
2224 if (Form == Arithmetic) {
2225 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
2226 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
2227 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2228 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2229 return ExprError();
2230 }
2231 if (!IsAddSub && !ValType->isIntegerType()) {
2232 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
2233 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2234 return ExprError();
2235 }
David Majnemere85cff82015-01-28 05:48:06 +00002236 if (IsC11 && ValType->isPointerType() &&
2237 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
2238 diag::err_incomplete_type)) {
2239 return ExprError();
2240 }
Richard Smithfeea8832012-04-12 05:08:17 +00002241 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
2242 // For __atomic_*_n operations, the value type must be a scalar integral or
2243 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002244 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00002245 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2246 return ExprError();
2247 }
2248
Eli Friedmanaa769812013-09-11 03:49:34 +00002249 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
2250 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00002251 // For GNU atomics, require a trivially-copyable type. This is not part of
2252 // the GNU atomics specification, but we enforce it for sanity.
2253 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002254 << Ptr->getType() << Ptr->getSourceRange();
2255 return ExprError();
2256 }
2257
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002258 switch (ValType.getObjCLifetime()) {
2259 case Qualifiers::OCL_None:
2260 case Qualifiers::OCL_ExplicitNone:
2261 // okay
2262 break;
2263
2264 case Qualifiers::OCL_Weak:
2265 case Qualifiers::OCL_Strong:
2266 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00002267 // FIXME: Can this happen? By this point, ValType should be known
2268 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002269 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
2270 << ValType << Ptr->getSourceRange();
2271 return ExprError();
2272 }
2273
David Majnemerc6eb6502015-06-03 00:26:35 +00002274 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
2275 // volatile-ness of the pointee-type inject itself into the result or the
Eric Fiselier8d662442016-03-30 23:39:56 +00002276 // other operands. Similarly atomic_load can take a pointer to a const 'A'.
David Majnemerc6eb6502015-06-03 00:26:35 +00002277 ValType.removeLocalVolatile();
Eric Fiselier8d662442016-03-30 23:39:56 +00002278 ValType.removeLocalConst();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002279 QualType ResultType = ValType;
Eric Fiselier8d662442016-03-30 23:39:56 +00002280 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002281 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00002282 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002283 ResultType = Context.BoolTy;
2284
Richard Smithfeea8832012-04-12 05:08:17 +00002285 // The type of a parameter passed 'by value'. In the GNU atomics, such
2286 // arguments are actually passed as pointers.
2287 QualType ByValType = ValType; // 'CP'
2288 if (!IsC11 && !IsN)
2289 ByValType = Ptr->getType();
2290
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002291 // The first argument --- the pointer --- has a fixed type; we
2292 // deduce the types of the rest of the arguments accordingly. Walk
2293 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00002294 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002295 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00002296 if (i < NumVals[Form] + 1) {
2297 switch (i) {
2298 case 1:
2299 // The second argument is the non-atomic operand. For arithmetic, this
2300 // is always passed by value, and for a compare_exchange it is always
2301 // passed by address. For the rest, GNU uses by-address and C11 uses
2302 // by-value.
2303 assert(Form != Load);
2304 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
2305 Ty = ValType;
2306 else if (Form == Copy || Form == Xchg)
2307 Ty = ByValType;
2308 else if (Form == Arithmetic)
2309 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00002310 else {
2311 Expr *ValArg = TheCall->getArg(i);
2312 unsigned AS = 0;
2313 // Keep address space of non-atomic pointer type.
2314 if (const PointerType *PtrTy =
2315 ValArg->getType()->getAs<PointerType>()) {
2316 AS = PtrTy->getPointeeType().getAddressSpace();
2317 }
2318 Ty = Context.getPointerType(
2319 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
2320 }
Richard Smithfeea8832012-04-12 05:08:17 +00002321 break;
2322 case 2:
2323 // The third argument to compare_exchange / GNU exchange is a
2324 // (pointer to a) desired value.
2325 Ty = ByValType;
2326 break;
2327 case 3:
2328 // The fourth argument to GNU compare_exchange is a 'weak' flag.
2329 Ty = Context.BoolTy;
2330 break;
2331 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002332 } else {
2333 // The order(s) are always converted to int.
2334 Ty = Context.IntTy;
2335 }
Richard Smithfeea8832012-04-12 05:08:17 +00002336
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002337 InitializedEntity Entity =
2338 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00002339 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002340 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2341 if (Arg.isInvalid())
2342 return true;
2343 TheCall->setArg(i, Arg.get());
2344 }
2345
Richard Smithfeea8832012-04-12 05:08:17 +00002346 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002347 SmallVector<Expr*, 5> SubExprs;
2348 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00002349 switch (Form) {
2350 case Init:
2351 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00002352 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00002353 break;
2354 case Load:
2355 SubExprs.push_back(TheCall->getArg(1)); // Order
2356 break;
Eric Fiselier8d662442016-03-30 23:39:56 +00002357 case LoadCopy:
Richard Smithfeea8832012-04-12 05:08:17 +00002358 case Copy:
2359 case Arithmetic:
2360 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002361 SubExprs.push_back(TheCall->getArg(2)); // Order
2362 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00002363 break;
2364 case GNUXchg:
2365 // Note, AtomicExpr::getVal2() has a special case for this atomic.
2366 SubExprs.push_back(TheCall->getArg(3)); // Order
2367 SubExprs.push_back(TheCall->getArg(1)); // Val1
2368 SubExprs.push_back(TheCall->getArg(2)); // Val2
2369 break;
2370 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002371 SubExprs.push_back(TheCall->getArg(3)); // Order
2372 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002373 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00002374 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00002375 break;
2376 case GNUCmpXchg:
2377 SubExprs.push_back(TheCall->getArg(4)); // Order
2378 SubExprs.push_back(TheCall->getArg(1)); // Val1
2379 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
2380 SubExprs.push_back(TheCall->getArg(2)); // Val2
2381 SubExprs.push_back(TheCall->getArg(3)); // Weak
2382 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002383 }
Tim Northovere94a34c2014-03-11 10:49:14 +00002384
2385 if (SubExprs.size() >= 2 && Form != Init) {
2386 llvm::APSInt Result(32);
2387 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
2388 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00002389 Diag(SubExprs[1]->getLocStart(),
2390 diag::warn_atomic_op_has_invalid_memory_order)
2391 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00002392 }
2393
Fariborz Jahanian615de762013-05-28 17:37:39 +00002394 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
2395 SubExprs, ResultType, Op,
2396 TheCall->getRParenLoc());
2397
2398 if ((Op == AtomicExpr::AO__c11_atomic_load ||
2399 (Op == AtomicExpr::AO__c11_atomic_store)) &&
2400 Context.AtomicUsesUnsupportedLibcall(AE))
2401 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
2402 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002403
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002404 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002405}
2406
John McCall29ad95b2011-08-27 01:09:30 +00002407/// checkBuiltinArgument - Given a call to a builtin function, perform
2408/// normal type-checking on the given argument, updating the call in
2409/// place. This is useful when a builtin function requires custom
2410/// type-checking for some of its arguments but not necessarily all of
2411/// them.
2412///
2413/// Returns true on error.
2414static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
2415 FunctionDecl *Fn = E->getDirectCallee();
2416 assert(Fn && "builtin call without direct callee!");
2417
2418 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
2419 InitializedEntity Entity =
2420 InitializedEntity::InitializeParameter(S.Context, Param);
2421
2422 ExprResult Arg = E->getArg(0);
2423 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
2424 if (Arg.isInvalid())
2425 return true;
2426
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002427 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00002428 return false;
2429}
2430
Chris Lattnerdc046542009-05-08 06:58:22 +00002431/// SemaBuiltinAtomicOverloaded - We have a call to a function like
2432/// __sync_fetch_and_add, which is an overloaded function based on the pointer
2433/// type of its first argument. The main ActOnCallExpr routines have already
2434/// promoted the types of arguments because all of these calls are prototyped as
2435/// void(...).
2436///
2437/// This function goes through and does final semantic checking for these
2438/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00002439ExprResult
2440Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002441 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00002442 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2443 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2444
2445 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002446 if (TheCall->getNumArgs() < 1) {
2447 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2448 << 0 << 1 << TheCall->getNumArgs()
2449 << TheCall->getCallee()->getSourceRange();
2450 return ExprError();
2451 }
Mike Stump11289f42009-09-09 15:08:12 +00002452
Chris Lattnerdc046542009-05-08 06:58:22 +00002453 // Inspect the first argument of the atomic builtin. This should always be
2454 // a pointer type, whose element is an integral scalar or pointer type.
2455 // Because it is a pointer type, we don't have to worry about any implicit
2456 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002457 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00002458 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00002459 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
2460 if (FirstArgResult.isInvalid())
2461 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002462 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00002463 TheCall->setArg(0, FirstArg);
2464
John McCall31168b02011-06-15 23:02:42 +00002465 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
2466 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002467 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
2468 << FirstArg->getType() << FirstArg->getSourceRange();
2469 return ExprError();
2470 }
Mike Stump11289f42009-09-09 15:08:12 +00002471
John McCall31168b02011-06-15 23:02:42 +00002472 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00002473 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002474 !ValType->isBlockPointerType()) {
2475 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
2476 << FirstArg->getType() << FirstArg->getSourceRange();
2477 return ExprError();
2478 }
Chris Lattnerdc046542009-05-08 06:58:22 +00002479
John McCall31168b02011-06-15 23:02:42 +00002480 switch (ValType.getObjCLifetime()) {
2481 case Qualifiers::OCL_None:
2482 case Qualifiers::OCL_ExplicitNone:
2483 // okay
2484 break;
2485
2486 case Qualifiers::OCL_Weak:
2487 case Qualifiers::OCL_Strong:
2488 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00002489 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00002490 << ValType << FirstArg->getSourceRange();
2491 return ExprError();
2492 }
2493
John McCallb50451a2011-10-05 07:41:44 +00002494 // Strip any qualifiers off ValType.
2495 ValType = ValType.getUnqualifiedType();
2496
Chandler Carruth3973af72010-07-18 20:54:12 +00002497 // The majority of builtins return a value, but a few have special return
2498 // types, so allow them to override appropriately below.
2499 QualType ResultType = ValType;
2500
Chris Lattnerdc046542009-05-08 06:58:22 +00002501 // We need to figure out which concrete builtin this maps onto. For example,
2502 // __sync_fetch_and_add with a 2 byte object turns into
2503 // __sync_fetch_and_add_2.
2504#define BUILTIN_ROW(x) \
2505 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
2506 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00002507
Chris Lattnerdc046542009-05-08 06:58:22 +00002508 static const unsigned BuiltinIndices[][5] = {
2509 BUILTIN_ROW(__sync_fetch_and_add),
2510 BUILTIN_ROW(__sync_fetch_and_sub),
2511 BUILTIN_ROW(__sync_fetch_and_or),
2512 BUILTIN_ROW(__sync_fetch_and_and),
2513 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00002514 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00002515
Chris Lattnerdc046542009-05-08 06:58:22 +00002516 BUILTIN_ROW(__sync_add_and_fetch),
2517 BUILTIN_ROW(__sync_sub_and_fetch),
2518 BUILTIN_ROW(__sync_and_and_fetch),
2519 BUILTIN_ROW(__sync_or_and_fetch),
2520 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00002521 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00002522
Chris Lattnerdc046542009-05-08 06:58:22 +00002523 BUILTIN_ROW(__sync_val_compare_and_swap),
2524 BUILTIN_ROW(__sync_bool_compare_and_swap),
2525 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00002526 BUILTIN_ROW(__sync_lock_release),
2527 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00002528 };
Mike Stump11289f42009-09-09 15:08:12 +00002529#undef BUILTIN_ROW
2530
Chris Lattnerdc046542009-05-08 06:58:22 +00002531 // Determine the index of the size.
2532 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00002533 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00002534 case 1: SizeIndex = 0; break;
2535 case 2: SizeIndex = 1; break;
2536 case 4: SizeIndex = 2; break;
2537 case 8: SizeIndex = 3; break;
2538 case 16: SizeIndex = 4; break;
2539 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002540 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
2541 << FirstArg->getType() << FirstArg->getSourceRange();
2542 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00002543 }
Mike Stump11289f42009-09-09 15:08:12 +00002544
Chris Lattnerdc046542009-05-08 06:58:22 +00002545 // Each of these builtins has one pointer argument, followed by some number of
2546 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
2547 // that we ignore. Find out which row of BuiltinIndices to read from as well
2548 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00002549 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00002550 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00002551 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00002552 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00002553 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00002554 case Builtin::BI__sync_fetch_and_add:
2555 case Builtin::BI__sync_fetch_and_add_1:
2556 case Builtin::BI__sync_fetch_and_add_2:
2557 case Builtin::BI__sync_fetch_and_add_4:
2558 case Builtin::BI__sync_fetch_and_add_8:
2559 case Builtin::BI__sync_fetch_and_add_16:
2560 BuiltinIndex = 0;
2561 break;
2562
2563 case Builtin::BI__sync_fetch_and_sub:
2564 case Builtin::BI__sync_fetch_and_sub_1:
2565 case Builtin::BI__sync_fetch_and_sub_2:
2566 case Builtin::BI__sync_fetch_and_sub_4:
2567 case Builtin::BI__sync_fetch_and_sub_8:
2568 case Builtin::BI__sync_fetch_and_sub_16:
2569 BuiltinIndex = 1;
2570 break;
2571
2572 case Builtin::BI__sync_fetch_and_or:
2573 case Builtin::BI__sync_fetch_and_or_1:
2574 case Builtin::BI__sync_fetch_and_or_2:
2575 case Builtin::BI__sync_fetch_and_or_4:
2576 case Builtin::BI__sync_fetch_and_or_8:
2577 case Builtin::BI__sync_fetch_and_or_16:
2578 BuiltinIndex = 2;
2579 break;
2580
2581 case Builtin::BI__sync_fetch_and_and:
2582 case Builtin::BI__sync_fetch_and_and_1:
2583 case Builtin::BI__sync_fetch_and_and_2:
2584 case Builtin::BI__sync_fetch_and_and_4:
2585 case Builtin::BI__sync_fetch_and_and_8:
2586 case Builtin::BI__sync_fetch_and_and_16:
2587 BuiltinIndex = 3;
2588 break;
Mike Stump11289f42009-09-09 15:08:12 +00002589
Douglas Gregor73722482011-11-28 16:30:08 +00002590 case Builtin::BI__sync_fetch_and_xor:
2591 case Builtin::BI__sync_fetch_and_xor_1:
2592 case Builtin::BI__sync_fetch_and_xor_2:
2593 case Builtin::BI__sync_fetch_and_xor_4:
2594 case Builtin::BI__sync_fetch_and_xor_8:
2595 case Builtin::BI__sync_fetch_and_xor_16:
2596 BuiltinIndex = 4;
2597 break;
2598
Hal Finkeld2208b52014-10-02 20:53:50 +00002599 case Builtin::BI__sync_fetch_and_nand:
2600 case Builtin::BI__sync_fetch_and_nand_1:
2601 case Builtin::BI__sync_fetch_and_nand_2:
2602 case Builtin::BI__sync_fetch_and_nand_4:
2603 case Builtin::BI__sync_fetch_and_nand_8:
2604 case Builtin::BI__sync_fetch_and_nand_16:
2605 BuiltinIndex = 5;
2606 WarnAboutSemanticsChange = true;
2607 break;
2608
Douglas Gregor73722482011-11-28 16:30:08 +00002609 case Builtin::BI__sync_add_and_fetch:
2610 case Builtin::BI__sync_add_and_fetch_1:
2611 case Builtin::BI__sync_add_and_fetch_2:
2612 case Builtin::BI__sync_add_and_fetch_4:
2613 case Builtin::BI__sync_add_and_fetch_8:
2614 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002615 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00002616 break;
2617
2618 case Builtin::BI__sync_sub_and_fetch:
2619 case Builtin::BI__sync_sub_and_fetch_1:
2620 case Builtin::BI__sync_sub_and_fetch_2:
2621 case Builtin::BI__sync_sub_and_fetch_4:
2622 case Builtin::BI__sync_sub_and_fetch_8:
2623 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002624 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00002625 break;
2626
2627 case Builtin::BI__sync_and_and_fetch:
2628 case Builtin::BI__sync_and_and_fetch_1:
2629 case Builtin::BI__sync_and_and_fetch_2:
2630 case Builtin::BI__sync_and_and_fetch_4:
2631 case Builtin::BI__sync_and_and_fetch_8:
2632 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002633 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00002634 break;
2635
2636 case Builtin::BI__sync_or_and_fetch:
2637 case Builtin::BI__sync_or_and_fetch_1:
2638 case Builtin::BI__sync_or_and_fetch_2:
2639 case Builtin::BI__sync_or_and_fetch_4:
2640 case Builtin::BI__sync_or_and_fetch_8:
2641 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002642 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00002643 break;
2644
2645 case Builtin::BI__sync_xor_and_fetch:
2646 case Builtin::BI__sync_xor_and_fetch_1:
2647 case Builtin::BI__sync_xor_and_fetch_2:
2648 case Builtin::BI__sync_xor_and_fetch_4:
2649 case Builtin::BI__sync_xor_and_fetch_8:
2650 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002651 BuiltinIndex = 10;
2652 break;
2653
2654 case Builtin::BI__sync_nand_and_fetch:
2655 case Builtin::BI__sync_nand_and_fetch_1:
2656 case Builtin::BI__sync_nand_and_fetch_2:
2657 case Builtin::BI__sync_nand_and_fetch_4:
2658 case Builtin::BI__sync_nand_and_fetch_8:
2659 case Builtin::BI__sync_nand_and_fetch_16:
2660 BuiltinIndex = 11;
2661 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00002662 break;
Mike Stump11289f42009-09-09 15:08:12 +00002663
Chris Lattnerdc046542009-05-08 06:58:22 +00002664 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00002665 case Builtin::BI__sync_val_compare_and_swap_1:
2666 case Builtin::BI__sync_val_compare_and_swap_2:
2667 case Builtin::BI__sync_val_compare_and_swap_4:
2668 case Builtin::BI__sync_val_compare_and_swap_8:
2669 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002670 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00002671 NumFixed = 2;
2672 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002673
Chris Lattnerdc046542009-05-08 06:58:22 +00002674 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00002675 case Builtin::BI__sync_bool_compare_and_swap_1:
2676 case Builtin::BI__sync_bool_compare_and_swap_2:
2677 case Builtin::BI__sync_bool_compare_and_swap_4:
2678 case Builtin::BI__sync_bool_compare_and_swap_8:
2679 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002680 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00002681 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00002682 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00002683 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002684
2685 case Builtin::BI__sync_lock_test_and_set:
2686 case Builtin::BI__sync_lock_test_and_set_1:
2687 case Builtin::BI__sync_lock_test_and_set_2:
2688 case Builtin::BI__sync_lock_test_and_set_4:
2689 case Builtin::BI__sync_lock_test_and_set_8:
2690 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002691 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00002692 break;
2693
Chris Lattnerdc046542009-05-08 06:58:22 +00002694 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00002695 case Builtin::BI__sync_lock_release_1:
2696 case Builtin::BI__sync_lock_release_2:
2697 case Builtin::BI__sync_lock_release_4:
2698 case Builtin::BI__sync_lock_release_8:
2699 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002700 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00002701 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00002702 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00002703 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002704
2705 case Builtin::BI__sync_swap:
2706 case Builtin::BI__sync_swap_1:
2707 case Builtin::BI__sync_swap_2:
2708 case Builtin::BI__sync_swap_4:
2709 case Builtin::BI__sync_swap_8:
2710 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002711 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00002712 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00002713 }
Mike Stump11289f42009-09-09 15:08:12 +00002714
Chris Lattnerdc046542009-05-08 06:58:22 +00002715 // Now that we know how many fixed arguments we expect, first check that we
2716 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002717 if (TheCall->getNumArgs() < 1+NumFixed) {
2718 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2719 << 0 << 1+NumFixed << TheCall->getNumArgs()
2720 << TheCall->getCallee()->getSourceRange();
2721 return ExprError();
2722 }
Mike Stump11289f42009-09-09 15:08:12 +00002723
Hal Finkeld2208b52014-10-02 20:53:50 +00002724 if (WarnAboutSemanticsChange) {
2725 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
2726 << TheCall->getCallee()->getSourceRange();
2727 }
2728
Chris Lattner5b9241b2009-05-08 15:36:58 +00002729 // Get the decl for the concrete builtin from this, we can tell what the
2730 // concrete integer type we should convert to is.
2731 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Eric Christopher02d5d862015-08-06 01:01:12 +00002732 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00002733 FunctionDecl *NewBuiltinDecl;
2734 if (NewBuiltinID == BuiltinID)
2735 NewBuiltinDecl = FDecl;
2736 else {
2737 // Perform builtin lookup to avoid redeclaring it.
2738 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
2739 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
2740 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
2741 assert(Res.getFoundDecl());
2742 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00002743 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00002744 return ExprError();
2745 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002746
John McCallcf142162010-08-07 06:22:56 +00002747 // The first argument --- the pointer --- has a fixed type; we
2748 // deduce the types of the rest of the arguments accordingly. Walk
2749 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00002750 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00002751 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00002752
Chris Lattnerdc046542009-05-08 06:58:22 +00002753 // GCC does an implicit conversion to the pointer or integer ValType. This
2754 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00002755 // Initialize the argument.
2756 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2757 ValType, /*consume*/ false);
2758 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00002759 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002760 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002761
Chris Lattnerdc046542009-05-08 06:58:22 +00002762 // Okay, we have something that *can* be converted to the right type. Check
2763 // to see if there is a potentially weird extension going on here. This can
2764 // happen when you do an atomic operation on something like an char* and
2765 // pass in 42. The 42 gets converted to char. This is even more strange
2766 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00002767 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002768 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00002769 }
Mike Stump11289f42009-09-09 15:08:12 +00002770
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002771 ASTContext& Context = this->getASTContext();
2772
2773 // Create a new DeclRefExpr to refer to the new decl.
2774 DeclRefExpr* NewDRE = DeclRefExpr::Create(
2775 Context,
2776 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00002777 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002778 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00002779 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002780 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00002781 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002782 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00002783
Chris Lattnerdc046542009-05-08 06:58:22 +00002784 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00002785 // FIXME: This loses syntactic information.
2786 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
2787 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
2788 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002789 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00002790
Chandler Carruthbc8cab12010-07-18 07:23:17 +00002791 // Change the result type of the call to match the original value type. This
2792 // is arbitrary, but the codegen for these builtins ins design to handle it
2793 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00002794 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002795
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002796 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00002797}
2798
Michael Zolotukhin84df1232015-09-08 23:52:33 +00002799/// SemaBuiltinNontemporalOverloaded - We have a call to
2800/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
2801/// overloaded function based on the pointer type of its last argument.
2802///
2803/// This function goes through and does final semantic checking for these
2804/// builtins.
2805ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
2806 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
2807 DeclRefExpr *DRE =
2808 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2809 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2810 unsigned BuiltinID = FDecl->getBuiltinID();
2811 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
2812 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
2813 "Unexpected nontemporal load/store builtin!");
2814 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
2815 unsigned numArgs = isStore ? 2 : 1;
2816
2817 // Ensure that we have the proper number of arguments.
2818 if (checkArgCount(*this, TheCall, numArgs))
2819 return ExprError();
2820
2821 // Inspect the last argument of the nontemporal builtin. This should always
2822 // be a pointer type, from which we imply the type of the memory access.
2823 // Because it is a pointer type, we don't have to worry about any implicit
2824 // casts here.
2825 Expr *PointerArg = TheCall->getArg(numArgs - 1);
2826 ExprResult PointerArgResult =
2827 DefaultFunctionArrayLvalueConversion(PointerArg);
2828
2829 if (PointerArgResult.isInvalid())
2830 return ExprError();
2831 PointerArg = PointerArgResult.get();
2832 TheCall->setArg(numArgs - 1, PointerArg);
2833
2834 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2835 if (!pointerType) {
2836 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
2837 << PointerArg->getType() << PointerArg->getSourceRange();
2838 return ExprError();
2839 }
2840
2841 QualType ValType = pointerType->getPointeeType();
2842
2843 // Strip any qualifiers off ValType.
2844 ValType = ValType.getUnqualifiedType();
2845 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2846 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
2847 !ValType->isVectorType()) {
2848 Diag(DRE->getLocStart(),
2849 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
2850 << PointerArg->getType() << PointerArg->getSourceRange();
2851 return ExprError();
2852 }
2853
2854 if (!isStore) {
2855 TheCall->setType(ValType);
2856 return TheCallResult;
2857 }
2858
2859 ExprResult ValArg = TheCall->getArg(0);
2860 InitializedEntity Entity = InitializedEntity::InitializeParameter(
2861 Context, ValType, /*consume*/ false);
2862 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2863 if (ValArg.isInvalid())
2864 return ExprError();
2865
2866 TheCall->setArg(0, ValArg.get());
2867 TheCall->setType(Context.VoidTy);
2868 return TheCallResult;
2869}
2870
Chris Lattner6436fb62009-02-18 06:01:06 +00002871/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00002872/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00002873/// Note: It might also make sense to do the UTF-16 conversion here (would
2874/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00002875bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00002876 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00002877 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
2878
Douglas Gregorfb65e592011-07-27 05:40:30 +00002879 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002880 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
2881 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00002882 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00002883 }
Mike Stump11289f42009-09-09 15:08:12 +00002884
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002885 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002886 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002887 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002888 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00002889 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002890 UTF16 *ToPtr = &ToBuf[0];
2891
2892 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2893 &ToPtr, ToPtr + NumBytes,
2894 strictConversion);
2895 // Check for conversion failure.
2896 if (Result != conversionOK)
2897 Diag(Arg->getLocStart(),
2898 diag::warn_cfstring_truncated) << Arg->getSourceRange();
2899 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00002900 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002901}
2902
Charles Davisc7d5c942015-09-17 20:55:33 +00002903/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
2904/// for validity. Emit an error and return true on failure; return false
2905/// on success.
2906bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00002907 Expr *Fn = TheCall->getCallee();
2908 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00002909 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002910 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002911 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2912 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00002913 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002914 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00002915 return true;
2916 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002917
2918 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00002919 return Diag(TheCall->getLocEnd(),
2920 diag::err_typecheck_call_too_few_args_at_least)
2921 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002922 }
2923
John McCall29ad95b2011-08-27 01:09:30 +00002924 // Type-check the first argument normally.
2925 if (checkBuiltinArgument(*this, TheCall, 0))
2926 return true;
2927
Chris Lattnere202e6a2007-12-20 00:05:45 +00002928 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00002929 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00002930 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00002931 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00002932 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00002933 else if (FunctionDecl *FD = getCurFunctionDecl())
2934 isVariadic = FD->isVariadic();
2935 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002936 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00002937
Chris Lattnere202e6a2007-12-20 00:05:45 +00002938 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002939 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2940 return true;
2941 }
Mike Stump11289f42009-09-09 15:08:12 +00002942
Chris Lattner43be2e62007-12-19 23:59:04 +00002943 // Verify that the second argument to the builtin is the last argument of the
2944 // current function or method.
2945 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00002946 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002947
Nico Weber9eea7642013-05-24 23:31:57 +00002948 // These are valid if SecondArgIsLastNamedArgument is false after the next
2949 // block.
2950 QualType Type;
2951 SourceLocation ParamLoc;
Aaron Ballman1de59c52016-04-24 13:30:21 +00002952 bool IsCRegister = false;
Nico Weber9eea7642013-05-24 23:31:57 +00002953
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002954 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
2955 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002956 // FIXME: This isn't correct for methods (results in bogus warning).
2957 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002958 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00002959 if (CurBlock)
David Majnemera3debed2016-06-24 05:33:44 +00002960 LastArg = CurBlock->TheDecl->parameters().back();
Steve Naroff439a3e42009-04-15 19:33:47 +00002961 else if (FunctionDecl *FD = getCurFunctionDecl())
David Majnemera3debed2016-06-24 05:33:44 +00002962 LastArg = FD->parameters().back();
Chris Lattner43be2e62007-12-19 23:59:04 +00002963 else
David Majnemera3debed2016-06-24 05:33:44 +00002964 LastArg = getCurMethodDecl()->parameters().back();
Chris Lattner43be2e62007-12-19 23:59:04 +00002965 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00002966
2967 Type = PV->getType();
2968 ParamLoc = PV->getLocation();
Aaron Ballman1de59c52016-04-24 13:30:21 +00002969 IsCRegister =
2970 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
Chris Lattner43be2e62007-12-19 23:59:04 +00002971 }
2972 }
Mike Stump11289f42009-09-09 15:08:12 +00002973
Chris Lattner43be2e62007-12-19 23:59:04 +00002974 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002975 Diag(TheCall->getArg(1)->getLocStart(),
Aaron Ballman05164812016-04-18 18:10:53 +00002976 diag::warn_second_arg_of_va_start_not_last_named_param);
Aaron Ballman1de59c52016-04-24 13:30:21 +00002977 else if (IsCRegister || Type->isReferenceType() ||
2978 Type->isPromotableIntegerType() ||
2979 Type->isSpecificBuiltinType(BuiltinType::Float)) {
2980 unsigned Reason = 0;
2981 if (Type->isReferenceType()) Reason = 1;
2982 else if (IsCRegister) Reason = 2;
2983 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
Nico Weber9eea7642013-05-24 23:31:57 +00002984 Diag(ParamLoc, diag::note_parameter_type) << Type;
2985 }
2986
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00002987 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00002988 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00002989}
Chris Lattner43be2e62007-12-19 23:59:04 +00002990
Charles Davisc7d5c942015-09-17 20:55:33 +00002991/// Check the arguments to '__builtin_va_start' for validity, and that
2992/// it was called from a function of the native ABI.
2993/// Emit an error and return true on failure; return false on success.
2994bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
2995 // On x86-64 Unix, don't allow this in Win64 ABI functions.
2996 // On x64 Windows, don't allow this in System V ABI functions.
2997 // (Yes, that means there's no corresponding way to support variadic
2998 // System V ABI functions on Windows.)
2999 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) {
3000 unsigned OS = Context.getTargetInfo().getTriple().getOS();
3001 clang::CallingConv CC = CC_C;
3002 if (const FunctionDecl *FD = getCurFunctionDecl())
3003 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3004 if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) ||
3005 (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64))
3006 return Diag(TheCall->getCallee()->getLocStart(),
3007 diag::err_va_start_used_in_wrong_abi_function)
3008 << (OS != llvm::Triple::Win32);
3009 }
3010 return SemaBuiltinVAStartImpl(TheCall);
3011}
3012
3013/// Check the arguments to '__builtin_ms_va_start' for validity, and that
3014/// it was called from a Win64 ABI function.
3015/// Emit an error and return true on failure; return false on success.
3016bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) {
3017 // This only makes sense for x86-64.
3018 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3019 Expr *Callee = TheCall->getCallee();
3020 if (TT.getArch() != llvm::Triple::x86_64)
3021 return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt);
3022 // Don't allow this in System V ABI functions.
3023 clang::CallingConv CC = CC_C;
3024 if (const FunctionDecl *FD = getCurFunctionDecl())
3025 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3026 if (CC == CC_X86_64SysV ||
3027 (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64))
3028 return Diag(Callee->getLocStart(),
3029 diag::err_ms_va_start_used_in_sysv_function);
3030 return SemaBuiltinVAStartImpl(TheCall);
3031}
3032
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003033bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
3034 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
3035 // const char *named_addr);
3036
3037 Expr *Func = Call->getCallee();
3038
3039 if (Call->getNumArgs() < 3)
3040 return Diag(Call->getLocEnd(),
3041 diag::err_typecheck_call_too_few_args_at_least)
3042 << 0 /*function call*/ << 3 << Call->getNumArgs();
3043
3044 // Determine whether the current function is variadic or not.
3045 bool IsVariadic;
3046 if (BlockScopeInfo *CurBlock = getCurBlock())
3047 IsVariadic = CurBlock->TheDecl->isVariadic();
3048 else if (FunctionDecl *FD = getCurFunctionDecl())
3049 IsVariadic = FD->isVariadic();
3050 else if (ObjCMethodDecl *MD = getCurMethodDecl())
3051 IsVariadic = MD->isVariadic();
3052 else
3053 llvm_unreachable("unexpected statement type");
3054
3055 if (!IsVariadic) {
3056 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3057 return true;
3058 }
3059
3060 // Type-check the first argument normally.
3061 if (checkBuiltinArgument(*this, Call, 0))
3062 return true;
3063
Benjamin Kramere0ca6e12015-03-01 18:09:50 +00003064 const struct {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003065 unsigned ArgNo;
3066 QualType Type;
3067 } ArgumentTypes[] = {
3068 { 1, Context.getPointerType(Context.CharTy.withConst()) },
3069 { 2, Context.getSizeType() },
3070 };
3071
3072 for (const auto &AT : ArgumentTypes) {
3073 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
3074 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
3075 continue;
3076 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
3077 << Arg->getType() << AT.Type << 1 /* different class */
3078 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
3079 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
3080 }
3081
3082 return false;
3083}
3084
Chris Lattner2da14fb2007-12-20 00:26:33 +00003085/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
3086/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00003087bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
3088 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00003089 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00003090 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00003091 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00003092 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003093 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003094 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00003095 << SourceRange(TheCall->getArg(2)->getLocStart(),
3096 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003097
John Wiegley01296292011-04-08 18:41:53 +00003098 ExprResult OrigArg0 = TheCall->getArg(0);
3099 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00003100
Chris Lattner2da14fb2007-12-20 00:26:33 +00003101 // Do standard promotions between the two arguments, returning their common
3102 // type.
Chris Lattner08464942007-12-28 05:29:59 +00003103 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00003104 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
3105 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00003106
3107 // Make sure any conversions are pushed back into the call; this is
3108 // type safe since unordered compare builtins are declared as "_Bool
3109 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00003110 TheCall->setArg(0, OrigArg0.get());
3111 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00003112
John Wiegley01296292011-04-08 18:41:53 +00003113 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00003114 return false;
3115
Chris Lattner2da14fb2007-12-20 00:26:33 +00003116 // If the common type isn't a real floating type, then the arguments were
3117 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00003118 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00003119 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003120 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00003121 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
3122 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003123
Chris Lattner2da14fb2007-12-20 00:26:33 +00003124 return false;
3125}
3126
Benjamin Kramer634fc102010-02-15 22:42:31 +00003127/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
3128/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00003129/// to check everything. We expect the last argument to be a floating point
3130/// value.
3131bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
3132 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00003133 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00003134 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00003135 if (TheCall->getNumArgs() > NumArgs)
3136 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003137 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003138 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00003139 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003140 (*(TheCall->arg_end()-1))->getLocEnd());
3141
Benjamin Kramer64aae502010-02-16 10:07:31 +00003142 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00003143
Eli Friedman7e4faac2009-08-31 20:06:00 +00003144 if (OrigArg->isTypeDependent())
3145 return false;
3146
Chris Lattner68784ef2010-05-06 05:50:07 +00003147 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00003148 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00003149 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003150 diag::err_typecheck_call_invalid_unary_fp)
3151 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003152
Chris Lattner68784ef2010-05-06 05:50:07 +00003153 // If this is an implicit conversion from float -> double, remove it.
3154 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
3155 Expr *CastArg = Cast->getSubExpr();
3156 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
3157 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
3158 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00003159 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00003160 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00003161 }
3162 }
3163
Eli Friedman7e4faac2009-08-31 20:06:00 +00003164 return false;
3165}
3166
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003167/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
3168// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00003169ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00003170 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003171 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00003172 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00003173 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3174 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003175
Nate Begemana0110022010-06-08 00:16:34 +00003176 // Determine which of the following types of shufflevector we're checking:
3177 // 1) unary, vector mask: (lhs, mask)
Craig Topperb3174a82016-05-18 04:11:25 +00003178 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
Nate Begemana0110022010-06-08 00:16:34 +00003179 QualType resType = TheCall->getArg(0)->getType();
3180 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00003181
Douglas Gregorc25f7662009-05-19 22:10:17 +00003182 if (!TheCall->getArg(0)->isTypeDependent() &&
3183 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00003184 QualType LHSType = TheCall->getArg(0)->getType();
3185 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00003186
Craig Topperbaca3892013-07-29 06:47:04 +00003187 if (!LHSType->isVectorType() || !RHSType->isVectorType())
3188 return ExprError(Diag(TheCall->getLocStart(),
3189 diag::err_shufflevector_non_vector)
3190 << SourceRange(TheCall->getArg(0)->getLocStart(),
3191 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00003192
Nate Begemana0110022010-06-08 00:16:34 +00003193 numElements = LHSType->getAs<VectorType>()->getNumElements();
3194 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00003195
Nate Begemana0110022010-06-08 00:16:34 +00003196 // Check to see if we have a call with 2 vector arguments, the unary shuffle
3197 // with mask. If so, verify that RHS is an integer vector type with the
3198 // same number of elts as lhs.
3199 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00003200 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00003201 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00003202 return ExprError(Diag(TheCall->getLocStart(),
3203 diag::err_shufflevector_incompatible_vector)
3204 << SourceRange(TheCall->getArg(1)->getLocStart(),
3205 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00003206 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00003207 return ExprError(Diag(TheCall->getLocStart(),
3208 diag::err_shufflevector_incompatible_vector)
3209 << SourceRange(TheCall->getArg(0)->getLocStart(),
3210 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00003211 } else if (numElements != numResElements) {
3212 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00003213 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00003214 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00003215 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003216 }
3217
3218 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00003219 if (TheCall->getArg(i)->isTypeDependent() ||
3220 TheCall->getArg(i)->isValueDependent())
3221 continue;
3222
Nate Begemana0110022010-06-08 00:16:34 +00003223 llvm::APSInt Result(32);
3224 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
3225 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00003226 diag::err_shufflevector_nonconstant_argument)
3227 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003228
Craig Topper50ad5b72013-08-03 17:40:38 +00003229 // Allow -1 which will be translated to undef in the IR.
3230 if (Result.isSigned() && Result.isAllOnesValue())
3231 continue;
3232
Chris Lattner7ab824e2008-08-10 02:05:13 +00003233 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003234 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00003235 diag::err_shufflevector_argument_too_large)
3236 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003237 }
3238
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003239 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003240
Chris Lattner7ab824e2008-08-10 02:05:13 +00003241 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003242 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00003243 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003244 }
3245
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003246 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
3247 TheCall->getCallee()->getLocStart(),
3248 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003249}
Chris Lattner43be2e62007-12-19 23:59:04 +00003250
Hal Finkelc4d7c822013-09-18 03:29:45 +00003251/// SemaConvertVectorExpr - Handle __builtin_convertvector
3252ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
3253 SourceLocation BuiltinLoc,
3254 SourceLocation RParenLoc) {
3255 ExprValueKind VK = VK_RValue;
3256 ExprObjectKind OK = OK_Ordinary;
3257 QualType DstTy = TInfo->getType();
3258 QualType SrcTy = E->getType();
3259
3260 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
3261 return ExprError(Diag(BuiltinLoc,
3262 diag::err_convertvector_non_vector)
3263 << E->getSourceRange());
3264 if (!DstTy->isVectorType() && !DstTy->isDependentType())
3265 return ExprError(Diag(BuiltinLoc,
3266 diag::err_convertvector_non_vector_type));
3267
3268 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
3269 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
3270 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
3271 if (SrcElts != DstElts)
3272 return ExprError(Diag(BuiltinLoc,
3273 diag::err_convertvector_incompatible_vector)
3274 << E->getSourceRange());
3275 }
3276
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003277 return new (Context)
3278 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00003279}
3280
Daniel Dunbarb7257262008-07-21 22:59:13 +00003281/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
3282// This is declared to take (const void*, ...) and can take two
3283// optional constant int args.
3284bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00003285 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003286
Chris Lattner3b054132008-11-19 05:08:23 +00003287 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003288 return Diag(TheCall->getLocEnd(),
3289 diag::err_typecheck_call_too_many_args_at_most)
3290 << 0 /*function call*/ << 3 << NumArgs
3291 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003292
3293 // Argument 0 is checked for us and the remaining arguments must be
3294 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00003295 for (unsigned i = 1; i != NumArgs; ++i)
3296 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00003297 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003298
Warren Hunt20e4a5d2014-02-21 23:08:53 +00003299 return false;
3300}
3301
Hal Finkelf0417332014-07-17 14:25:55 +00003302/// SemaBuiltinAssume - Handle __assume (MS Extension).
3303// __assume does not evaluate its arguments, and should warn if its argument
3304// has side effects.
3305bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
3306 Expr *Arg = TheCall->getArg(0);
3307 if (Arg->isInstantiationDependent()) return false;
3308
3309 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00003310 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00003311 << Arg->getSourceRange()
3312 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
3313
3314 return false;
3315}
3316
3317/// Handle __builtin_assume_aligned. This is declared
3318/// as (const void*, size_t, ...) and can take one optional constant int arg.
3319bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
3320 unsigned NumArgs = TheCall->getNumArgs();
3321
3322 if (NumArgs > 3)
3323 return Diag(TheCall->getLocEnd(),
3324 diag::err_typecheck_call_too_many_args_at_most)
3325 << 0 /*function call*/ << 3 << NumArgs
3326 << TheCall->getSourceRange();
3327
3328 // The alignment must be a constant integer.
3329 Expr *Arg = TheCall->getArg(1);
3330
3331 // We can't check the value of a dependent argument.
3332 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
3333 llvm::APSInt Result;
3334 if (SemaBuiltinConstantArg(TheCall, 1, Result))
3335 return true;
3336
3337 if (!Result.isPowerOf2())
3338 return Diag(TheCall->getLocStart(),
3339 diag::err_alignment_not_power_of_two)
3340 << Arg->getSourceRange();
3341 }
3342
3343 if (NumArgs > 2) {
3344 ExprResult Arg(TheCall->getArg(2));
3345 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3346 Context.getSizeType(), false);
3347 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3348 if (Arg.isInvalid()) return true;
3349 TheCall->setArg(2, Arg.get());
3350 }
Hal Finkelf0417332014-07-17 14:25:55 +00003351
3352 return false;
3353}
3354
Eric Christopher8d0c6212010-04-17 02:26:23 +00003355/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
3356/// TheCall is a constant expression.
3357bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
3358 llvm::APSInt &Result) {
3359 Expr *Arg = TheCall->getArg(ArgNum);
3360 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3361 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3362
3363 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
3364
3365 if (!Arg->isIntegerConstantExpr(Result, Context))
3366 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00003367 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00003368
Chris Lattnerd545ad12009-09-23 06:06:36 +00003369 return false;
3370}
3371
Richard Sandiford28940af2014-04-16 08:47:51 +00003372/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
3373/// TheCall is a constant expression in the range [Low, High].
3374bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
3375 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00003376 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00003377
3378 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00003379 Expr *Arg = TheCall->getArg(ArgNum);
3380 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00003381 return false;
3382
Eric Christopher8d0c6212010-04-17 02:26:23 +00003383 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00003384 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00003385 return true;
3386
Richard Sandiford28940af2014-04-16 08:47:51 +00003387 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00003388 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00003389 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00003390
3391 return false;
3392}
3393
Luke Cheeseman59b2d832015-06-15 17:51:01 +00003394/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
3395/// TheCall is an ARM/AArch64 special register string literal.
3396bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
3397 int ArgNum, unsigned ExpectedFieldNum,
3398 bool AllowName) {
3399 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
3400 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
3401 BuiltinID == ARM::BI__builtin_arm_rsr ||
3402 BuiltinID == ARM::BI__builtin_arm_rsrp ||
3403 BuiltinID == ARM::BI__builtin_arm_wsr ||
3404 BuiltinID == ARM::BI__builtin_arm_wsrp;
3405 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
3406 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
3407 BuiltinID == AArch64::BI__builtin_arm_rsr ||
3408 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
3409 BuiltinID == AArch64::BI__builtin_arm_wsr ||
3410 BuiltinID == AArch64::BI__builtin_arm_wsrp;
3411 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
3412
3413 // We can't check the value of a dependent argument.
3414 Expr *Arg = TheCall->getArg(ArgNum);
3415 if (Arg->isTypeDependent() || Arg->isValueDependent())
3416 return false;
3417
3418 // Check if the argument is a string literal.
3419 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3420 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
3421 << Arg->getSourceRange();
3422
3423 // Check the type of special register given.
3424 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3425 SmallVector<StringRef, 6> Fields;
3426 Reg.split(Fields, ":");
3427
3428 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
3429 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
3430 << Arg->getSourceRange();
3431
3432 // If the string is the name of a register then we cannot check that it is
3433 // valid here but if the string is of one the forms described in ACLE then we
3434 // can check that the supplied fields are integers and within the valid
3435 // ranges.
3436 if (Fields.size() > 1) {
3437 bool FiveFields = Fields.size() == 5;
3438
3439 bool ValidString = true;
3440 if (IsARMBuiltin) {
3441 ValidString &= Fields[0].startswith_lower("cp") ||
3442 Fields[0].startswith_lower("p");
3443 if (ValidString)
3444 Fields[0] =
3445 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
3446
3447 ValidString &= Fields[2].startswith_lower("c");
3448 if (ValidString)
3449 Fields[2] = Fields[2].drop_front(1);
3450
3451 if (FiveFields) {
3452 ValidString &= Fields[3].startswith_lower("c");
3453 if (ValidString)
3454 Fields[3] = Fields[3].drop_front(1);
3455 }
3456 }
3457
3458 SmallVector<int, 5> Ranges;
3459 if (FiveFields)
3460 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15});
3461 else
3462 Ranges.append({15, 7, 15});
3463
3464 for (unsigned i=0; i<Fields.size(); ++i) {
3465 int IntField;
3466 ValidString &= !Fields[i].getAsInteger(10, IntField);
3467 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
3468 }
3469
3470 if (!ValidString)
3471 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
3472 << Arg->getSourceRange();
3473
3474 } else if (IsAArch64Builtin && Fields.size() == 1) {
3475 // If the register name is one of those that appear in the condition below
3476 // and the special register builtin being used is one of the write builtins,
3477 // then we require that the argument provided for writing to the register
3478 // is an integer constant expression. This is because it will be lowered to
3479 // an MSR (immediate) instruction, so we need to know the immediate at
3480 // compile time.
3481 if (TheCall->getNumArgs() != 2)
3482 return false;
3483
3484 std::string RegLower = Reg.lower();
3485 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
3486 RegLower != "pan" && RegLower != "uao")
3487 return false;
3488
3489 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
3490 }
3491
3492 return false;
3493}
3494
Eli Friedmanc97d0142009-05-03 06:04:26 +00003495/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003496/// This checks that the target supports __builtin_longjmp and
3497/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003498bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003499 if (!Context.getTargetInfo().hasSjLjLowering())
3500 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
3501 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
3502
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003503 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00003504 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00003505
Eric Christopher8d0c6212010-04-17 02:26:23 +00003506 // TODO: This is less than ideal. Overload this to take a value.
3507 if (SemaBuiltinConstantArg(TheCall, 1, Result))
3508 return true;
3509
3510 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003511 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
3512 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
3513
3514 return false;
3515}
3516
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003517/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
3518/// This checks that the target supports __builtin_setjmp.
3519bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
3520 if (!Context.getTargetInfo().hasSjLjLowering())
3521 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
3522 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
3523 return false;
3524}
3525
Richard Smithd7293d72013-08-05 18:49:43 +00003526namespace {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003527class UncoveredArgHandler {
3528 enum { Unknown = -1, AllCovered = -2 };
3529 signed FirstUncoveredArg;
3530 SmallVector<const Expr *, 4> DiagnosticExprs;
3531
3532public:
3533 UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
3534
3535 bool hasUncoveredArg() const {
3536 return (FirstUncoveredArg >= 0);
3537 }
3538
3539 unsigned getUncoveredArg() const {
3540 assert(hasUncoveredArg() && "no uncovered argument");
3541 return FirstUncoveredArg;
3542 }
3543
3544 void setAllCovered() {
3545 // A string has been found with all arguments covered, so clear out
3546 // the diagnostics.
3547 DiagnosticExprs.clear();
3548 FirstUncoveredArg = AllCovered;
3549 }
3550
3551 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
3552 assert(NewFirstUncoveredArg >= 0 && "Outside range");
3553
3554 // Don't update if a previous string covers all arguments.
3555 if (FirstUncoveredArg == AllCovered)
3556 return;
3557
3558 // UncoveredArgHandler tracks the highest uncovered argument index
3559 // and with it all the strings that match this index.
3560 if (NewFirstUncoveredArg == FirstUncoveredArg)
3561 DiagnosticExprs.push_back(StrExpr);
3562 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
3563 DiagnosticExprs.clear();
3564 DiagnosticExprs.push_back(StrExpr);
3565 FirstUncoveredArg = NewFirstUncoveredArg;
3566 }
3567 }
3568
3569 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
3570};
3571
Richard Smithd7293d72013-08-05 18:49:43 +00003572enum StringLiteralCheckType {
3573 SLCT_NotALiteral,
3574 SLCT_UncheckedLiteral,
3575 SLCT_CheckedLiteral
3576};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003577} // end anonymous namespace
Richard Smithd7293d72013-08-05 18:49:43 +00003578
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00003579static void CheckFormatString(Sema &S, const StringLiteral *FExpr,
3580 const Expr *OrigFormatExpr,
3581 ArrayRef<const Expr *> Args,
3582 bool HasVAListArg, unsigned format_idx,
3583 unsigned firstDataArg,
3584 Sema::FormatStringType Type,
3585 bool inFunctionCall,
3586 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003587 llvm::SmallBitVector &CheckedVarArgs,
3588 UncoveredArgHandler &UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00003589
Richard Smith55ce3522012-06-25 20:30:08 +00003590// Determine if an expression is a string literal or constant string.
3591// If this function returns false on the arguments to a function expecting a
3592// format string, we will usually need to emit a warning.
3593// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00003594static StringLiteralCheckType
3595checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
3596 bool HasVAListArg, unsigned format_idx,
3597 unsigned firstDataArg, Sema::FormatStringType Type,
3598 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003599 llvm::SmallBitVector &CheckedVarArgs,
3600 UncoveredArgHandler &UncoveredArg) {
Ted Kremenek808829352010-09-09 03:51:39 +00003601 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00003602 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00003603 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003604
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003605 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00003606
Richard Smithd7293d72013-08-05 18:49:43 +00003607 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00003608 // Technically -Wformat-nonliteral does not warn about this case.
3609 // The behavior of printf and friends in this case is implementation
3610 // dependent. Ideally if the format string cannot be null then
3611 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00003612 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00003613
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003614 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00003615 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003616 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00003617 // The expression is a literal if both sub-expressions were, and it was
3618 // completely checked only if both sub-expressions were checked.
3619 const AbstractConditionalOperator *C =
3620 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003621
3622 // Determine whether it is necessary to check both sub-expressions, for
3623 // example, because the condition expression is a constant that can be
3624 // evaluated at compile time.
3625 bool CheckLeft = true, CheckRight = true;
3626
3627 bool Cond;
3628 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
3629 if (Cond)
3630 CheckRight = false;
3631 else
3632 CheckLeft = false;
3633 }
3634
3635 StringLiteralCheckType Left;
3636 if (!CheckLeft)
3637 Left = SLCT_UncheckedLiteral;
3638 else {
3639 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
3640 HasVAListArg, format_idx, firstDataArg,
3641 Type, CallType, InFunctionCall,
3642 CheckedVarArgs, UncoveredArg);
3643 if (Left == SLCT_NotALiteral || !CheckRight)
3644 return Left;
3645 }
3646
Richard Smith55ce3522012-06-25 20:30:08 +00003647 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00003648 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003649 HasVAListArg, format_idx, firstDataArg,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003650 Type, CallType, InFunctionCall, CheckedVarArgs,
3651 UncoveredArg);
3652
3653 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003654 }
3655
3656 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00003657 E = cast<ImplicitCastExpr>(E)->getSubExpr();
3658 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003659 }
3660
John McCallc07a0c72011-02-17 10:25:35 +00003661 case Stmt::OpaqueValueExprClass:
3662 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
3663 E = src;
3664 goto tryAgain;
3665 }
Richard Smith55ce3522012-06-25 20:30:08 +00003666 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00003667
Ted Kremeneka8890832011-02-24 23:03:04 +00003668 case Stmt::PredefinedExprClass:
3669 // While __func__, etc., are technically not string literals, they
3670 // cannot contain format specifiers and thus are not a security
3671 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00003672 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00003673
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003674 case Stmt::DeclRefExprClass: {
3675 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00003676
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003677 // As an exception, do not flag errors for variables binding to
3678 // const string literals.
3679 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
3680 bool isConstant = false;
3681 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003682
Richard Smithd7293d72013-08-05 18:49:43 +00003683 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
3684 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00003685 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00003686 isConstant = T.isConstant(S.Context) &&
3687 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00003688 } else if (T->isObjCObjectPointerType()) {
3689 // In ObjC, there is usually no "const ObjectPointer" type,
3690 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00003691 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003692 }
Mike Stump11289f42009-09-09 15:08:12 +00003693
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003694 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00003695 if (const Expr *Init = VD->getAnyInitializer()) {
3696 // Look through initializers like const char c[] = { "foo" }
3697 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3698 if (InitList->isStringLiteralInit())
3699 Init = InitList->getInit(0)->IgnoreParenImpCasts();
3700 }
Richard Smithd7293d72013-08-05 18:49:43 +00003701 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003702 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003703 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003704 /*InFunctionCall*/false, CheckedVarArgs,
3705 UncoveredArg);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00003706 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003707 }
Mike Stump11289f42009-09-09 15:08:12 +00003708
Anders Carlssonb012ca92009-06-28 19:55:58 +00003709 // For vprintf* functions (i.e., HasVAListArg==true), we add a
3710 // special check to see if the format string is a function parameter
3711 // of the function calling the printf function. If the function
3712 // has an attribute indicating it is a printf-like function, then we
3713 // should suppress warnings concerning non-literals being used in a call
3714 // to a vprintf function. For example:
3715 //
3716 // void
3717 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
3718 // va_list ap;
3719 // va_start(ap, fmt);
3720 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
3721 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00003722 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003723 if (HasVAListArg) {
3724 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
3725 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
3726 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003727 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003728 // adjust for implicit parameter
3729 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
3730 if (MD->isInstance())
3731 ++PVIndex;
3732 // We also check if the formats are compatible.
3733 // We can't pass a 'scanf' string to a 'printf' function.
3734 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00003735 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00003736 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003737 }
3738 }
3739 }
3740 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003741 }
Mike Stump11289f42009-09-09 15:08:12 +00003742
Richard Smith55ce3522012-06-25 20:30:08 +00003743 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003744 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003745
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00003746 case Stmt::CallExprClass:
3747 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003748 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00003749 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
3750 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
3751 unsigned ArgIndex = FA->getFormatIdx();
3752 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
3753 if (MD->isInstance())
3754 --ArgIndex;
3755 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00003756
Richard Smithd7293d72013-08-05 18:49:43 +00003757 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003758 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00003759 Type, CallType, InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003760 CheckedVarArgs, UncoveredArg);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003761 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3762 unsigned BuiltinID = FD->getBuiltinID();
3763 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
3764 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
3765 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00003766 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003767 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003768 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003769 InFunctionCall, CheckedVarArgs,
3770 UncoveredArg);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003771 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003772 }
3773 }
Mike Stump11289f42009-09-09 15:08:12 +00003774
Richard Smith55ce3522012-06-25 20:30:08 +00003775 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003776 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003777 case Stmt::ObjCStringLiteralClass:
3778 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00003779 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003780
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003781 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003782 StrE = ObjCFExpr->getString();
3783 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003784 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00003785
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003786 if (StrE) {
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00003787 CheckFormatString(S, StrE, E, Args, HasVAListArg, format_idx,
3788 firstDataArg, Type, InFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003789 CheckedVarArgs, UncoveredArg);
Richard Smith55ce3522012-06-25 20:30:08 +00003790 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003791 }
Mike Stump11289f42009-09-09 15:08:12 +00003792
Richard Smith55ce3522012-06-25 20:30:08 +00003793 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003794 }
Mike Stump11289f42009-09-09 15:08:12 +00003795
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003796 default:
Richard Smith55ce3522012-06-25 20:30:08 +00003797 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003798 }
3799}
3800
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003801Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00003802 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003803 .Case("scanf", FST_Scanf)
3804 .Cases("printf", "printf0", FST_Printf)
3805 .Cases("NSString", "CFString", FST_NSString)
3806 .Case("strftime", FST_Strftime)
3807 .Case("strfmon", FST_Strfmon)
3808 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
Dimitry Andric6b5ed342015-02-19 22:32:33 +00003809 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00003810 .Case("os_trace", FST_OSTrace)
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003811 .Default(FST_Unknown);
3812}
3813
Jordan Rose3e0ec582012-07-19 18:10:23 +00003814/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00003815/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00003816/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003817bool Sema::CheckFormatArguments(const FormatAttr *Format,
3818 ArrayRef<const Expr *> Args,
3819 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003820 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003821 SourceLocation Loc, SourceRange Range,
3822 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00003823 FormatStringInfo FSI;
3824 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003825 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00003826 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00003827 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003828 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003829}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00003830
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003831bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003832 bool HasVAListArg, unsigned format_idx,
3833 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003834 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003835 SourceLocation Loc, SourceRange Range,
3836 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00003837 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003838 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003839 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00003840 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003841 }
Mike Stump11289f42009-09-09 15:08:12 +00003842
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003843 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00003844
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003845 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00003846 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003847 // Dynamically generated format strings are difficult to
3848 // automatically vet at compile time. Requiring that format strings
3849 // are string literals: (1) permits the checking of format strings by
3850 // the compiler and thereby (2) can practically remove the source of
3851 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00003852
Mike Stump11289f42009-09-09 15:08:12 +00003853 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00003854 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00003855 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00003856 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003857 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00003858 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00003859 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
3860 format_idx, firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003861 /*IsFunctionCall*/true, CheckedVarArgs,
3862 UncoveredArg);
3863
3864 // Generate a diagnostic where an uncovered argument is detected.
3865 if (UncoveredArg.hasUncoveredArg()) {
3866 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
3867 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
3868 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
3869 }
3870
Richard Smith55ce3522012-06-25 20:30:08 +00003871 if (CT != SLCT_NotALiteral)
3872 // Literal format string found, check done!
3873 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00003874
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00003875 // Strftime is particular as it always uses a single 'time' argument,
3876 // so it is safe to pass a non-literal string.
3877 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00003878 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00003879
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00003880 // Do not emit diag when the string param is a macro expansion and the
3881 // format is either NSString or CFString. This is a hack to prevent
3882 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
3883 // which are usually used in place of NS and CF string literals.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00003884 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
3885 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
Richard Smith55ce3522012-06-25 20:30:08 +00003886 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00003887
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003888 // If there are no arguments specified, warn with -Wformat-security, otherwise
3889 // warn only with -Wformat-nonliteral.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00003890 if (Args.size() == firstDataArg) {
Bob Wilson57819fc2016-03-15 20:56:38 +00003891 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
3892 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00003893 switch (Type) {
3894 default:
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00003895 break;
3896 case FST_Kprintf:
3897 case FST_FreeBSDKPrintf:
3898 case FST_Printf:
Bob Wilson57819fc2016-03-15 20:56:38 +00003899 Diag(FormatLoc, diag::note_format_security_fixit)
3900 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00003901 break;
3902 case FST_NSString:
Bob Wilson57819fc2016-03-15 20:56:38 +00003903 Diag(FormatLoc, diag::note_format_security_fixit)
3904 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00003905 break;
3906 }
3907 } else {
3908 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003909 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00003910 }
Richard Smith55ce3522012-06-25 20:30:08 +00003911 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003912}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003913
Ted Kremenekab278de2010-01-28 23:39:18 +00003914namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00003915class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
3916protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00003917 Sema &S;
3918 const StringLiteral *FExpr;
3919 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00003920 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00003921 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00003922 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00003923 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003924 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00003925 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00003926 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00003927 bool usesPositionalArgs;
3928 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00003929 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00003930 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00003931 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003932 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003933
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003934public:
Ted Kremenek02087932010-07-16 02:11:22 +00003935 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00003936 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003937 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003938 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003939 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003940 Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003941 llvm::SmallBitVector &CheckedVarArgs,
3942 UncoveredArgHandler &UncoveredArg)
Ted Kremenekab278de2010-01-28 23:39:18 +00003943 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003944 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
3945 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003946 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00003947 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00003948 inFunctionCall(inFunctionCall), CallType(callType),
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003949 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00003950 CoveredArgs.resize(numDataArgs);
3951 CoveredArgs.reset();
3952 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003953
Ted Kremenek019d2242010-01-29 01:50:07 +00003954 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003955
Ted Kremenek02087932010-07-16 02:11:22 +00003956 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003957 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003958
Jordan Rose92303592012-09-08 04:00:03 +00003959 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003960 const analyze_format_string::FormatSpecifier &FS,
3961 const analyze_format_string::ConversionSpecifier &CS,
3962 const char *startSpecifier, unsigned specifierLen,
3963 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00003964
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003965 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003966 const analyze_format_string::FormatSpecifier &FS,
3967 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003968
3969 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003970 const analyze_format_string::ConversionSpecifier &CS,
3971 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003972
Craig Toppere14c0f82014-03-12 04:55:44 +00003973 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00003974
Craig Toppere14c0f82014-03-12 04:55:44 +00003975 void HandleInvalidPosition(const char *startSpecifier,
3976 unsigned specifierLen,
3977 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00003978
Craig Toppere14c0f82014-03-12 04:55:44 +00003979 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00003980
Craig Toppere14c0f82014-03-12 04:55:44 +00003981 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003982
Richard Trieu03cf7b72011-10-28 00:41:25 +00003983 template <typename Range>
Benjamin Kramer7320b992016-06-15 14:20:56 +00003984 static void
3985 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
3986 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
3987 bool IsStringLocation, Range StringRange,
3988 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003989
Ted Kremenek02087932010-07-16 02:11:22 +00003990protected:
Ted Kremenekce815422010-07-19 21:25:57 +00003991 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
3992 const char *startSpec,
3993 unsigned specifierLen,
3994 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003995
3996 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
3997 const char *startSpec,
3998 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00003999
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004000 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00004001 CharSourceRange getSpecifierRange(const char *startSpecifier,
4002 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00004003 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004004
Ted Kremenek5739de72010-01-29 01:06:55 +00004005 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004006
4007 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
4008 const analyze_format_string::ConversionSpecifier &CS,
4009 const char *startSpecifier, unsigned specifierLen,
4010 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00004011
4012 template <typename Range>
4013 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
4014 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00004015 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00004016};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004017} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00004018
Ted Kremenek02087932010-07-16 02:11:22 +00004019SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00004020 return OrigFormatExpr->getSourceRange();
4021}
4022
Ted Kremenek02087932010-07-16 02:11:22 +00004023CharSourceRange CheckFormatHandler::
4024getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00004025 SourceLocation Start = getLocationOfByte(startSpecifier);
4026 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
4027
4028 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00004029 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00004030
4031 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004032}
4033
Ted Kremenek02087932010-07-16 02:11:22 +00004034SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004035 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00004036}
4037
Ted Kremenek02087932010-07-16 02:11:22 +00004038void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
4039 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00004040 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
4041 getLocationOfByte(startSpecifier),
4042 /*IsStringLocation*/true,
4043 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00004044}
4045
Jordan Rose92303592012-09-08 04:00:03 +00004046void CheckFormatHandler::HandleInvalidLengthModifier(
4047 const analyze_format_string::FormatSpecifier &FS,
4048 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00004049 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00004050 using namespace analyze_format_string;
4051
4052 const LengthModifier &LM = FS.getLengthModifier();
4053 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4054
4055 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00004056 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00004057 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004058 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00004059 getLocationOfByte(LM.getStart()),
4060 /*IsStringLocation*/true,
4061 getSpecifierRange(startSpecifier, specifierLen));
4062
4063 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4064 << FixedLM->toString()
4065 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
4066
4067 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004068 FixItHint Hint;
4069 if (DiagID == diag::warn_format_nonsensical_length)
4070 Hint = FixItHint::CreateRemoval(LMRange);
4071
4072 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00004073 getLocationOfByte(LM.getStart()),
4074 /*IsStringLocation*/true,
4075 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00004076 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00004077 }
4078}
4079
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004080void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00004081 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004082 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004083 using namespace analyze_format_string;
4084
4085 const LengthModifier &LM = FS.getLengthModifier();
4086 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4087
4088 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00004089 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00004090 if (FixedLM) {
4091 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4092 << LM.toString() << 0,
4093 getLocationOfByte(LM.getStart()),
4094 /*IsStringLocation*/true,
4095 getSpecifierRange(startSpecifier, specifierLen));
4096
4097 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4098 << FixedLM->toString()
4099 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
4100
4101 } else {
4102 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4103 << LM.toString() << 0,
4104 getLocationOfByte(LM.getStart()),
4105 /*IsStringLocation*/true,
4106 getSpecifierRange(startSpecifier, specifierLen));
4107 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004108}
4109
4110void CheckFormatHandler::HandleNonStandardConversionSpecifier(
4111 const analyze_format_string::ConversionSpecifier &CS,
4112 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00004113 using namespace analyze_format_string;
4114
4115 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00004116 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00004117 if (FixedCS) {
4118 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4119 << CS.toString() << /*conversion specifier*/1,
4120 getLocationOfByte(CS.getStart()),
4121 /*IsStringLocation*/true,
4122 getSpecifierRange(startSpecifier, specifierLen));
4123
4124 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
4125 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
4126 << FixedCS->toString()
4127 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
4128 } else {
4129 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4130 << CS.toString() << /*conversion specifier*/1,
4131 getLocationOfByte(CS.getStart()),
4132 /*IsStringLocation*/true,
4133 getSpecifierRange(startSpecifier, specifierLen));
4134 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004135}
4136
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00004137void CheckFormatHandler::HandlePosition(const char *startPos,
4138 unsigned posLen) {
4139 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
4140 getLocationOfByte(startPos),
4141 /*IsStringLocation*/true,
4142 getSpecifierRange(startPos, posLen));
4143}
4144
Ted Kremenekd1668192010-02-27 01:41:03 +00004145void
Ted Kremenek02087932010-07-16 02:11:22 +00004146CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
4147 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004148 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
4149 << (unsigned) p,
4150 getLocationOfByte(startPos), /*IsStringLocation*/true,
4151 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00004152}
4153
Ted Kremenek02087932010-07-16 02:11:22 +00004154void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00004155 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004156 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
4157 getLocationOfByte(startPos),
4158 /*IsStringLocation*/true,
4159 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00004160}
4161
Ted Kremenek02087932010-07-16 02:11:22 +00004162void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004163 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00004164 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00004165 EmitFormatDiagnostic(
4166 S.PDiag(diag::warn_printf_format_string_contains_null_char),
4167 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
4168 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00004169 }
Ted Kremenek02087932010-07-16 02:11:22 +00004170}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004171
Jordan Rose58bbe422012-07-19 18:10:08 +00004172// Note that this may return NULL if there was an error parsing or building
4173// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00004174const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004175 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00004176}
4177
4178void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004179 // Does the number of data arguments exceed the number of
4180 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00004181 if (!HasVAListArg) {
4182 // Find any arguments that weren't covered.
4183 CoveredArgs.flip();
4184 signed notCoveredArg = CoveredArgs.find_first();
4185 if (notCoveredArg >= 0) {
4186 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004187 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
4188 } else {
4189 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00004190 }
4191 }
4192}
4193
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004194void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
4195 const Expr *ArgExpr) {
4196 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
4197 "Invalid state");
4198
4199 if (!ArgExpr)
4200 return;
4201
4202 SourceLocation Loc = ArgExpr->getLocStart();
4203
4204 if (S.getSourceManager().isInSystemMacro(Loc))
4205 return;
4206
4207 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
4208 for (auto E : DiagnosticExprs)
4209 PDiag << E->getSourceRange();
4210
4211 CheckFormatHandler::EmitFormatDiagnostic(
4212 S, IsFunctionCall, DiagnosticExprs[0],
4213 PDiag, Loc, /*IsStringLocation*/false,
4214 DiagnosticExprs[0]->getSourceRange());
4215}
4216
Ted Kremenekce815422010-07-19 21:25:57 +00004217bool
4218CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
4219 SourceLocation Loc,
4220 const char *startSpec,
4221 unsigned specifierLen,
4222 const char *csStart,
4223 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00004224 bool keepGoing = true;
4225 if (argIndex < NumDataArgs) {
4226 // Consider the argument coverered, even though the specifier doesn't
4227 // make sense.
4228 CoveredArgs.set(argIndex);
4229 }
4230 else {
4231 // If argIndex exceeds the number of data arguments we
4232 // don't issue a warning because that is just a cascade of warnings (and
4233 // they may have intended '%%' anyway). We don't want to continue processing
4234 // the format string after this point, however, as we will like just get
4235 // gibberish when trying to match arguments.
4236 keepGoing = false;
4237 }
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00004238
4239 StringRef Specifier(csStart, csLen);
4240
4241 // If the specifier in non-printable, it could be the first byte of a UTF-8
4242 // sequence. In that case, print the UTF-8 code point. If not, print the byte
4243 // hex value.
4244 std::string CodePointStr;
4245 if (!llvm::sys::locale::isPrint(*csStart)) {
4246 UTF32 CodePoint;
4247 const UTF8 **B = reinterpret_cast<const UTF8 **>(&csStart);
4248 const UTF8 *E =
4249 reinterpret_cast<const UTF8 *>(csStart + csLen);
4250 ConversionResult Result =
4251 llvm::convertUTF8Sequence(B, E, &CodePoint, strictConversion);
4252
4253 if (Result != conversionOK) {
4254 unsigned char FirstChar = *csStart;
4255 CodePoint = (UTF32)FirstChar;
4256 }
4257
4258 llvm::raw_string_ostream OS(CodePointStr);
4259 if (CodePoint < 256)
4260 OS << "\\x" << llvm::format("%02x", CodePoint);
4261 else if (CodePoint <= 0xFFFF)
4262 OS << "\\u" << llvm::format("%04x", CodePoint);
4263 else
4264 OS << "\\U" << llvm::format("%08x", CodePoint);
4265 OS.flush();
4266 Specifier = CodePointStr;
4267 }
4268
4269 EmitFormatDiagnostic(
4270 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
4271 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
4272
Ted Kremenekce815422010-07-19 21:25:57 +00004273 return keepGoing;
4274}
4275
Richard Trieu03cf7b72011-10-28 00:41:25 +00004276void
4277CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
4278 const char *startSpec,
4279 unsigned specifierLen) {
4280 EmitFormatDiagnostic(
4281 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
4282 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
4283}
4284
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004285bool
4286CheckFormatHandler::CheckNumArgs(
4287 const analyze_format_string::FormatSpecifier &FS,
4288 const analyze_format_string::ConversionSpecifier &CS,
4289 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
4290
4291 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004292 PartialDiagnostic PDiag = FS.usesPositionalArg()
4293 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
4294 << (argIndex+1) << NumDataArgs)
4295 : S.PDiag(diag::warn_printf_insufficient_data_args);
4296 EmitFormatDiagnostic(
4297 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
4298 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004299
4300 // Since more arguments than conversion tokens are given, by extension
4301 // all arguments are covered, so mark this as so.
4302 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004303 return false;
4304 }
4305 return true;
4306}
4307
Richard Trieu03cf7b72011-10-28 00:41:25 +00004308template<typename Range>
4309void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
4310 SourceLocation Loc,
4311 bool IsStringLocation,
4312 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00004313 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004314 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00004315 Loc, IsStringLocation, StringRange, FixIt);
4316}
4317
4318/// \brief If the format string is not within the funcion call, emit a note
4319/// so that the function call and string are in diagnostic messages.
4320///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00004321/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00004322/// call and only one diagnostic message will be produced. Otherwise, an
4323/// extra note will be emitted pointing to location of the format string.
4324///
4325/// \param ArgumentExpr the expression that is passed as the format string
4326/// argument in the function call. Used for getting locations when two
4327/// diagnostics are emitted.
4328///
4329/// \param PDiag the callee should already have provided any strings for the
4330/// diagnostic message. This function only adds locations and fixits
4331/// to diagnostics.
4332///
4333/// \param Loc primary location for diagnostic. If two diagnostics are
4334/// required, one will be at Loc and a new SourceLocation will be created for
4335/// the other one.
4336///
4337/// \param IsStringLocation if true, Loc points to the format string should be
4338/// used for the note. Otherwise, Loc points to the argument list and will
4339/// be used with PDiag.
4340///
4341/// \param StringRange some or all of the string to highlight. This is
4342/// templated so it can accept either a CharSourceRange or a SourceRange.
4343///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00004344/// \param FixIt optional fix it hint for the format string.
Benjamin Kramer7320b992016-06-15 14:20:56 +00004345template <typename Range>
4346void CheckFormatHandler::EmitFormatDiagnostic(
4347 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
4348 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
4349 Range StringRange, ArrayRef<FixItHint> FixIt) {
Jordan Roseaee34382012-09-05 22:56:26 +00004350 if (InFunctionCall) {
4351 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
4352 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00004353 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00004354 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004355 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
4356 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00004357
4358 const Sema::SemaDiagnosticBuilder &Note =
4359 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
4360 diag::note_format_string_defined);
4361
4362 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00004363 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00004364 }
4365}
4366
Ted Kremenek02087932010-07-16 02:11:22 +00004367//===--- CHECK: Printf format string checking ------------------------------===//
4368
4369namespace {
4370class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004371 bool ObjCContext;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004372
Ted Kremenek02087932010-07-16 02:11:22 +00004373public:
4374 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
4375 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004376 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00004377 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004378 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004379 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00004380 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004381 llvm::SmallBitVector &CheckedVarArgs,
4382 UncoveredArgHandler &UncoveredArg)
Richard Smithd7293d72013-08-05 18:49:43 +00004383 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
4384 numDataArgs, beg, hasVAListArg, Args,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004385 formatIdx, inFunctionCall, CallType, CheckedVarArgs,
4386 UncoveredArg),
Richard Smithd7293d72013-08-05 18:49:43 +00004387 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00004388 {}
4389
Ted Kremenek02087932010-07-16 02:11:22 +00004390 bool HandleInvalidPrintfConversionSpecifier(
4391 const analyze_printf::PrintfSpecifier &FS,
4392 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004393 unsigned specifierLen) override;
4394
Ted Kremenek02087932010-07-16 02:11:22 +00004395 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
4396 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004397 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00004398 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
4399 const char *StartSpecifier,
4400 unsigned SpecifierLen,
4401 const Expr *E);
4402
Ted Kremenek02087932010-07-16 02:11:22 +00004403 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
4404 const char *startSpecifier, unsigned specifierLen);
4405 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
4406 const analyze_printf::OptionalAmount &Amt,
4407 unsigned type,
4408 const char *startSpecifier, unsigned specifierLen);
4409 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
4410 const analyze_printf::OptionalFlag &flag,
4411 const char *startSpecifier, unsigned specifierLen);
4412 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
4413 const analyze_printf::OptionalFlag &ignoredFlag,
4414 const analyze_printf::OptionalFlag &flag,
4415 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004416 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00004417 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00004418
4419 void HandleEmptyObjCModifierFlag(const char *startFlag,
4420 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00004421
Ted Kremenek2b417712015-07-02 05:39:16 +00004422 void HandleInvalidObjCModifierFlag(const char *startFlag,
4423 unsigned flagLen) override;
4424
4425 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
4426 const char *flagsEnd,
4427 const char *conversionPosition)
4428 override;
4429};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004430} // end anonymous namespace
Ted Kremenek02087932010-07-16 02:11:22 +00004431
4432bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
4433 const analyze_printf::PrintfSpecifier &FS,
4434 const char *startSpecifier,
4435 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004436 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00004437 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00004438
Ted Kremenekce815422010-07-19 21:25:57 +00004439 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
4440 getLocationOfByte(CS.getStart()),
4441 startSpecifier, specifierLen,
4442 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00004443}
4444
Ted Kremenek02087932010-07-16 02:11:22 +00004445bool CheckPrintfHandler::HandleAmount(
4446 const analyze_format_string::OptionalAmount &Amt,
4447 unsigned k, const char *startSpecifier,
4448 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004449 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004450 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00004451 unsigned argIndex = Amt.getArgIndex();
4452 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004453 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
4454 << k,
4455 getLocationOfByte(Amt.getStart()),
4456 /*IsStringLocation*/true,
4457 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00004458 // Don't do any more checking. We will just emit
4459 // spurious errors.
4460 return false;
4461 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004462
Ted Kremenek5739de72010-01-29 01:06:55 +00004463 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00004464 // Although not in conformance with C99, we also allow the argument to be
4465 // an 'unsigned int' as that is a reasonably safe case. GCC also
4466 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00004467 CoveredArgs.set(argIndex);
4468 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00004469 if (!Arg)
4470 return false;
4471
Ted Kremenek5739de72010-01-29 01:06:55 +00004472 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004473
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004474 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
4475 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004476
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004477 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004478 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004479 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00004480 << T << Arg->getSourceRange(),
4481 getLocationOfByte(Amt.getStart()),
4482 /*IsStringLocation*/true,
4483 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00004484 // Don't do any more checking. We will just emit
4485 // spurious errors.
4486 return false;
4487 }
4488 }
4489 }
4490 return true;
4491}
Ted Kremenek5739de72010-01-29 01:06:55 +00004492
Tom Careb49ec692010-06-17 19:00:27 +00004493void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00004494 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004495 const analyze_printf::OptionalAmount &Amt,
4496 unsigned type,
4497 const char *startSpecifier,
4498 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004499 const analyze_printf::PrintfConversionSpecifier &CS =
4500 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00004501
Richard Trieu03cf7b72011-10-28 00:41:25 +00004502 FixItHint fixit =
4503 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
4504 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
4505 Amt.getConstantLength()))
4506 : FixItHint();
4507
4508 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
4509 << type << CS.toString(),
4510 getLocationOfByte(Amt.getStart()),
4511 /*IsStringLocation*/true,
4512 getSpecifierRange(startSpecifier, specifierLen),
4513 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00004514}
4515
Ted Kremenek02087932010-07-16 02:11:22 +00004516void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004517 const analyze_printf::OptionalFlag &flag,
4518 const char *startSpecifier,
4519 unsigned specifierLen) {
4520 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004521 const analyze_printf::PrintfConversionSpecifier &CS =
4522 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00004523 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
4524 << flag.toString() << CS.toString(),
4525 getLocationOfByte(flag.getPosition()),
4526 /*IsStringLocation*/true,
4527 getSpecifierRange(startSpecifier, specifierLen),
4528 FixItHint::CreateRemoval(
4529 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00004530}
4531
4532void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00004533 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004534 const analyze_printf::OptionalFlag &ignoredFlag,
4535 const analyze_printf::OptionalFlag &flag,
4536 const char *startSpecifier,
4537 unsigned specifierLen) {
4538 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00004539 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
4540 << ignoredFlag.toString() << flag.toString(),
4541 getLocationOfByte(ignoredFlag.getPosition()),
4542 /*IsStringLocation*/true,
4543 getSpecifierRange(startSpecifier, specifierLen),
4544 FixItHint::CreateRemoval(
4545 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00004546}
4547
Ted Kremenek2b417712015-07-02 05:39:16 +00004548// void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
4549// bool IsStringLocation, Range StringRange,
4550// ArrayRef<FixItHint> Fixit = None);
4551
4552void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
4553 unsigned flagLen) {
4554 // Warn about an empty flag.
4555 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
4556 getLocationOfByte(startFlag),
4557 /*IsStringLocation*/true,
4558 getSpecifierRange(startFlag, flagLen));
4559}
4560
4561void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
4562 unsigned flagLen) {
4563 // Warn about an invalid flag.
4564 auto Range = getSpecifierRange(startFlag, flagLen);
4565 StringRef flag(startFlag, flagLen);
4566 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
4567 getLocationOfByte(startFlag),
4568 /*IsStringLocation*/true,
4569 Range, FixItHint::CreateRemoval(Range));
4570}
4571
4572void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
4573 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
4574 // Warn about using '[...]' without a '@' conversion.
4575 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
4576 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
4577 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
4578 getLocationOfByte(conversionPosition),
4579 /*IsStringLocation*/true,
4580 Range, FixItHint::CreateRemoval(Range));
4581}
4582
Richard Smith55ce3522012-06-25 20:30:08 +00004583// Determines if the specified is a C++ class or struct containing
4584// a member with the specified name and kind (e.g. a CXXMethodDecl named
4585// "c_str()").
4586template<typename MemberKind>
4587static llvm::SmallPtrSet<MemberKind*, 1>
4588CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
4589 const RecordType *RT = Ty->getAs<RecordType>();
4590 llvm::SmallPtrSet<MemberKind*, 1> Results;
4591
4592 if (!RT)
4593 return Results;
4594 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00004595 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00004596 return Results;
4597
Alp Tokerb6cc5922014-05-03 03:45:55 +00004598 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00004599 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00004600 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00004601
4602 // We just need to include all members of the right kind turned up by the
4603 // filter, at this point.
4604 if (S.LookupQualifiedName(R, RT->getDecl()))
4605 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
4606 NamedDecl *decl = (*I)->getUnderlyingDecl();
4607 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
4608 Results.insert(FK);
4609 }
4610 return Results;
4611}
4612
Richard Smith2868a732014-02-28 01:36:39 +00004613/// Check if we could call '.c_str()' on an object.
4614///
4615/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
4616/// allow the call, or if it would be ambiguous).
4617bool Sema::hasCStrMethod(const Expr *E) {
4618 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
4619 MethodSet Results =
4620 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
4621 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
4622 MI != ME; ++MI)
4623 if ((*MI)->getMinRequiredArguments() == 0)
4624 return true;
4625 return false;
4626}
4627
Richard Smith55ce3522012-06-25 20:30:08 +00004628// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004629// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00004630// Returns true when a c_str() conversion method is found.
4631bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00004632 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00004633 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
4634
4635 MethodSet Results =
4636 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
4637
4638 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
4639 MI != ME; ++MI) {
4640 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00004641 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00004642 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00004643 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00004644 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00004645 S.Diag(E->getLocStart(), diag::note_printf_c_str)
4646 << "c_str()"
4647 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
4648 return true;
4649 }
4650 }
4651
4652 return false;
4653}
4654
Ted Kremenekab278de2010-01-28 23:39:18 +00004655bool
Ted Kremenek02087932010-07-16 02:11:22 +00004656CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00004657 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00004658 const char *startSpecifier,
4659 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004660 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00004661 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004662 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00004663
Ted Kremenek6cd69422010-07-19 22:01:06 +00004664 if (FS.consumesDataArgument()) {
4665 if (atFirstArg) {
4666 atFirstArg = false;
4667 usesPositionalArgs = FS.usesPositionalArg();
4668 }
4669 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004670 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
4671 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00004672 return false;
4673 }
Ted Kremenek5739de72010-01-29 01:06:55 +00004674 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004675
Ted Kremenekd1668192010-02-27 01:41:03 +00004676 // First check if the field width, precision, and conversion specifier
4677 // have matching data arguments.
4678 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
4679 startSpecifier, specifierLen)) {
4680 return false;
4681 }
4682
4683 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
4684 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004685 return false;
4686 }
4687
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004688 if (!CS.consumesDataArgument()) {
4689 // FIXME: Technically specifying a precision or field width here
4690 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00004691 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004692 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004693
Ted Kremenek4a49d982010-02-26 19:18:41 +00004694 // Consume the argument.
4695 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00004696 if (argIndex < NumDataArgs) {
4697 // The check to see if the argIndex is valid will come later.
4698 // We set the bit here because we may exit early from this
4699 // function if we encounter some other error.
4700 CoveredArgs.set(argIndex);
4701 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00004702
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004703 // FreeBSD kernel extensions.
4704 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
4705 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
4706 // We need at least two arguments.
4707 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
4708 return false;
4709
4710 // Claim the second argument.
4711 CoveredArgs.set(argIndex + 1);
4712
4713 // Type check the first argument (int for %b, pointer for %D)
4714 const Expr *Ex = getDataArg(argIndex);
4715 const analyze_printf::ArgType &AT =
4716 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
4717 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
4718 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
4719 EmitFormatDiagnostic(
4720 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4721 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
4722 << false << Ex->getSourceRange(),
4723 Ex->getLocStart(), /*IsStringLocation*/false,
4724 getSpecifierRange(startSpecifier, specifierLen));
4725
4726 // Type check the second argument (char * for both %b and %D)
4727 Ex = getDataArg(argIndex + 1);
4728 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
4729 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
4730 EmitFormatDiagnostic(
4731 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4732 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
4733 << false << Ex->getSourceRange(),
4734 Ex->getLocStart(), /*IsStringLocation*/false,
4735 getSpecifierRange(startSpecifier, specifierLen));
4736
4737 return true;
4738 }
4739
Ted Kremenek4a49d982010-02-26 19:18:41 +00004740 // Check for using an Objective-C specific conversion specifier
4741 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004742 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00004743 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
4744 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00004745 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004746
Tom Careb49ec692010-06-17 19:00:27 +00004747 // Check for invalid use of field width
4748 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00004749 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00004750 startSpecifier, specifierLen);
4751 }
4752
4753 // Check for invalid use of precision
4754 if (!FS.hasValidPrecision()) {
4755 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
4756 startSpecifier, specifierLen);
4757 }
4758
4759 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00004760 if (!FS.hasValidThousandsGroupingPrefix())
4761 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004762 if (!FS.hasValidLeadingZeros())
4763 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
4764 if (!FS.hasValidPlusPrefix())
4765 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00004766 if (!FS.hasValidSpacePrefix())
4767 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004768 if (!FS.hasValidAlternativeForm())
4769 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
4770 if (!FS.hasValidLeftJustified())
4771 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
4772
4773 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00004774 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
4775 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
4776 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004777 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
4778 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
4779 startSpecifier, specifierLen);
4780
4781 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00004782 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00004783 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4784 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00004785 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004786 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00004787 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004788 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4789 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00004790
Jordan Rose92303592012-09-08 04:00:03 +00004791 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4792 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4793
Ted Kremenek9fcd8302010-01-29 01:43:31 +00004794 // The remaining checks depend on the data arguments.
4795 if (HasVAListArg)
4796 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004797
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004798 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00004799 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004800
Jordan Rose58bbe422012-07-19 18:10:08 +00004801 const Expr *Arg = getDataArg(argIndex);
4802 if (!Arg)
4803 return true;
4804
4805 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00004806}
4807
Jordan Roseaee34382012-09-05 22:56:26 +00004808static bool requiresParensToAddCast(const Expr *E) {
4809 // FIXME: We should have a general way to reason about operator
4810 // precedence and whether parens are actually needed here.
4811 // Take care of a few common cases where they aren't.
4812 const Expr *Inside = E->IgnoreImpCasts();
4813 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
4814 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
4815
4816 switch (Inside->getStmtClass()) {
4817 case Stmt::ArraySubscriptExprClass:
4818 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004819 case Stmt::CharacterLiteralClass:
4820 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004821 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004822 case Stmt::FloatingLiteralClass:
4823 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004824 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004825 case Stmt::ObjCArrayLiteralClass:
4826 case Stmt::ObjCBoolLiteralExprClass:
4827 case Stmt::ObjCBoxedExprClass:
4828 case Stmt::ObjCDictionaryLiteralClass:
4829 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004830 case Stmt::ObjCIvarRefExprClass:
4831 case Stmt::ObjCMessageExprClass:
4832 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004833 case Stmt::ObjCStringLiteralClass:
4834 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004835 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004836 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004837 case Stmt::UnaryOperatorClass:
4838 return false;
4839 default:
4840 return true;
4841 }
4842}
4843
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004844static std::pair<QualType, StringRef>
4845shouldNotPrintDirectly(const ASTContext &Context,
4846 QualType IntendedTy,
4847 const Expr *E) {
4848 // Use a 'while' to peel off layers of typedefs.
4849 QualType TyTy = IntendedTy;
4850 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
4851 StringRef Name = UserTy->getDecl()->getName();
4852 QualType CastTy = llvm::StringSwitch<QualType>(Name)
4853 .Case("NSInteger", Context.LongTy)
4854 .Case("NSUInteger", Context.UnsignedLongTy)
4855 .Case("SInt32", Context.IntTy)
4856 .Case("UInt32", Context.UnsignedIntTy)
4857 .Default(QualType());
4858
4859 if (!CastTy.isNull())
4860 return std::make_pair(CastTy, Name);
4861
4862 TyTy = UserTy->desugar();
4863 }
4864
4865 // Strip parens if necessary.
4866 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
4867 return shouldNotPrintDirectly(Context,
4868 PE->getSubExpr()->getType(),
4869 PE->getSubExpr());
4870
4871 // If this is a conditional expression, then its result type is constructed
4872 // via usual arithmetic conversions and thus there might be no necessary
4873 // typedef sugar there. Recurse to operands to check for NSInteger &
4874 // Co. usage condition.
4875 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4876 QualType TrueTy, FalseTy;
4877 StringRef TrueName, FalseName;
4878
4879 std::tie(TrueTy, TrueName) =
4880 shouldNotPrintDirectly(Context,
4881 CO->getTrueExpr()->getType(),
4882 CO->getTrueExpr());
4883 std::tie(FalseTy, FalseName) =
4884 shouldNotPrintDirectly(Context,
4885 CO->getFalseExpr()->getType(),
4886 CO->getFalseExpr());
4887
4888 if (TrueTy == FalseTy)
4889 return std::make_pair(TrueTy, TrueName);
4890 else if (TrueTy.isNull())
4891 return std::make_pair(FalseTy, FalseName);
4892 else if (FalseTy.isNull())
4893 return std::make_pair(TrueTy, TrueName);
4894 }
4895
4896 return std::make_pair(QualType(), StringRef());
4897}
4898
Richard Smith55ce3522012-06-25 20:30:08 +00004899bool
4900CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
4901 const char *StartSpecifier,
4902 unsigned SpecifierLen,
4903 const Expr *E) {
4904 using namespace analyze_format_string;
4905 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004906 // Now type check the data expression that matches the
4907 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004908 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
4909 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00004910 if (!AT.isValid())
4911 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00004912
Jordan Rose598ec092012-12-05 18:44:40 +00004913 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00004914 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
4915 ExprTy = TET->getUnderlyingExpr()->getType();
4916 }
4917
Seth Cantrellb4802962015-03-04 03:12:10 +00004918 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
4919
4920 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00004921 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00004922 }
Jordan Rose98709982012-06-04 22:48:57 +00004923
Jordan Rose22b74712012-09-05 22:56:19 +00004924 // Look through argument promotions for our error message's reported type.
4925 // This includes the integral and floating promotions, but excludes array
4926 // and function pointer decay; seeing that an argument intended to be a
4927 // string has type 'char [6]' is probably more confusing than 'char *'.
4928 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
4929 if (ICE->getCastKind() == CK_IntegralCast ||
4930 ICE->getCastKind() == CK_FloatingCast) {
4931 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00004932 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00004933
4934 // Check if we didn't match because of an implicit cast from a 'char'
4935 // or 'short' to an 'int'. This is done because printf is a varargs
4936 // function.
4937 if (ICE->getType() == S.Context.IntTy ||
4938 ICE->getType() == S.Context.UnsignedIntTy) {
4939 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00004940 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00004941 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00004942 }
Jordan Rose98709982012-06-04 22:48:57 +00004943 }
Jordan Rose598ec092012-12-05 18:44:40 +00004944 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
4945 // Special case for 'a', which has type 'int' in C.
4946 // Note, however, that we do /not/ want to treat multibyte constants like
4947 // 'MooV' as characters! This form is deprecated but still exists.
4948 if (ExprTy == S.Context.IntTy)
4949 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
4950 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00004951 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004952
Jordan Rosebc53ed12014-05-31 04:12:14 +00004953 // Look through enums to their underlying type.
4954 bool IsEnum = false;
4955 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
4956 ExprTy = EnumTy->getDecl()->getIntegerType();
4957 IsEnum = true;
4958 }
4959
Jordan Rose0e5badd2012-12-05 18:44:49 +00004960 // %C in an Objective-C context prints a unichar, not a wchar_t.
4961 // If the argument is an integer of some kind, believe the %C and suggest
4962 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00004963 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00004964 if (ObjCContext &&
4965 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
4966 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
4967 !ExprTy->isCharType()) {
4968 // 'unichar' is defined as a typedef of unsigned short, but we should
4969 // prefer using the typedef if it is visible.
4970 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00004971
4972 // While we are here, check if the value is an IntegerLiteral that happens
4973 // to be within the valid range.
4974 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
4975 const llvm::APInt &V = IL->getValue();
4976 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
4977 return true;
4978 }
4979
Jordan Rose0e5badd2012-12-05 18:44:49 +00004980 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
4981 Sema::LookupOrdinaryName);
4982 if (S.LookupName(Result, S.getCurScope())) {
4983 NamedDecl *ND = Result.getFoundDecl();
4984 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
4985 if (TD->getUnderlyingType() == IntendedTy)
4986 IntendedTy = S.Context.getTypedefType(TD);
4987 }
4988 }
4989 }
4990
4991 // Special-case some of Darwin's platform-independence types by suggesting
4992 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004993 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00004994 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004995 QualType CastTy;
4996 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
4997 if (!CastTy.isNull()) {
4998 IntendedTy = CastTy;
4999 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00005000 }
5001 }
5002
Jordan Rose22b74712012-09-05 22:56:19 +00005003 // We may be able to offer a FixItHint if it is a supported type.
5004 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00005005 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00005006 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005007
Jordan Rose22b74712012-09-05 22:56:19 +00005008 if (success) {
5009 // Get the fix string from the fixed format specifier
5010 SmallString<16> buf;
5011 llvm::raw_svector_ostream os(buf);
5012 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005013
Jordan Roseaee34382012-09-05 22:56:26 +00005014 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
5015
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005016 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00005017 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5018 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
5019 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5020 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00005021 // In this case, the specifier is wrong and should be changed to match
5022 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00005023 EmitFormatDiagnostic(S.PDiag(diag)
5024 << AT.getRepresentativeTypeName(S.Context)
5025 << IntendedTy << IsEnum << E->getSourceRange(),
5026 E->getLocStart(),
5027 /*IsStringLocation*/ false, SpecRange,
5028 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00005029 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00005030 // The canonical type for formatting this value is different from the
5031 // actual type of the expression. (This occurs, for example, with Darwin's
5032 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
5033 // should be printed as 'long' for 64-bit compatibility.)
5034 // Rather than emitting a normal format/argument mismatch, we want to
5035 // add a cast to the recommended type (and correct the format string
5036 // if necessary).
5037 SmallString<16> CastBuf;
5038 llvm::raw_svector_ostream CastFix(CastBuf);
5039 CastFix << "(";
5040 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
5041 CastFix << ")";
5042
5043 SmallVector<FixItHint,4> Hints;
5044 if (!AT.matchesType(S.Context, IntendedTy))
5045 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
5046
5047 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
5048 // If there's already a cast present, just replace it.
5049 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
5050 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
5051
5052 } else if (!requiresParensToAddCast(E)) {
5053 // If the expression has high enough precedence,
5054 // just write the C-style cast.
5055 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
5056 CastFix.str()));
5057 } else {
5058 // Otherwise, add parens around the expression as well as the cast.
5059 CastFix << "(";
5060 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
5061 CastFix.str()));
5062
Alp Tokerb6cc5922014-05-03 03:45:55 +00005063 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00005064 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
5065 }
5066
Jordan Rose0e5badd2012-12-05 18:44:49 +00005067 if (ShouldNotPrintDirectly) {
5068 // The expression has a type that should not be printed directly.
5069 // We extract the name from the typedef because we don't want to show
5070 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005071 StringRef Name;
5072 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
5073 Name = TypedefTy->getDecl()->getName();
5074 else
5075 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00005076 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00005077 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00005078 << E->getSourceRange(),
5079 E->getLocStart(), /*IsStringLocation=*/false,
5080 SpecRange, Hints);
5081 } else {
5082 // In this case, the expression could be printed using a different
5083 // specifier, but we've decided that the specifier is probably correct
5084 // and we should cast instead. Just use the normal warning message.
5085 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00005086 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5087 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00005088 << E->getSourceRange(),
5089 E->getLocStart(), /*IsStringLocation*/false,
5090 SpecRange, Hints);
5091 }
Jordan Roseaee34382012-09-05 22:56:26 +00005092 }
Jordan Rose22b74712012-09-05 22:56:19 +00005093 } else {
5094 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
5095 SpecifierLen);
5096 // Since the warning for passing non-POD types to variadic functions
5097 // was deferred until now, we emit a warning for non-POD
5098 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00005099 switch (S.isValidVarArgType(ExprTy)) {
5100 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00005101 case Sema::VAK_ValidInCXX11: {
5102 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5103 if (match == analyze_printf::ArgType::NoMatchPedantic) {
5104 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5105 }
Richard Smithd7293d72013-08-05 18:49:43 +00005106
Seth Cantrellb4802962015-03-04 03:12:10 +00005107 EmitFormatDiagnostic(
5108 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
5109 << IsEnum << CSR << E->getSourceRange(),
5110 E->getLocStart(), /*IsStringLocation*/ false, CSR);
5111 break;
5112 }
Richard Smithd7293d72013-08-05 18:49:43 +00005113 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00005114 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00005115 EmitFormatDiagnostic(
5116 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005117 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00005118 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00005119 << CallType
5120 << AT.getRepresentativeTypeName(S.Context)
5121 << CSR
5122 << E->getSourceRange(),
5123 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00005124 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00005125 break;
5126
5127 case Sema::VAK_Invalid:
5128 if (ExprTy->isObjCObjectType())
5129 EmitFormatDiagnostic(
5130 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
5131 << S.getLangOpts().CPlusPlus11
5132 << ExprTy
5133 << CallType
5134 << AT.getRepresentativeTypeName(S.Context)
5135 << CSR
5136 << E->getSourceRange(),
5137 E->getLocStart(), /*IsStringLocation*/false, CSR);
5138 else
5139 // FIXME: If this is an initializer list, suggest removing the braces
5140 // or inserting a cast to the target type.
5141 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
5142 << isa<InitListExpr>(E) << ExprTy << CallType
5143 << AT.getRepresentativeTypeName(S.Context)
5144 << E->getSourceRange();
5145 break;
5146 }
5147
5148 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
5149 "format string specifier index out of range");
5150 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005151 }
5152
Ted Kremenekab278de2010-01-28 23:39:18 +00005153 return true;
5154}
5155
Ted Kremenek02087932010-07-16 02:11:22 +00005156//===--- CHECK: Scanf format string checking ------------------------------===//
5157
5158namespace {
5159class CheckScanfHandler : public CheckFormatHandler {
5160public:
5161 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
5162 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005163 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005164 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005165 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00005166 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005167 llvm::SmallBitVector &CheckedVarArgs,
5168 UncoveredArgHandler &UncoveredArg)
Richard Smithd7293d72013-08-05 18:49:43 +00005169 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
5170 numDataArgs, beg, hasVAListArg,
5171 Args, formatIdx, inFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005172 CheckedVarArgs, UncoveredArg)
Jordan Rose3e0ec582012-07-19 18:10:23 +00005173 {}
Ted Kremenek02087932010-07-16 02:11:22 +00005174
5175 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
5176 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005177 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00005178
5179 bool HandleInvalidScanfConversionSpecifier(
5180 const analyze_scanf::ScanfSpecifier &FS,
5181 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005182 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00005183
Craig Toppere14c0f82014-03-12 04:55:44 +00005184 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00005185};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005186} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00005187
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00005188void CheckScanfHandler::HandleIncompleteScanList(const char *start,
5189 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005190 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
5191 getLocationOfByte(end), /*IsStringLocation*/true,
5192 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00005193}
5194
Ted Kremenekce815422010-07-19 21:25:57 +00005195bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
5196 const analyze_scanf::ScanfSpecifier &FS,
5197 const char *startSpecifier,
5198 unsigned specifierLen) {
5199
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005200 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00005201 FS.getConversionSpecifier();
5202
5203 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5204 getLocationOfByte(CS.getStart()),
5205 startSpecifier, specifierLen,
5206 CS.getStart(), CS.getLength());
5207}
5208
Ted Kremenek02087932010-07-16 02:11:22 +00005209bool CheckScanfHandler::HandleScanfSpecifier(
5210 const analyze_scanf::ScanfSpecifier &FS,
5211 const char *startSpecifier,
5212 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00005213 using namespace analyze_scanf;
5214 using namespace analyze_format_string;
5215
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005216 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00005217
Ted Kremenek6cd69422010-07-19 22:01:06 +00005218 // Handle case where '%' and '*' don't consume an argument. These shouldn't
5219 // be used to decide if we are using positional arguments consistently.
5220 if (FS.consumesDataArgument()) {
5221 if (atFirstArg) {
5222 atFirstArg = false;
5223 usesPositionalArgs = FS.usesPositionalArg();
5224 }
5225 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005226 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5227 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00005228 return false;
5229 }
Ted Kremenek02087932010-07-16 02:11:22 +00005230 }
5231
5232 // Check if the field with is non-zero.
5233 const OptionalAmount &Amt = FS.getFieldWidth();
5234 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
5235 if (Amt.getConstantAmount() == 0) {
5236 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
5237 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00005238 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
5239 getLocationOfByte(Amt.getStart()),
5240 /*IsStringLocation*/true, R,
5241 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00005242 }
5243 }
Seth Cantrellb4802962015-03-04 03:12:10 +00005244
Ted Kremenek02087932010-07-16 02:11:22 +00005245 if (!FS.consumesDataArgument()) {
5246 // FIXME: Technically specifying a precision or field width here
5247 // makes no sense. Worth issuing a warning at some point.
5248 return true;
5249 }
Seth Cantrellb4802962015-03-04 03:12:10 +00005250
Ted Kremenek02087932010-07-16 02:11:22 +00005251 // Consume the argument.
5252 unsigned argIndex = FS.getArgIndex();
5253 if (argIndex < NumDataArgs) {
5254 // The check to see if the argIndex is valid will come later.
5255 // We set the bit here because we may exit early from this
5256 // function if we encounter some other error.
5257 CoveredArgs.set(argIndex);
5258 }
Seth Cantrellb4802962015-03-04 03:12:10 +00005259
Ted Kremenek4407ea42010-07-20 20:04:47 +00005260 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00005261 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00005262 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5263 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00005264 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005265 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00005266 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005267 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5268 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005269
Jordan Rose92303592012-09-08 04:00:03 +00005270 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
5271 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5272
Ted Kremenek02087932010-07-16 02:11:22 +00005273 // The remaining checks depend on the data arguments.
5274 if (HasVAListArg)
5275 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00005276
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005277 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00005278 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00005279
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005280 // Check that the argument type matches the format specifier.
5281 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00005282 if (!Ex)
5283 return true;
5284
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00005285 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00005286
5287 if (!AT.isValid()) {
5288 return true;
5289 }
5290
Seth Cantrellb4802962015-03-04 03:12:10 +00005291 analyze_format_string::ArgType::MatchKind match =
5292 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00005293 if (match == analyze_format_string::ArgType::Match) {
5294 return true;
5295 }
Seth Cantrellb4802962015-03-04 03:12:10 +00005296
Seth Cantrell79340072015-03-04 05:58:08 +00005297 ScanfSpecifier fixedFS = FS;
5298 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
5299 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005300
Seth Cantrell79340072015-03-04 05:58:08 +00005301 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5302 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
5303 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5304 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005305
Seth Cantrell79340072015-03-04 05:58:08 +00005306 if (success) {
5307 // Get the fix string from the fixed format specifier.
5308 SmallString<128> buf;
5309 llvm::raw_svector_ostream os(buf);
5310 fixedFS.toString(os);
5311
5312 EmitFormatDiagnostic(
5313 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
5314 << Ex->getType() << false << Ex->getSourceRange(),
5315 Ex->getLocStart(),
5316 /*IsStringLocation*/ false,
5317 getSpecifierRange(startSpecifier, specifierLen),
5318 FixItHint::CreateReplacement(
5319 getSpecifierRange(startSpecifier, specifierLen), os.str()));
5320 } else {
5321 EmitFormatDiagnostic(S.PDiag(diag)
5322 << AT.getRepresentativeTypeName(S.Context)
5323 << Ex->getType() << false << Ex->getSourceRange(),
5324 Ex->getLocStart(),
5325 /*IsStringLocation*/ false,
5326 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005327 }
5328
Ted Kremenek02087932010-07-16 02:11:22 +00005329 return true;
5330}
5331
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005332static void CheckFormatString(Sema &S, const StringLiteral *FExpr,
5333 const Expr *OrigFormatExpr,
5334 ArrayRef<const Expr *> Args,
5335 bool HasVAListArg, unsigned format_idx,
5336 unsigned firstDataArg,
5337 Sema::FormatStringType Type,
5338 bool inFunctionCall,
5339 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005340 llvm::SmallBitVector &CheckedVarArgs,
5341 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00005342 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00005343 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005344 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005345 S, inFunctionCall, Args[format_idx],
5346 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00005347 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00005348 return;
5349 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005350
Ted Kremenekab278de2010-01-28 23:39:18 +00005351 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005352 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00005353 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005354 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005355 const ConstantArrayType *T =
5356 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005357 assert(T && "String literal not of constant array type!");
5358 size_t TypeSize = T->getSize().getZExtValue();
5359 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005360 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005361
5362 // Emit a warning if the string literal is truncated and does not contain an
5363 // embedded null character.
5364 if (TypeSize <= StrRef.size() &&
5365 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
5366 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005367 S, inFunctionCall, Args[format_idx],
5368 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005369 FExpr->getLocStart(),
5370 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
5371 return;
5372 }
5373
Ted Kremenekab278de2010-01-28 23:39:18 +00005374 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00005375 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005376 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005377 S, inFunctionCall, Args[format_idx],
5378 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00005379 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00005380 return;
5381 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005382
5383 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
5384 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSTrace) {
5385 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, firstDataArg,
5386 numDataArgs, (Type == Sema::FST_NSString ||
5387 Type == Sema::FST_OSTrace),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005388 Str, HasVAListArg, Args, format_idx,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005389 inFunctionCall, CallType, CheckedVarArgs,
5390 UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005391
Hans Wennborg23926bd2011-12-15 10:25:47 +00005392 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005393 S.getLangOpts(),
5394 S.Context.getTargetInfo(),
5395 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00005396 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005397 } else if (Type == Sema::FST_Scanf) {
5398 CheckScanfHandler H(S, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005399 Str, HasVAListArg, Args, format_idx,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005400 inFunctionCall, CallType, CheckedVarArgs,
5401 UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005402
Hans Wennborg23926bd2011-12-15 10:25:47 +00005403 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005404 S.getLangOpts(),
5405 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00005406 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005407 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00005408}
5409
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00005410bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
5411 // Str - The format string. NOTE: this is NOT null-terminated!
5412 StringRef StrRef = FExpr->getString();
5413 const char *Str = StrRef.data();
5414 // Account for cases where the string literal is truncated in a declaration.
5415 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
5416 assert(T && "String literal not of constant array type!");
5417 size_t TypeSize = T->getSize().getZExtValue();
5418 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
5419 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
5420 getLangOpts(),
5421 Context.getTargetInfo());
5422}
5423
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005424//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
5425
5426// Returns the related absolute value function that is larger, of 0 if one
5427// does not exist.
5428static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
5429 switch (AbsFunction) {
5430 default:
5431 return 0;
5432
5433 case Builtin::BI__builtin_abs:
5434 return Builtin::BI__builtin_labs;
5435 case Builtin::BI__builtin_labs:
5436 return Builtin::BI__builtin_llabs;
5437 case Builtin::BI__builtin_llabs:
5438 return 0;
5439
5440 case Builtin::BI__builtin_fabsf:
5441 return Builtin::BI__builtin_fabs;
5442 case Builtin::BI__builtin_fabs:
5443 return Builtin::BI__builtin_fabsl;
5444 case Builtin::BI__builtin_fabsl:
5445 return 0;
5446
5447 case Builtin::BI__builtin_cabsf:
5448 return Builtin::BI__builtin_cabs;
5449 case Builtin::BI__builtin_cabs:
5450 return Builtin::BI__builtin_cabsl;
5451 case Builtin::BI__builtin_cabsl:
5452 return 0;
5453
5454 case Builtin::BIabs:
5455 return Builtin::BIlabs;
5456 case Builtin::BIlabs:
5457 return Builtin::BIllabs;
5458 case Builtin::BIllabs:
5459 return 0;
5460
5461 case Builtin::BIfabsf:
5462 return Builtin::BIfabs;
5463 case Builtin::BIfabs:
5464 return Builtin::BIfabsl;
5465 case Builtin::BIfabsl:
5466 return 0;
5467
5468 case Builtin::BIcabsf:
5469 return Builtin::BIcabs;
5470 case Builtin::BIcabs:
5471 return Builtin::BIcabsl;
5472 case Builtin::BIcabsl:
5473 return 0;
5474 }
5475}
5476
5477// Returns the argument type of the absolute value function.
5478static QualType getAbsoluteValueArgumentType(ASTContext &Context,
5479 unsigned AbsType) {
5480 if (AbsType == 0)
5481 return QualType();
5482
5483 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
5484 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
5485 if (Error != ASTContext::GE_None)
5486 return QualType();
5487
5488 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
5489 if (!FT)
5490 return QualType();
5491
5492 if (FT->getNumParams() != 1)
5493 return QualType();
5494
5495 return FT->getParamType(0);
5496}
5497
5498// Returns the best absolute value function, or zero, based on type and
5499// current absolute value function.
5500static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
5501 unsigned AbsFunctionKind) {
5502 unsigned BestKind = 0;
5503 uint64_t ArgSize = Context.getTypeSize(ArgType);
5504 for (unsigned Kind = AbsFunctionKind; Kind != 0;
5505 Kind = getLargerAbsoluteValueFunction(Kind)) {
5506 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
5507 if (Context.getTypeSize(ParamType) >= ArgSize) {
5508 if (BestKind == 0)
5509 BestKind = Kind;
5510 else if (Context.hasSameType(ParamType, ArgType)) {
5511 BestKind = Kind;
5512 break;
5513 }
5514 }
5515 }
5516 return BestKind;
5517}
5518
5519enum AbsoluteValueKind {
5520 AVK_Integer,
5521 AVK_Floating,
5522 AVK_Complex
5523};
5524
5525static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
5526 if (T->isIntegralOrEnumerationType())
5527 return AVK_Integer;
5528 if (T->isRealFloatingType())
5529 return AVK_Floating;
5530 if (T->isAnyComplexType())
5531 return AVK_Complex;
5532
5533 llvm_unreachable("Type not integer, floating, or complex");
5534}
5535
5536// Changes the absolute value function to a different type. Preserves whether
5537// the function is a builtin.
5538static unsigned changeAbsFunction(unsigned AbsKind,
5539 AbsoluteValueKind ValueKind) {
5540 switch (ValueKind) {
5541 case AVK_Integer:
5542 switch (AbsKind) {
5543 default:
5544 return 0;
5545 case Builtin::BI__builtin_fabsf:
5546 case Builtin::BI__builtin_fabs:
5547 case Builtin::BI__builtin_fabsl:
5548 case Builtin::BI__builtin_cabsf:
5549 case Builtin::BI__builtin_cabs:
5550 case Builtin::BI__builtin_cabsl:
5551 return Builtin::BI__builtin_abs;
5552 case Builtin::BIfabsf:
5553 case Builtin::BIfabs:
5554 case Builtin::BIfabsl:
5555 case Builtin::BIcabsf:
5556 case Builtin::BIcabs:
5557 case Builtin::BIcabsl:
5558 return Builtin::BIabs;
5559 }
5560 case AVK_Floating:
5561 switch (AbsKind) {
5562 default:
5563 return 0;
5564 case Builtin::BI__builtin_abs:
5565 case Builtin::BI__builtin_labs:
5566 case Builtin::BI__builtin_llabs:
5567 case Builtin::BI__builtin_cabsf:
5568 case Builtin::BI__builtin_cabs:
5569 case Builtin::BI__builtin_cabsl:
5570 return Builtin::BI__builtin_fabsf;
5571 case Builtin::BIabs:
5572 case Builtin::BIlabs:
5573 case Builtin::BIllabs:
5574 case Builtin::BIcabsf:
5575 case Builtin::BIcabs:
5576 case Builtin::BIcabsl:
5577 return Builtin::BIfabsf;
5578 }
5579 case AVK_Complex:
5580 switch (AbsKind) {
5581 default:
5582 return 0;
5583 case Builtin::BI__builtin_abs:
5584 case Builtin::BI__builtin_labs:
5585 case Builtin::BI__builtin_llabs:
5586 case Builtin::BI__builtin_fabsf:
5587 case Builtin::BI__builtin_fabs:
5588 case Builtin::BI__builtin_fabsl:
5589 return Builtin::BI__builtin_cabsf;
5590 case Builtin::BIabs:
5591 case Builtin::BIlabs:
5592 case Builtin::BIllabs:
5593 case Builtin::BIfabsf:
5594 case Builtin::BIfabs:
5595 case Builtin::BIfabsl:
5596 return Builtin::BIcabsf;
5597 }
5598 }
5599 llvm_unreachable("Unable to convert function");
5600}
5601
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00005602static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005603 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
5604 if (!FnInfo)
5605 return 0;
5606
5607 switch (FDecl->getBuiltinID()) {
5608 default:
5609 return 0;
5610 case Builtin::BI__builtin_abs:
5611 case Builtin::BI__builtin_fabs:
5612 case Builtin::BI__builtin_fabsf:
5613 case Builtin::BI__builtin_fabsl:
5614 case Builtin::BI__builtin_labs:
5615 case Builtin::BI__builtin_llabs:
5616 case Builtin::BI__builtin_cabs:
5617 case Builtin::BI__builtin_cabsf:
5618 case Builtin::BI__builtin_cabsl:
5619 case Builtin::BIabs:
5620 case Builtin::BIlabs:
5621 case Builtin::BIllabs:
5622 case Builtin::BIfabs:
5623 case Builtin::BIfabsf:
5624 case Builtin::BIfabsl:
5625 case Builtin::BIcabs:
5626 case Builtin::BIcabsf:
5627 case Builtin::BIcabsl:
5628 return FDecl->getBuiltinID();
5629 }
5630 llvm_unreachable("Unknown Builtin type");
5631}
5632
5633// If the replacement is valid, emit a note with replacement function.
5634// Additionally, suggest including the proper header if not already included.
5635static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00005636 unsigned AbsKind, QualType ArgType) {
5637 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00005638 const char *HeaderName = nullptr;
5639 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00005640 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
5641 FunctionName = "std::abs";
5642 if (ArgType->isIntegralOrEnumerationType()) {
5643 HeaderName = "cstdlib";
5644 } else if (ArgType->isRealFloatingType()) {
5645 HeaderName = "cmath";
5646 } else {
5647 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005648 }
Richard Trieubeffb832014-04-15 23:47:53 +00005649
5650 // Lookup all std::abs
5651 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00005652 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00005653 R.suppressDiagnostics();
5654 S.LookupQualifiedName(R, Std);
5655
5656 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005657 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00005658 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
5659 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
5660 } else {
5661 FDecl = dyn_cast<FunctionDecl>(I);
5662 }
5663 if (!FDecl)
5664 continue;
5665
5666 // Found std::abs(), check that they are the right ones.
5667 if (FDecl->getNumParams() != 1)
5668 continue;
5669
5670 // Check that the parameter type can handle the argument.
5671 QualType ParamType = FDecl->getParamDecl(0)->getType();
5672 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
5673 S.Context.getTypeSize(ArgType) <=
5674 S.Context.getTypeSize(ParamType)) {
5675 // Found a function, don't need the header hint.
5676 EmitHeaderHint = false;
5677 break;
5678 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005679 }
Richard Trieubeffb832014-04-15 23:47:53 +00005680 }
5681 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00005682 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00005683 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
5684
5685 if (HeaderName) {
5686 DeclarationName DN(&S.Context.Idents.get(FunctionName));
5687 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
5688 R.suppressDiagnostics();
5689 S.LookupName(R, S.getCurScope());
5690
5691 if (R.isSingleResult()) {
5692 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
5693 if (FD && FD->getBuiltinID() == AbsKind) {
5694 EmitHeaderHint = false;
5695 } else {
5696 return;
5697 }
5698 } else if (!R.empty()) {
5699 return;
5700 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005701 }
5702 }
5703
5704 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00005705 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005706
Richard Trieubeffb832014-04-15 23:47:53 +00005707 if (!HeaderName)
5708 return;
5709
5710 if (!EmitHeaderHint)
5711 return;
5712
Alp Toker5d96e0a2014-07-11 20:53:51 +00005713 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
5714 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00005715}
5716
5717static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
5718 if (!FDecl)
5719 return false;
5720
5721 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
5722 return false;
5723
5724 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
5725
5726 while (ND && ND->isInlineNamespace()) {
5727 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005728 }
Richard Trieubeffb832014-04-15 23:47:53 +00005729
5730 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
5731 return false;
5732
5733 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
5734 return false;
5735
5736 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005737}
5738
5739// Warn when using the wrong abs() function.
5740void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
5741 const FunctionDecl *FDecl,
5742 IdentifierInfo *FnInfo) {
5743 if (Call->getNumArgs() != 1)
5744 return;
5745
5746 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00005747 bool IsStdAbs = IsFunctionStdAbs(FDecl);
5748 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005749 return;
5750
5751 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
5752 QualType ParamType = Call->getArg(0)->getType();
5753
Alp Toker5d96e0a2014-07-11 20:53:51 +00005754 // Unsigned types cannot be negative. Suggest removing the absolute value
5755 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005756 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00005757 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00005758 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005759 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
5760 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00005761 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005762 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
5763 return;
5764 }
5765
David Majnemer7f77eb92015-11-15 03:04:34 +00005766 // Taking the absolute value of a pointer is very suspicious, they probably
5767 // wanted to index into an array, dereference a pointer, call a function, etc.
5768 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
5769 unsigned DiagType = 0;
5770 if (ArgType->isFunctionType())
5771 DiagType = 1;
5772 else if (ArgType->isArrayType())
5773 DiagType = 2;
5774
5775 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
5776 return;
5777 }
5778
Richard Trieubeffb832014-04-15 23:47:53 +00005779 // std::abs has overloads which prevent most of the absolute value problems
5780 // from occurring.
5781 if (IsStdAbs)
5782 return;
5783
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005784 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
5785 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
5786
5787 // The argument and parameter are the same kind. Check if they are the right
5788 // size.
5789 if (ArgValueKind == ParamValueKind) {
5790 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
5791 return;
5792
5793 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
5794 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
5795 << FDecl << ArgType << ParamType;
5796
5797 if (NewAbsKind == 0)
5798 return;
5799
5800 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00005801 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005802 return;
5803 }
5804
5805 // ArgValueKind != ParamValueKind
5806 // The wrong type of absolute value function was used. Attempt to find the
5807 // proper one.
5808 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
5809 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
5810 if (NewAbsKind == 0)
5811 return;
5812
5813 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
5814 << FDecl << ParamValueKind << ArgValueKind;
5815
5816 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00005817 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005818}
5819
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005820//===--- CHECK: Standard memory functions ---------------------------------===//
5821
Nico Weber0e6daef2013-12-26 23:38:39 +00005822/// \brief Takes the expression passed to the size_t parameter of functions
5823/// such as memcmp, strncat, etc and warns if it's a comparison.
5824///
5825/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
5826static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
5827 IdentifierInfo *FnName,
5828 SourceLocation FnLoc,
5829 SourceLocation RParenLoc) {
5830 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
5831 if (!Size)
5832 return false;
5833
5834 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
5835 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
5836 return false;
5837
Nico Weber0e6daef2013-12-26 23:38:39 +00005838 SourceRange SizeRange = Size->getSourceRange();
5839 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
5840 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00005841 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00005842 << FnName << FixItHint::CreateInsertion(
5843 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00005844 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00005845 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00005846 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00005847 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
5848 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00005849
5850 return true;
5851}
5852
Reid Kleckner5fb5b122014-06-27 23:58:21 +00005853/// \brief Determine whether the given type is or contains a dynamic class type
5854/// (e.g., whether it has a vtable).
5855static const CXXRecordDecl *getContainedDynamicClass(QualType T,
5856 bool &IsContained) {
5857 // Look through array types while ignoring qualifiers.
5858 const Type *Ty = T->getBaseElementTypeUnsafe();
5859 IsContained = false;
5860
5861 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
5862 RD = RD ? RD->getDefinition() : nullptr;
Richard Trieu1c7237a2016-03-31 04:18:07 +00005863 if (!RD || RD->isInvalidDecl())
Reid Kleckner5fb5b122014-06-27 23:58:21 +00005864 return nullptr;
5865
5866 if (RD->isDynamicClass())
5867 return RD;
5868
5869 // Check all the fields. If any bases were dynamic, the class is dynamic.
5870 // It's impossible for a class to transitively contain itself by value, so
5871 // infinite recursion is impossible.
5872 for (auto *FD : RD->fields()) {
5873 bool SubContained;
5874 if (const CXXRecordDecl *ContainedRD =
5875 getContainedDynamicClass(FD->getType(), SubContained)) {
5876 IsContained = true;
5877 return ContainedRD;
5878 }
5879 }
5880
5881 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00005882}
5883
Chandler Carruth889ed862011-06-21 23:04:20 +00005884/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005885/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00005886static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00005887 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005888 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
5889 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
5890 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00005891
Craig Topperc3ec1492014-05-26 06:22:03 +00005892 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005893}
5894
Chandler Carruth889ed862011-06-21 23:04:20 +00005895/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00005896static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005897 if (const UnaryExprOrTypeTraitExpr *SizeOf =
5898 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
5899 if (SizeOf->getKind() == clang::UETT_SizeOf)
5900 return SizeOf->getTypeOfArgument();
5901
5902 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00005903}
5904
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005905/// \brief Check for dangerous or invalid arguments to memset().
5906///
Chandler Carruthac687262011-06-03 06:23:57 +00005907/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005908/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
5909/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005910///
5911/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005912void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00005913 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005914 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00005915 assert(BId != 0);
5916
Ted Kremenekb5fabb22011-04-28 01:38:02 +00005917 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00005918 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00005919 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00005920 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00005921 return;
5922
Anna Zaks22122702012-01-17 00:37:07 +00005923 unsigned LastArg = (BId == Builtin::BImemset ||
5924 BId == Builtin::BIstrndup ? 1 : 2);
5925 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00005926 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005927
Nico Weber0e6daef2013-12-26 23:38:39 +00005928 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
5929 Call->getLocStart(), Call->getRParenLoc()))
5930 return;
5931
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005932 // We have special checking when the length is a sizeof expression.
5933 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
5934 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
5935 llvm::FoldingSetNodeID SizeOfArgID;
5936
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005937 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
5938 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00005939 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005940
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005941 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00005942 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005943 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00005944 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00005945
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005946 // Never warn about void type pointers. This can be used to suppress
5947 // false positives.
5948 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005949 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005950
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005951 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
5952 // actually comparing the expressions for equality. Because computing the
5953 // expression IDs can be expensive, we only do this if the diagnostic is
5954 // enabled.
5955 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00005956 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
5957 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005958 // We only compute IDs for expressions if the warning is enabled, and
5959 // cache the sizeof arg's ID.
5960 if (SizeOfArgID == llvm::FoldingSetNodeID())
5961 SizeOfArg->Profile(SizeOfArgID, Context, true);
5962 llvm::FoldingSetNodeID DestID;
5963 Dest->Profile(DestID, Context, true);
5964 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00005965 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
5966 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005967 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00005968 StringRef ReadableName = FnName->getName();
5969
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005970 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00005971 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005972 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00005973 if (!PointeeTy->isIncompleteType() &&
5974 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005975 ActionIdx = 2; // If the pointee's size is sizeof(char),
5976 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00005977
5978 // If the function is defined as a builtin macro, do not show macro
5979 // expansion.
5980 SourceLocation SL = SizeOfArg->getExprLoc();
5981 SourceRange DSR = Dest->getSourceRange();
5982 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00005983 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00005984
5985 if (SM.isMacroArgExpansion(SL)) {
5986 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
5987 SL = SM.getSpellingLoc(SL);
5988 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
5989 SM.getSpellingLoc(DSR.getEnd()));
5990 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
5991 SM.getSpellingLoc(SSR.getEnd()));
5992 }
5993
Anna Zaksd08d9152012-05-30 23:14:52 +00005994 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005995 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00005996 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00005997 << PointeeTy
5998 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00005999 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00006000 << SSR);
6001 DiagRuntimeBehavior(SL, SizeOfArg,
6002 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
6003 << ActionIdx
6004 << SSR);
6005
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006006 break;
6007 }
6008 }
6009
6010 // Also check for cases where the sizeof argument is the exact same
6011 // type as the memory argument, and where it points to a user-defined
6012 // record type.
6013 if (SizeOfArgTy != QualType()) {
6014 if (PointeeTy->isRecordType() &&
6015 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
6016 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
6017 PDiag(diag::warn_sizeof_pointer_type_memaccess)
6018 << FnName << SizeOfArgTy << ArgIdx
6019 << PointeeTy << Dest->getSourceRange()
6020 << LenExpr->getSourceRange());
6021 break;
6022 }
Nico Weberc5e73862011-06-14 16:14:58 +00006023 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00006024 } else if (DestTy->isArrayType()) {
6025 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00006026 }
Nico Weberc5e73862011-06-14 16:14:58 +00006027
Nico Weberc44b35e2015-03-21 17:37:46 +00006028 if (PointeeTy == QualType())
6029 continue;
Anna Zaks22122702012-01-17 00:37:07 +00006030
Nico Weberc44b35e2015-03-21 17:37:46 +00006031 // Always complain about dynamic classes.
6032 bool IsContained;
6033 if (const CXXRecordDecl *ContainedRD =
6034 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00006035
Nico Weberc44b35e2015-03-21 17:37:46 +00006036 unsigned OperationType = 0;
6037 // "overwritten" if we're warning about the destination for any call
6038 // but memcmp; otherwise a verb appropriate to the call.
6039 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
6040 if (BId == Builtin::BImemcpy)
6041 OperationType = 1;
6042 else if(BId == Builtin::BImemmove)
6043 OperationType = 2;
6044 else if (BId == Builtin::BImemcmp)
6045 OperationType = 3;
6046 }
6047
John McCall31168b02011-06-15 23:02:42 +00006048 DiagRuntimeBehavior(
6049 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00006050 PDiag(diag::warn_dyn_class_memaccess)
6051 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
6052 << FnName << IsContained << ContainedRD << OperationType
6053 << Call->getCallee()->getSourceRange());
6054 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
6055 BId != Builtin::BImemset)
6056 DiagRuntimeBehavior(
6057 Dest->getExprLoc(), Dest,
6058 PDiag(diag::warn_arc_object_memaccess)
6059 << ArgIdx << FnName << PointeeTy
6060 << Call->getCallee()->getSourceRange());
6061 else
6062 continue;
6063
6064 DiagRuntimeBehavior(
6065 Dest->getExprLoc(), Dest,
6066 PDiag(diag::note_bad_memaccess_silence)
6067 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
6068 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006069 }
6070}
6071
Ted Kremenek6865f772011-08-18 20:55:45 +00006072// A little helper routine: ignore addition and subtraction of integer literals.
6073// This intentionally does not ignore all integer constant expressions because
6074// we don't want to remove sizeof().
6075static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
6076 Ex = Ex->IgnoreParenCasts();
6077
6078 for (;;) {
6079 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
6080 if (!BO || !BO->isAdditiveOp())
6081 break;
6082
6083 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
6084 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
6085
6086 if (isa<IntegerLiteral>(RHS))
6087 Ex = LHS;
6088 else if (isa<IntegerLiteral>(LHS))
6089 Ex = RHS;
6090 else
6091 break;
6092 }
6093
6094 return Ex;
6095}
6096
Anna Zaks13b08572012-08-08 21:42:23 +00006097static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
6098 ASTContext &Context) {
6099 // Only handle constant-sized or VLAs, but not flexible members.
6100 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
6101 // Only issue the FIXIT for arrays of size > 1.
6102 if (CAT->getSize().getSExtValue() <= 1)
6103 return false;
6104 } else if (!Ty->isVariableArrayType()) {
6105 return false;
6106 }
6107 return true;
6108}
6109
Ted Kremenek6865f772011-08-18 20:55:45 +00006110// Warn if the user has made the 'size' argument to strlcpy or strlcat
6111// be the size of the source, instead of the destination.
6112void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
6113 IdentifierInfo *FnName) {
6114
6115 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00006116 unsigned NumArgs = Call->getNumArgs();
6117 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00006118 return;
6119
6120 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
6121 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00006122 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00006123
6124 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
6125 Call->getLocStart(), Call->getRParenLoc()))
6126 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00006127
6128 // Look for 'strlcpy(dst, x, sizeof(x))'
6129 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
6130 CompareWithSrc = Ex;
6131 else {
6132 // Look for 'strlcpy(dst, x, strlen(x))'
6133 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00006134 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
6135 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00006136 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
6137 }
6138 }
6139
6140 if (!CompareWithSrc)
6141 return;
6142
6143 // Determine if the argument to sizeof/strlen is equal to the source
6144 // argument. In principle there's all kinds of things you could do
6145 // here, for instance creating an == expression and evaluating it with
6146 // EvaluateAsBooleanCondition, but this uses a more direct technique:
6147 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
6148 if (!SrcArgDRE)
6149 return;
6150
6151 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
6152 if (!CompareWithSrcDRE ||
6153 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
6154 return;
6155
6156 const Expr *OriginalSizeArg = Call->getArg(2);
6157 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
6158 << OriginalSizeArg->getSourceRange() << FnName;
6159
6160 // Output a FIXIT hint if the destination is an array (rather than a
6161 // pointer to an array). This could be enhanced to handle some
6162 // pointers if we know the actual size, like if DstArg is 'array+2'
6163 // we could say 'sizeof(array)-2'.
6164 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00006165 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00006166 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00006167
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00006168 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00006169 llvm::raw_svector_ostream OS(sizeString);
6170 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00006171 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00006172 OS << ")";
6173
6174 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
6175 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
6176 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00006177}
6178
Anna Zaks314cd092012-02-01 19:08:57 +00006179/// Check if two expressions refer to the same declaration.
6180static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
6181 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
6182 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
6183 return D1->getDecl() == D2->getDecl();
6184 return false;
6185}
6186
6187static const Expr *getStrlenExprArg(const Expr *E) {
6188 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6189 const FunctionDecl *FD = CE->getDirectCallee();
6190 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00006191 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00006192 return CE->getArg(0)->IgnoreParenCasts();
6193 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006194 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00006195}
6196
6197// Warn on anti-patterns as the 'size' argument to strncat.
6198// The correct size argument should look like following:
6199// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
6200void Sema::CheckStrncatArguments(const CallExpr *CE,
6201 IdentifierInfo *FnName) {
6202 // Don't crash if the user has the wrong number of arguments.
6203 if (CE->getNumArgs() < 3)
6204 return;
6205 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
6206 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
6207 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
6208
Nico Weber0e6daef2013-12-26 23:38:39 +00006209 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
6210 CE->getRParenLoc()))
6211 return;
6212
Anna Zaks314cd092012-02-01 19:08:57 +00006213 // Identify common expressions, which are wrongly used as the size argument
6214 // to strncat and may lead to buffer overflows.
6215 unsigned PatternType = 0;
6216 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
6217 // - sizeof(dst)
6218 if (referToTheSameDecl(SizeOfArg, DstArg))
6219 PatternType = 1;
6220 // - sizeof(src)
6221 else if (referToTheSameDecl(SizeOfArg, SrcArg))
6222 PatternType = 2;
6223 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
6224 if (BE->getOpcode() == BO_Sub) {
6225 const Expr *L = BE->getLHS()->IgnoreParenCasts();
6226 const Expr *R = BE->getRHS()->IgnoreParenCasts();
6227 // - sizeof(dst) - strlen(dst)
6228 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
6229 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
6230 PatternType = 1;
6231 // - sizeof(src) - (anything)
6232 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
6233 PatternType = 2;
6234 }
6235 }
6236
6237 if (PatternType == 0)
6238 return;
6239
Anna Zaks5069aa32012-02-03 01:27:37 +00006240 // Generate the diagnostic.
6241 SourceLocation SL = LenArg->getLocStart();
6242 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00006243 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00006244
6245 // If the function is defined as a builtin macro, do not show macro expansion.
6246 if (SM.isMacroArgExpansion(SL)) {
6247 SL = SM.getSpellingLoc(SL);
6248 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
6249 SM.getSpellingLoc(SR.getEnd()));
6250 }
6251
Anna Zaks13b08572012-08-08 21:42:23 +00006252 // Check if the destination is an array (rather than a pointer to an array).
6253 QualType DstTy = DstArg->getType();
6254 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
6255 Context);
6256 if (!isKnownSizeArray) {
6257 if (PatternType == 1)
6258 Diag(SL, diag::warn_strncat_wrong_size) << SR;
6259 else
6260 Diag(SL, diag::warn_strncat_src_size) << SR;
6261 return;
6262 }
6263
Anna Zaks314cd092012-02-01 19:08:57 +00006264 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00006265 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00006266 else
Anna Zaks5069aa32012-02-03 01:27:37 +00006267 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00006268
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00006269 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00006270 llvm::raw_svector_ostream OS(sizeString);
6271 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00006272 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00006273 OS << ") - ";
6274 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00006275 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00006276 OS << ") - 1";
6277
Anna Zaks5069aa32012-02-03 01:27:37 +00006278 Diag(SL, diag::note_strncat_wrong_size)
6279 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00006280}
6281
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006282//===--- CHECK: Return Address of Stack Variable --------------------------===//
6283
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006284static const Expr *EvalVal(const Expr *E,
6285 SmallVectorImpl<const DeclRefExpr *> &refVars,
6286 const Decl *ParentDecl);
6287static const Expr *EvalAddr(const Expr *E,
6288 SmallVectorImpl<const DeclRefExpr *> &refVars,
6289 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006290
6291/// CheckReturnStackAddr - Check if a return statement returns the address
6292/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006293static void
6294CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
6295 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00006296
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006297 const Expr *stackE = nullptr;
6298 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006299
6300 // Perform checking for returned stack addresses, local blocks,
6301 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00006302 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006303 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006304 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00006305 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006306 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006307 }
6308
Craig Topperc3ec1492014-05-26 06:22:03 +00006309 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006310 return; // Nothing suspicious was found.
6311
6312 SourceLocation diagLoc;
6313 SourceRange diagRange;
6314 if (refVars.empty()) {
6315 diagLoc = stackE->getLocStart();
6316 diagRange = stackE->getSourceRange();
6317 } else {
6318 // We followed through a reference variable. 'stackE' contains the
6319 // problematic expression but we will warn at the return statement pointing
6320 // at the reference variable. We will later display the "trail" of
6321 // reference variables using notes.
6322 diagLoc = refVars[0]->getLocStart();
6323 diagRange = refVars[0]->getSourceRange();
6324 }
6325
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006326 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
6327 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00006328 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006329 << DR->getDecl()->getDeclName() << diagRange;
6330 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006331 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006332 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006333 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006334 } else { // local temporary.
Craig Topperda7b27f2015-11-17 05:40:09 +00006335 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
6336 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006337 }
6338
6339 // Display the "trail" of reference variables that we followed until we
6340 // found the problematic expression using notes.
6341 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006342 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006343 // If this var binds to another reference var, show the range of the next
6344 // var, otherwise the var binds to the problematic expression, in which case
6345 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006346 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
6347 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006348 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
6349 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006350 }
6351}
6352
6353/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
6354/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006355/// to a location on the stack, a local block, an address of a label, or a
6356/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006357/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006358/// encounter a subexpression that (1) clearly does not lead to one of the
6359/// above problematic expressions (2) is something we cannot determine leads to
6360/// a problematic expression based on such local checking.
6361///
6362/// Both EvalAddr and EvalVal follow through reference variables to evaluate
6363/// the expression that they point to. Such variables are added to the
6364/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006365///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00006366/// EvalAddr processes expressions that are pointers that are used as
6367/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006368/// At the base case of the recursion is a check for the above problematic
6369/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006370///
6371/// This implementation handles:
6372///
6373/// * pointer-to-pointer casts
6374/// * implicit conversions from array references to pointers
6375/// * taking the address of fields
6376/// * arbitrary interplay between "&" and "*" operators
6377/// * pointer arithmetic from an address of a stack variable
6378/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006379static const Expr *EvalAddr(const Expr *E,
6380 SmallVectorImpl<const DeclRefExpr *> &refVars,
6381 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006382 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00006383 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006384
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006385 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00006386 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00006387 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006388 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00006389 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00006390
Peter Collingbourne91147592011-04-15 00:35:48 +00006391 E = E->IgnoreParens();
6392
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006393 // Our "symbolic interpreter" is just a dispatch off the currently
6394 // viewed AST node. We then recursively traverse the AST by calling
6395 // EvalAddr and EvalVal appropriately.
6396 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006397 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006398 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006399
Richard Smith40f08eb2014-01-30 22:05:38 +00006400 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00006401 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00006402 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00006403
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006404 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006405 // If this is a reference variable, follow through to the expression that
6406 // it points to.
6407 if (V->hasLocalStorage() &&
6408 V->getType()->isReferenceType() && V->hasInit()) {
6409 // Add the reference variable to the "trail".
6410 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006411 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006412 }
6413
Craig Topperc3ec1492014-05-26 06:22:03 +00006414 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006415 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006416
Chris Lattner934edb22007-12-28 05:31:15 +00006417 case Stmt::UnaryOperatorClass: {
6418 // The only unary operator that make sense to handle here
6419 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006420 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006421
John McCalle3027922010-08-25 11:45:40 +00006422 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006423 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006424 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006425 }
Mike Stump11289f42009-09-09 15:08:12 +00006426
Chris Lattner934edb22007-12-28 05:31:15 +00006427 case Stmt::BinaryOperatorClass: {
6428 // Handle pointer arithmetic. All other binary operators are not valid
6429 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006430 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00006431 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00006432
John McCalle3027922010-08-25 11:45:40 +00006433 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00006434 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006435
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006436 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00006437
6438 // Determine which argument is the real pointer base. It could be
6439 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006440 if (!Base->getType()->isPointerType())
6441 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00006442
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006443 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006444 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00006445 }
Steve Naroff2752a172008-09-10 19:17:48 +00006446
Chris Lattner934edb22007-12-28 05:31:15 +00006447 // For conditional operators we need to see if either the LHS or RHS are
6448 // valid DeclRefExpr*s. If one of them is valid, we return it.
6449 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006450 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006451
Chris Lattner934edb22007-12-28 05:31:15 +00006452 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006453 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006454 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006455 // In C++, we can have a throw-expression, which has 'void' type.
6456 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006457 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006458 return LHS;
6459 }
Chris Lattner934edb22007-12-28 05:31:15 +00006460
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006461 // In C++, we can have a throw-expression, which has 'void' type.
6462 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00006463 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006464
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006465 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00006466 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006467
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006468 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00006469 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006470 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00006471 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006472
6473 case Stmt::AddrLabelExprClass:
6474 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00006475
John McCall28fc7092011-11-10 05:35:25 +00006476 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006477 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
6478 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00006479
Ted Kremenekc3b4c522008-08-07 00:49:01 +00006480 // For casts, we need to handle conversions from arrays to
6481 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00006482 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00006483 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00006484 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00006485 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00006486 case Stmt::CXXStaticCastExprClass:
6487 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00006488 case Stmt::CXXConstCastExprClass:
6489 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006490 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00006491 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00006492 case CK_LValueToRValue:
6493 case CK_NoOp:
6494 case CK_BaseToDerived:
6495 case CK_DerivedToBase:
6496 case CK_UncheckedDerivedToBase:
6497 case CK_Dynamic:
6498 case CK_CPointerToObjCPointerCast:
6499 case CK_BlockPointerToObjCPointerCast:
6500 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006501 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00006502
6503 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006504 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00006505
Richard Trieudadefde2014-07-02 04:39:38 +00006506 case CK_BitCast:
6507 if (SubExpr->getType()->isAnyPointerType() ||
6508 SubExpr->getType()->isBlockPointerType() ||
6509 SubExpr->getType()->isObjCQualifiedIdType())
6510 return EvalAddr(SubExpr, refVars, ParentDecl);
6511 else
6512 return nullptr;
6513
Eli Friedman8195ad72012-02-23 23:04:32 +00006514 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00006515 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00006516 }
Chris Lattner934edb22007-12-28 05:31:15 +00006517 }
Mike Stump11289f42009-09-09 15:08:12 +00006518
Douglas Gregorfe314812011-06-21 17:03:29 +00006519 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006520 if (const Expr *Result =
6521 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
6522 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00006523 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00006524 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006525
Chris Lattner934edb22007-12-28 05:31:15 +00006526 // Everything else: we simply don't reason about them.
6527 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00006528 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00006529 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006530}
Mike Stump11289f42009-09-09 15:08:12 +00006531
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006532/// EvalVal - This function is complements EvalAddr in the mutual recursion.
6533/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006534static const Expr *EvalVal(const Expr *E,
6535 SmallVectorImpl<const DeclRefExpr *> &refVars,
6536 const Decl *ParentDecl) {
6537 do {
6538 // We should only be called for evaluating non-pointer expressions, or
6539 // expressions with a pointer type that are not used as references but
6540 // instead
6541 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00006542
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006543 // Our "symbolic interpreter" is just a dispatch off the currently
6544 // viewed AST node. We then recursively traverse the AST by calling
6545 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00006546
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006547 E = E->IgnoreParens();
6548 switch (E->getStmtClass()) {
6549 case Stmt::ImplicitCastExprClass: {
6550 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
6551 if (IE->getValueKind() == VK_LValue) {
6552 E = IE->getSubExpr();
6553 continue;
6554 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006555 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006556 }
Richard Smith40f08eb2014-01-30 22:05:38 +00006557
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006558 case Stmt::ExprWithCleanupsClass:
6559 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
6560 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006561
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006562 case Stmt::DeclRefExprClass: {
6563 // When we hit a DeclRefExpr we are looking at code that refers to a
6564 // variable's name. If it's not a reference variable we check if it has
6565 // local storage within the function, and if so, return the expression.
6566 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6567
6568 // If we leave the immediate function, the lifetime isn't about to end.
6569 if (DR->refersToEnclosingVariableOrCapture())
6570 return nullptr;
6571
6572 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
6573 // Check if it refers to itself, e.g. "int& i = i;".
6574 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006575 return DR;
6576
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006577 if (V->hasLocalStorage()) {
6578 if (!V->getType()->isReferenceType())
6579 return DR;
6580
6581 // Reference variable, follow through to the expression that
6582 // it points to.
6583 if (V->hasInit()) {
6584 // Add the reference variable to the "trail".
6585 refVars.push_back(DR);
6586 return EvalVal(V->getInit(), refVars, V);
6587 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006588 }
6589 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006590
6591 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006592 }
Mike Stump11289f42009-09-09 15:08:12 +00006593
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006594 case Stmt::UnaryOperatorClass: {
6595 // The only unary operator that make sense to handle here
6596 // is Deref. All others don't resolve to a "name." This includes
6597 // handling all sorts of rvalues passed to a unary operator.
6598 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006599
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006600 if (U->getOpcode() == UO_Deref)
6601 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00006602
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006603 return nullptr;
6604 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006605
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006606 case Stmt::ArraySubscriptExprClass: {
6607 // Array subscripts are potential references to data on the stack. We
6608 // retrieve the DeclRefExpr* for the array variable if it indeed
6609 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00006610 const auto *ASE = cast<ArraySubscriptExpr>(E);
6611 if (ASE->isTypeDependent())
6612 return nullptr;
6613 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006614 }
Mike Stump11289f42009-09-09 15:08:12 +00006615
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006616 case Stmt::OMPArraySectionExprClass: {
6617 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
6618 ParentDecl);
6619 }
Mike Stump11289f42009-09-09 15:08:12 +00006620
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006621 case Stmt::ConditionalOperatorClass: {
6622 // For conditional operators we need to see if either the LHS or RHS are
6623 // non-NULL Expr's. If one is non-NULL, we return it.
6624 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00006625
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006626 // Handle the GNU extension for missing LHS.
6627 if (const Expr *LHSExpr = C->getLHS()) {
6628 // In C++, we can have a throw-expression, which has 'void' type.
6629 if (!LHSExpr->getType()->isVoidType())
6630 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
6631 return LHS;
6632 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006633
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006634 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006635 if (C->getRHS()->getType()->isVoidType())
6636 return nullptr;
6637
6638 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006639 }
6640
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006641 // Accesses to members are potential references to data on the stack.
6642 case Stmt::MemberExprClass: {
6643 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00006644
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006645 // Check for indirect access. We only want direct field accesses.
6646 if (M->isArrow())
6647 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006648
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006649 // Check whether the member type is itself a reference, in which case
6650 // we're not going to refer to the member, but to what the member refers
6651 // to.
6652 if (M->getMemberDecl()->getType()->isReferenceType())
6653 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006654
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006655 return EvalVal(M->getBase(), refVars, ParentDecl);
6656 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00006657
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006658 case Stmt::MaterializeTemporaryExprClass:
6659 if (const Expr *Result =
6660 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
6661 refVars, ParentDecl))
6662 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006663 return E;
6664
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006665 default:
6666 // Check that we don't return or take the address of a reference to a
6667 // temporary. This is only useful in C++.
6668 if (!E->isTypeDependent() && E->isRValue())
6669 return E;
6670
6671 // Everything else: we simply don't reason about them.
6672 return nullptr;
6673 }
6674 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006675}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006676
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006677void
6678Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
6679 SourceLocation ReturnLoc,
6680 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00006681 const AttrVec *Attrs,
6682 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006683 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
6684
6685 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00006686 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
6687 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00006688 CheckNonNullExpr(*this, RetValExp))
6689 Diag(ReturnLoc, diag::warn_null_ret)
6690 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00006691
6692 // C++11 [basic.stc.dynamic.allocation]p4:
6693 // If an allocation function declared with a non-throwing
6694 // exception-specification fails to allocate storage, it shall return
6695 // a null pointer. Any other allocation function that fails to allocate
6696 // storage shall indicate failure only by throwing an exception [...]
6697 if (FD) {
6698 OverloadedOperatorKind Op = FD->getOverloadedOperator();
6699 if (Op == OO_New || Op == OO_Array_New) {
6700 const FunctionProtoType *Proto
6701 = FD->getType()->castAs<FunctionProtoType>();
6702 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
6703 CheckNonNullExpr(*this, RetValExp))
6704 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
6705 << FD << getLangOpts().CPlusPlus11;
6706 }
6707 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006708}
6709
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006710//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
6711
6712/// Check for comparisons of floating point operands using != and ==.
6713/// Issue a warning if these are no self-comparisons, as they are not likely
6714/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00006715void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00006716 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
6717 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006718
6719 // Special case: check for x == x (which is OK).
6720 // Do not emit warnings for such cases.
6721 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
6722 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
6723 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00006724 return;
Mike Stump11289f42009-09-09 15:08:12 +00006725
Ted Kremenekeda40e22007-11-29 00:59:04 +00006726 // Special case: check for comparisons against literals that can be exactly
6727 // represented by APFloat. In such cases, do not emit a warning. This
6728 // is a heuristic: often comparison against such literals are used to
6729 // detect if a value in a variable has not changed. This clearly can
6730 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00006731 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
6732 if (FLL->isExact())
6733 return;
6734 } else
6735 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
6736 if (FLR->isExact())
6737 return;
Mike Stump11289f42009-09-09 15:08:12 +00006738
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006739 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00006740 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00006741 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00006742 return;
Mike Stump11289f42009-09-09 15:08:12 +00006743
David Blaikie1f4ff152012-07-16 20:47:22 +00006744 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00006745 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00006746 return;
Mike Stump11289f42009-09-09 15:08:12 +00006747
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006748 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00006749 Diag(Loc, diag::warn_floatingpoint_eq)
6750 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006751}
John McCallca01b222010-01-04 23:21:16 +00006752
John McCall70aa5392010-01-06 05:24:50 +00006753//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
6754//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00006755
John McCall70aa5392010-01-06 05:24:50 +00006756namespace {
John McCallca01b222010-01-04 23:21:16 +00006757
John McCall70aa5392010-01-06 05:24:50 +00006758/// Structure recording the 'active' range of an integer-valued
6759/// expression.
6760struct IntRange {
6761 /// The number of bits active in the int.
6762 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00006763
John McCall70aa5392010-01-06 05:24:50 +00006764 /// True if the int is known not to have negative values.
6765 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00006766
John McCall70aa5392010-01-06 05:24:50 +00006767 IntRange(unsigned Width, bool NonNegative)
6768 : Width(Width), NonNegative(NonNegative)
6769 {}
John McCallca01b222010-01-04 23:21:16 +00006770
John McCall817d4af2010-11-10 23:38:19 +00006771 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00006772 static IntRange forBoolType() {
6773 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00006774 }
6775
John McCall817d4af2010-11-10 23:38:19 +00006776 /// Returns the range of an opaque value of the given integral type.
6777 static IntRange forValueOfType(ASTContext &C, QualType T) {
6778 return forValueOfCanonicalType(C,
6779 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00006780 }
6781
John McCall817d4af2010-11-10 23:38:19 +00006782 /// Returns the range of an opaque value of a canonical integral type.
6783 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00006784 assert(T->isCanonicalUnqualified());
6785
6786 if (const VectorType *VT = dyn_cast<VectorType>(T))
6787 T = VT->getElementType().getTypePtr();
6788 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
6789 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00006790 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
6791 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00006792
David Majnemer6a426652013-06-07 22:07:20 +00006793 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00006794 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00006795 EnumDecl *Enum = ET->getDecl();
6796 if (!Enum->isCompleteDefinition())
6797 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00006798
David Majnemer6a426652013-06-07 22:07:20 +00006799 unsigned NumPositive = Enum->getNumPositiveBits();
6800 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00006801
David Majnemer6a426652013-06-07 22:07:20 +00006802 if (NumNegative == 0)
6803 return IntRange(NumPositive, true/*NonNegative*/);
6804 else
6805 return IntRange(std::max(NumPositive + 1, NumNegative),
6806 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00006807 }
John McCall70aa5392010-01-06 05:24:50 +00006808
6809 const BuiltinType *BT = cast<BuiltinType>(T);
6810 assert(BT->isInteger());
6811
6812 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
6813 }
6814
John McCall817d4af2010-11-10 23:38:19 +00006815 /// Returns the "target" range of a canonical integral type, i.e.
6816 /// the range of values expressible in the type.
6817 ///
6818 /// This matches forValueOfCanonicalType except that enums have the
6819 /// full range of their type, not the range of their enumerators.
6820 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
6821 assert(T->isCanonicalUnqualified());
6822
6823 if (const VectorType *VT = dyn_cast<VectorType>(T))
6824 T = VT->getElementType().getTypePtr();
6825 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
6826 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00006827 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
6828 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00006829 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00006830 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00006831
6832 const BuiltinType *BT = cast<BuiltinType>(T);
6833 assert(BT->isInteger());
6834
6835 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
6836 }
6837
6838 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00006839 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00006840 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00006841 L.NonNegative && R.NonNegative);
6842 }
6843
John McCall817d4af2010-11-10 23:38:19 +00006844 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00006845 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00006846 return IntRange(std::min(L.Width, R.Width),
6847 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00006848 }
6849};
6850
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006851IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006852 if (value.isSigned() && value.isNegative())
6853 return IntRange(value.getMinSignedBits(), false);
6854
6855 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00006856 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00006857
6858 // isNonNegative() just checks the sign bit without considering
6859 // signedness.
6860 return IntRange(value.getActiveBits(), true);
6861}
6862
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006863IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
6864 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006865 if (result.isInt())
6866 return GetValueRange(C, result.getInt(), MaxWidth);
6867
6868 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00006869 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
6870 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
6871 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
6872 R = IntRange::join(R, El);
6873 }
John McCall70aa5392010-01-06 05:24:50 +00006874 return R;
6875 }
6876
6877 if (result.isComplexInt()) {
6878 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
6879 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
6880 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00006881 }
6882
6883 // This can happen with lossless casts to intptr_t of "based" lvalues.
6884 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00006885 // FIXME: The only reason we need to pass the type in here is to get
6886 // the sign right on this one case. It would be nice if APValue
6887 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006888 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00006889 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00006890}
John McCall70aa5392010-01-06 05:24:50 +00006891
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006892QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00006893 QualType Ty = E->getType();
6894 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
6895 Ty = AtomicRHS->getValueType();
6896 return Ty;
6897}
6898
John McCall70aa5392010-01-06 05:24:50 +00006899/// Pseudo-evaluate the given integer expression, estimating the
6900/// range of values it might take.
6901///
6902/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006903IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006904 E = E->IgnoreParens();
6905
6906 // Try a full evaluation first.
6907 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00006908 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00006909 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00006910
6911 // I think we only want to look through implicit casts here; if the
6912 // user has an explicit widening cast, we should treat the value as
6913 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006914 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00006915 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00006916 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
6917
Eli Friedmane6d33952013-07-08 20:20:06 +00006918 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00006919
George Burgess IVdf1ed002016-01-13 01:52:39 +00006920 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
6921 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00006922
John McCall70aa5392010-01-06 05:24:50 +00006923 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00006924 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00006925 return OutputTypeRange;
6926
6927 IntRange SubRange
6928 = GetExprRange(C, CE->getSubExpr(),
6929 std::min(MaxWidth, OutputTypeRange.Width));
6930
6931 // Bail out if the subexpr's range is as wide as the cast type.
6932 if (SubRange.Width >= OutputTypeRange.Width)
6933 return OutputTypeRange;
6934
6935 // Otherwise, we take the smaller width, and we're non-negative if
6936 // either the output type or the subexpr is.
6937 return IntRange(SubRange.Width,
6938 SubRange.NonNegative || OutputTypeRange.NonNegative);
6939 }
6940
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006941 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00006942 // If we can fold the condition, just take that operand.
6943 bool CondResult;
6944 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
6945 return GetExprRange(C, CondResult ? CO->getTrueExpr()
6946 : CO->getFalseExpr(),
6947 MaxWidth);
6948
6949 // Otherwise, conservatively merge.
6950 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
6951 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
6952 return IntRange::join(L, R);
6953 }
6954
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006955 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00006956 switch (BO->getOpcode()) {
6957
6958 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00006959 case BO_LAnd:
6960 case BO_LOr:
6961 case BO_LT:
6962 case BO_GT:
6963 case BO_LE:
6964 case BO_GE:
6965 case BO_EQ:
6966 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00006967 return IntRange::forBoolType();
6968
John McCallc3688382011-07-13 06:35:24 +00006969 // The type of the assignments is the type of the LHS, so the RHS
6970 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00006971 case BO_MulAssign:
6972 case BO_DivAssign:
6973 case BO_RemAssign:
6974 case BO_AddAssign:
6975 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00006976 case BO_XorAssign:
6977 case BO_OrAssign:
6978 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00006979 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00006980
John McCallc3688382011-07-13 06:35:24 +00006981 // Simple assignments just pass through the RHS, which will have
6982 // been coerced to the LHS type.
6983 case BO_Assign:
6984 // TODO: bitfields?
6985 return GetExprRange(C, BO->getRHS(), MaxWidth);
6986
John McCall70aa5392010-01-06 05:24:50 +00006987 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00006988 case BO_PtrMemD:
6989 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00006990 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006991
John McCall2ce81ad2010-01-06 22:07:33 +00006992 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00006993 case BO_And:
6994 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00006995 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
6996 GetExprRange(C, BO->getRHS(), MaxWidth));
6997
John McCall70aa5392010-01-06 05:24:50 +00006998 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00006999 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00007000 // ...except that we want to treat '1 << (blah)' as logically
7001 // positive. It's an important idiom.
7002 if (IntegerLiteral *I
7003 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
7004 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00007005 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00007006 return IntRange(R.Width, /*NonNegative*/ true);
7007 }
7008 }
7009 // fallthrough
7010
John McCalle3027922010-08-25 11:45:40 +00007011 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00007012 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00007013
John McCall2ce81ad2010-01-06 22:07:33 +00007014 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00007015 case BO_Shr:
7016 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00007017 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
7018
7019 // If the shift amount is a positive constant, drop the width by
7020 // that much.
7021 llvm::APSInt shift;
7022 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
7023 shift.isNonNegative()) {
7024 unsigned zext = shift.getZExtValue();
7025 if (zext >= L.Width)
7026 L.Width = (L.NonNegative ? 0 : 1);
7027 else
7028 L.Width -= zext;
7029 }
7030
7031 return L;
7032 }
7033
7034 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00007035 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00007036 return GetExprRange(C, BO->getRHS(), MaxWidth);
7037
John McCall2ce81ad2010-01-06 22:07:33 +00007038 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00007039 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00007040 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00007041 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00007042 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007043
John McCall51431812011-07-14 22:39:48 +00007044 // The width of a division result is mostly determined by the size
7045 // of the LHS.
7046 case BO_Div: {
7047 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00007048 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00007049 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
7050
7051 // If the divisor is constant, use that.
7052 llvm::APSInt divisor;
7053 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
7054 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
7055 if (log2 >= L.Width)
7056 L.Width = (L.NonNegative ? 0 : 1);
7057 else
7058 L.Width = std::min(L.Width - log2, MaxWidth);
7059 return L;
7060 }
7061
7062 // Otherwise, just use the LHS's width.
7063 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
7064 return IntRange(L.Width, L.NonNegative && R.NonNegative);
7065 }
7066
7067 // The result of a remainder can't be larger than the result of
7068 // either side.
7069 case BO_Rem: {
7070 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00007071 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00007072 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
7073 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
7074
7075 IntRange meet = IntRange::meet(L, R);
7076 meet.Width = std::min(meet.Width, MaxWidth);
7077 return meet;
7078 }
7079
7080 // The default behavior is okay for these.
7081 case BO_Mul:
7082 case BO_Add:
7083 case BO_Xor:
7084 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00007085 break;
7086 }
7087
John McCall51431812011-07-14 22:39:48 +00007088 // The default case is to treat the operation as if it were closed
7089 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00007090 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
7091 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
7092 return IntRange::join(L, R);
7093 }
7094
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007095 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00007096 switch (UO->getOpcode()) {
7097 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00007098 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00007099 return IntRange::forBoolType();
7100
7101 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00007102 case UO_Deref:
7103 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00007104 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00007105
7106 default:
7107 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
7108 }
7109 }
7110
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007111 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00007112 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
7113
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007114 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00007115 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00007116 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00007117
Eli Friedmane6d33952013-07-08 20:20:06 +00007118 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00007119}
John McCall263a48b2010-01-04 23:31:57 +00007120
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007121IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00007122 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00007123}
7124
John McCall263a48b2010-01-04 23:31:57 +00007125/// Checks whether the given value, which currently has the given
7126/// source semantics, has the same value when coerced through the
7127/// target semantics.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007128bool IsSameFloatAfterCast(const llvm::APFloat &value,
7129 const llvm::fltSemantics &Src,
7130 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00007131 llvm::APFloat truncated = value;
7132
7133 bool ignored;
7134 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
7135 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
7136
7137 return truncated.bitwiseIsEqual(value);
7138}
7139
7140/// Checks whether the given value, which currently has the given
7141/// source semantics, has the same value when coerced through the
7142/// target semantics.
7143///
7144/// The value might be a vector of floats (or a complex number).
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007145bool IsSameFloatAfterCast(const APValue &value,
7146 const llvm::fltSemantics &Src,
7147 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00007148 if (value.isFloat())
7149 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
7150
7151 if (value.isVector()) {
7152 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
7153 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
7154 return false;
7155 return true;
7156 }
7157
7158 assert(value.isComplexFloat());
7159 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
7160 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
7161}
7162
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007163void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007164
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007165bool IsZero(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00007166 // Suppress cases where we are comparing against an enum constant.
7167 if (const DeclRefExpr *DR =
7168 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
7169 if (isa<EnumConstantDecl>(DR->getDecl()))
7170 return false;
7171
7172 // Suppress cases where the '0' value is expanded from a macro.
7173 if (E->getLocStart().isMacroID())
7174 return false;
7175
John McCallcc7e5bf2010-05-06 08:58:33 +00007176 llvm::APSInt Value;
7177 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
7178}
7179
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007180bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00007181 // Strip off implicit integral promotions.
7182 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00007183 if (ICE->getCastKind() != CK_IntegralCast &&
7184 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00007185 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00007186 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00007187 }
7188
7189 return E->getType()->isEnumeralType();
7190}
7191
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007192void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00007193 // Disable warning in template instantiations.
7194 if (!S.ActiveTemplateInstantiations.empty())
7195 return;
7196
John McCalle3027922010-08-25 11:45:40 +00007197 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00007198 if (E->isValueDependent())
7199 return;
7200
John McCalle3027922010-08-25 11:45:40 +00007201 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007202 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00007203 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00007204 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00007205 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007206 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00007207 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00007208 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00007209 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007210 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00007211 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00007212 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00007213 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007214 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00007215 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00007216 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
7217 }
7218}
7219
Benjamin Kramer7320b992016-06-15 14:20:56 +00007220void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant,
7221 Expr *Other, const llvm::APSInt &Value,
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007222 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00007223 // Disable warning in template instantiations.
7224 if (!S.ActiveTemplateInstantiations.empty())
7225 return;
7226
Richard Trieu0f097742014-04-04 04:13:47 +00007227 // TODO: Investigate using GetExprRange() to get tighter bounds
7228 // on the bit ranges.
7229 QualType OtherT = Other->getType();
David Majnemer7800f1f2015-05-23 01:32:17 +00007230 if (const auto *AT = OtherT->getAs<AtomicType>())
Justin Bogner4f42fc42014-07-21 18:01:53 +00007231 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00007232 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
7233 unsigned OtherWidth = OtherRange.Width;
7234
7235 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
7236
Richard Trieu560910c2012-11-14 22:50:24 +00007237 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00007238 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00007239 return;
7240
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007241 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00007242 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00007243
Richard Trieu0f097742014-04-04 04:13:47 +00007244 // Used for diagnostic printout.
7245 enum {
7246 LiteralConstant = 0,
7247 CXXBoolLiteralTrue,
7248 CXXBoolLiteralFalse
7249 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00007250
Richard Trieu0f097742014-04-04 04:13:47 +00007251 if (!OtherIsBooleanType) {
7252 QualType ConstantT = Constant->getType();
7253 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00007254
Richard Trieu0f097742014-04-04 04:13:47 +00007255 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
7256 return;
7257 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
7258 "comparison with non-integer type");
7259
7260 bool ConstantSigned = ConstantT->isSignedIntegerType();
7261 bool CommonSigned = CommonT->isSignedIntegerType();
7262
7263 bool EqualityOnly = false;
7264
7265 if (CommonSigned) {
7266 // The common type is signed, therefore no signed to unsigned conversion.
7267 if (!OtherRange.NonNegative) {
7268 // Check that the constant is representable in type OtherT.
7269 if (ConstantSigned) {
7270 if (OtherWidth >= Value.getMinSignedBits())
7271 return;
7272 } else { // !ConstantSigned
7273 if (OtherWidth >= Value.getActiveBits() + 1)
7274 return;
7275 }
7276 } else { // !OtherSigned
7277 // Check that the constant is representable in type OtherT.
7278 // Negative values are out of range.
7279 if (ConstantSigned) {
7280 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
7281 return;
7282 } else { // !ConstantSigned
7283 if (OtherWidth >= Value.getActiveBits())
7284 return;
7285 }
Richard Trieu560910c2012-11-14 22:50:24 +00007286 }
Richard Trieu0f097742014-04-04 04:13:47 +00007287 } else { // !CommonSigned
7288 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00007289 if (OtherWidth >= Value.getActiveBits())
7290 return;
Craig Toppercf360162014-06-18 05:13:11 +00007291 } else { // OtherSigned
7292 assert(!ConstantSigned &&
7293 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00007294 // Check to see if the constant is representable in OtherT.
7295 if (OtherWidth > Value.getActiveBits())
7296 return;
7297 // Check to see if the constant is equivalent to a negative value
7298 // cast to CommonT.
7299 if (S.Context.getIntWidth(ConstantT) ==
7300 S.Context.getIntWidth(CommonT) &&
7301 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
7302 return;
7303 // The constant value rests between values that OtherT can represent
7304 // after conversion. Relational comparison still works, but equality
7305 // comparisons will be tautological.
7306 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00007307 }
7308 }
Richard Trieu0f097742014-04-04 04:13:47 +00007309
7310 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
7311
7312 if (op == BO_EQ || op == BO_NE) {
7313 IsTrue = op == BO_NE;
7314 } else if (EqualityOnly) {
7315 return;
7316 } else if (RhsConstant) {
7317 if (op == BO_GT || op == BO_GE)
7318 IsTrue = !PositiveConstant;
7319 else // op == BO_LT || op == BO_LE
7320 IsTrue = PositiveConstant;
7321 } else {
7322 if (op == BO_LT || op == BO_LE)
7323 IsTrue = !PositiveConstant;
7324 else // op == BO_GT || op == BO_GE
7325 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00007326 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007327 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00007328 // Other isKnownToHaveBooleanValue
7329 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
7330 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
7331 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
7332
7333 static const struct LinkedConditions {
7334 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
7335 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
7336 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
7337 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
7338 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
7339 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
7340
7341 } TruthTable = {
7342 // Constant on LHS. | Constant on RHS. |
7343 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
7344 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
7345 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
7346 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
7347 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
7348 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
7349 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
7350 };
7351
7352 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
7353
7354 enum ConstantValue ConstVal = Zero;
7355 if (Value.isUnsigned() || Value.isNonNegative()) {
7356 if (Value == 0) {
7357 LiteralOrBoolConstant =
7358 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
7359 ConstVal = Zero;
7360 } else if (Value == 1) {
7361 LiteralOrBoolConstant =
7362 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
7363 ConstVal = One;
7364 } else {
7365 LiteralOrBoolConstant = LiteralConstant;
7366 ConstVal = GT_One;
7367 }
7368 } else {
7369 ConstVal = LT_Zero;
7370 }
7371
7372 CompareBoolWithConstantResult CmpRes;
7373
7374 switch (op) {
7375 case BO_LT:
7376 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
7377 break;
7378 case BO_GT:
7379 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
7380 break;
7381 case BO_LE:
7382 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
7383 break;
7384 case BO_GE:
7385 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
7386 break;
7387 case BO_EQ:
7388 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
7389 break;
7390 case BO_NE:
7391 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
7392 break;
7393 default:
7394 CmpRes = Unkwn;
7395 break;
7396 }
7397
7398 if (CmpRes == AFals) {
7399 IsTrue = false;
7400 } else if (CmpRes == ATrue) {
7401 IsTrue = true;
7402 } else {
7403 return;
7404 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007405 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00007406
7407 // If this is a comparison to an enum constant, include that
7408 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00007409 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00007410 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
7411 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
7412
7413 SmallString<64> PrettySourceValue;
7414 llvm::raw_svector_ostream OS(PrettySourceValue);
7415 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00007416 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00007417 else
7418 OS << Value;
7419
Richard Trieu0f097742014-04-04 04:13:47 +00007420 S.DiagRuntimeBehavior(
7421 E->getOperatorLoc(), E,
7422 S.PDiag(diag::warn_out_of_range_compare)
7423 << OS.str() << LiteralOrBoolConstant
7424 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
7425 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007426}
7427
John McCallcc7e5bf2010-05-06 08:58:33 +00007428/// Analyze the operands of the given comparison. Implements the
7429/// fallback case from AnalyzeComparison.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007430void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00007431 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
7432 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00007433}
John McCall263a48b2010-01-04 23:31:57 +00007434
John McCallca01b222010-01-04 23:21:16 +00007435/// \brief Implements -Wsign-compare.
7436///
Richard Trieu82402a02011-09-15 21:56:47 +00007437/// \param E the binary operator to check for warnings
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007438void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007439 // The type the comparison is being performed in.
7440 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00007441
7442 // Only analyze comparison operators where both sides have been converted to
7443 // the same type.
7444 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
7445 return AnalyzeImpConvsInComparison(S, E);
7446
7447 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00007448 if (E->isValueDependent())
7449 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007450
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007451 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
7452 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007453
7454 bool IsComparisonConstant = false;
7455
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007456 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007457 // of 'true' or 'false'.
7458 if (T->isIntegralType(S.Context)) {
7459 llvm::APSInt RHSValue;
7460 bool IsRHSIntegralLiteral =
7461 RHS->isIntegerConstantExpr(RHSValue, S.Context);
7462 llvm::APSInt LHSValue;
7463 bool IsLHSIntegralLiteral =
7464 LHS->isIntegerConstantExpr(LHSValue, S.Context);
7465 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
7466 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
7467 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
7468 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
7469 else
7470 IsComparisonConstant =
7471 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007472 } else if (!T->hasUnsignedIntegerRepresentation())
7473 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007474
John McCallcc7e5bf2010-05-06 08:58:33 +00007475 // We don't do anything special if this isn't an unsigned integral
7476 // comparison: we're only interested in integral comparisons, and
7477 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00007478 //
7479 // We also don't care about value-dependent expressions or expressions
7480 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007481 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00007482 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007483
John McCallcc7e5bf2010-05-06 08:58:33 +00007484 // Check to see if one of the (unmodified) operands is of different
7485 // signedness.
7486 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00007487 if (LHS->getType()->hasSignedIntegerRepresentation()) {
7488 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00007489 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00007490 signedOperand = LHS;
7491 unsignedOperand = RHS;
7492 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
7493 signedOperand = RHS;
7494 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00007495 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00007496 CheckTrivialUnsignedComparison(S, E);
7497 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007498 }
7499
John McCallcc7e5bf2010-05-06 08:58:33 +00007500 // Otherwise, calculate the effective range of the signed operand.
7501 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00007502
John McCallcc7e5bf2010-05-06 08:58:33 +00007503 // Go ahead and analyze implicit conversions in the operands. Note
7504 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00007505 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
7506 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00007507
John McCallcc7e5bf2010-05-06 08:58:33 +00007508 // If the signed range is non-negative, -Wsign-compare won't fire,
7509 // but we should still check for comparisons which are always true
7510 // or false.
7511 if (signedRange.NonNegative)
7512 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007513
7514 // For (in)equality comparisons, if the unsigned operand is a
7515 // constant which cannot collide with a overflowed signed operand,
7516 // then reinterpreting the signed operand as unsigned will not
7517 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00007518 if (E->isEqualityOp()) {
7519 unsigned comparisonWidth = S.Context.getIntWidth(T);
7520 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00007521
John McCallcc7e5bf2010-05-06 08:58:33 +00007522 // We should never be unable to prove that the unsigned operand is
7523 // non-negative.
7524 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
7525
7526 if (unsignedRange.Width < comparisonWidth)
7527 return;
7528 }
7529
Douglas Gregorbfb4a212012-05-01 01:53:49 +00007530 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
7531 S.PDiag(diag::warn_mixed_sign_comparison)
7532 << LHS->getType() << RHS->getType()
7533 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00007534}
7535
John McCall1f425642010-11-11 03:21:53 +00007536/// Analyzes an attempt to assign the given value to a bitfield.
7537///
7538/// Returns true if there was something fishy about the attempt.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007539bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
7540 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00007541 assert(Bitfield->isBitField());
7542 if (Bitfield->isInvalidDecl())
7543 return false;
7544
John McCalldeebbcf2010-11-11 05:33:51 +00007545 // White-list bool bitfields.
7546 if (Bitfield->getType()->isBooleanType())
7547 return false;
7548
Douglas Gregor789adec2011-02-04 13:09:01 +00007549 // Ignore value- or type-dependent expressions.
7550 if (Bitfield->getBitWidth()->isValueDependent() ||
7551 Bitfield->getBitWidth()->isTypeDependent() ||
7552 Init->isValueDependent() ||
7553 Init->isTypeDependent())
7554 return false;
7555
John McCall1f425642010-11-11 03:21:53 +00007556 Expr *OriginalInit = Init->IgnoreParenImpCasts();
7557
Richard Smith5fab0c92011-12-28 19:48:30 +00007558 llvm::APSInt Value;
7559 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00007560 return false;
7561
John McCall1f425642010-11-11 03:21:53 +00007562 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00007563 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00007564
7565 if (OriginalWidth <= FieldWidth)
7566 return false;
7567
Eli Friedmanc267a322012-01-26 23:11:39 +00007568 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00007569 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00007570 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00007571
Eli Friedmanc267a322012-01-26 23:11:39 +00007572 // Check whether the stored value is equal to the original value.
7573 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00007574 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00007575 return false;
7576
Eli Friedmanc267a322012-01-26 23:11:39 +00007577 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00007578 // therefore don't strictly fit into a signed bitfield of width 1.
7579 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00007580 return false;
7581
John McCall1f425642010-11-11 03:21:53 +00007582 std::string PrettyValue = Value.toString(10);
7583 std::string PrettyTrunc = TruncatedValue.toString(10);
7584
7585 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
7586 << PrettyValue << PrettyTrunc << OriginalInit->getType()
7587 << Init->getSourceRange();
7588
7589 return true;
7590}
7591
John McCalld2a53122010-11-09 23:24:47 +00007592/// Analyze the given simple or compound assignment for warning-worthy
7593/// operations.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007594void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00007595 // Just recurse on the LHS.
7596 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
7597
7598 // We want to recurse on the RHS as normal unless we're assigning to
7599 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00007600 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007601 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00007602 E->getOperatorLoc())) {
7603 // Recurse, ignoring any implicit conversions on the RHS.
7604 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
7605 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00007606 }
7607 }
7608
7609 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
7610}
7611
John McCall263a48b2010-01-04 23:31:57 +00007612/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007613void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
7614 SourceLocation CContext, unsigned diag,
7615 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00007616 if (pruneControlFlow) {
7617 S.DiagRuntimeBehavior(E->getExprLoc(), E,
7618 S.PDiag(diag)
7619 << SourceType << T << E->getSourceRange()
7620 << SourceRange(CContext));
7621 return;
7622 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00007623 S.Diag(E->getExprLoc(), diag)
7624 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
7625}
7626
Chandler Carruth7f3654f2011-04-05 06:47:57 +00007627/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007628void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
7629 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00007630 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00007631}
7632
Richard Trieube234c32016-04-21 21:04:55 +00007633
7634/// Diagnose an implicit cast from a floating point value to an integer value.
7635void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
7636
7637 SourceLocation CContext) {
7638 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
7639 const bool PruneWarnings = !S.ActiveTemplateInstantiations.empty();
7640
7641 Expr *InnerE = E->IgnoreParenImpCasts();
7642 // We also want to warn on, e.g., "int i = -1.234"
7643 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
7644 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
7645 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
7646
7647 const bool IsLiteral =
7648 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
7649
7650 llvm::APFloat Value(0.0);
7651 bool IsConstant =
7652 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
7653 if (!IsConstant) {
Richard Trieu891f0f12016-04-22 22:14:32 +00007654 return DiagnoseImpCast(S, E, T, CContext,
7655 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +00007656 }
7657
Chandler Carruth016ef402011-04-10 08:36:24 +00007658 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +00007659
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00007660 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
7661 T->hasUnsignedIntegerRepresentation());
Richard Trieube234c32016-04-21 21:04:55 +00007662 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
7663 &isExact) == llvm::APFloat::opOK &&
Richard Trieu891f0f12016-04-22 22:14:32 +00007664 isExact) {
Richard Trieube234c32016-04-21 21:04:55 +00007665 if (IsLiteral) return;
7666 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
7667 PruneWarnings);
7668 }
7669
7670 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +00007671 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +00007672 // Warn on floating point literal to integer.
7673 DiagID = diag::warn_impcast_literal_float_to_integer;
7674 } else if (IntegerValue == 0) {
7675 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
7676 return DiagnoseImpCast(S, E, T, CContext,
7677 diag::warn_impcast_float_integer, PruneWarnings);
7678 }
7679 // Warn on non-zero to zero conversion.
7680 DiagID = diag::warn_impcast_float_to_integer_zero;
7681 } else {
7682 if (IntegerValue.isUnsigned()) {
7683 if (!IntegerValue.isMaxValue()) {
7684 return DiagnoseImpCast(S, E, T, CContext,
7685 diag::warn_impcast_float_integer, PruneWarnings);
7686 }
7687 } else { // IntegerValue.isSigned()
7688 if (!IntegerValue.isMaxSignedValue() &&
7689 !IntegerValue.isMinSignedValue()) {
7690 return DiagnoseImpCast(S, E, T, CContext,
7691 diag::warn_impcast_float_integer, PruneWarnings);
7692 }
7693 }
7694 // Warn on evaluatable floating point expression to integer conversion.
7695 DiagID = diag::warn_impcast_float_to_integer;
7696 }
Chandler Carruth016ef402011-04-10 08:36:24 +00007697
Eli Friedman07185912013-08-29 23:44:43 +00007698 // FIXME: Force the precision of the source value down so we don't print
7699 // digits which are usually useless (we don't really care here if we
7700 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
7701 // would automatically print the shortest representation, but it's a bit
7702 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00007703 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00007704 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
7705 precision = (precision * 59 + 195) / 196;
7706 Value.toString(PrettySourceValue, precision);
7707
David Blaikie9b88cc02012-05-15 17:18:27 +00007708 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +00007709 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +00007710 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00007711 else
David Blaikie9b88cc02012-05-15 17:18:27 +00007712 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00007713
Richard Trieube234c32016-04-21 21:04:55 +00007714 if (PruneWarnings) {
7715 S.DiagRuntimeBehavior(E->getExprLoc(), E,
7716 S.PDiag(DiagID)
7717 << E->getType() << T.getUnqualifiedType()
7718 << PrettySourceValue << PrettyTargetValue
7719 << E->getSourceRange() << SourceRange(CContext));
7720 } else {
7721 S.Diag(E->getExprLoc(), DiagID)
7722 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
7723 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
7724 }
Chandler Carruth016ef402011-04-10 08:36:24 +00007725}
7726
John McCall18a2c2c2010-11-09 22:22:12 +00007727std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
7728 if (!Range.Width) return "0";
7729
7730 llvm::APSInt ValueInRange = Value;
7731 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00007732 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00007733 return ValueInRange.toString(10);
7734}
7735
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007736bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007737 if (!isa<ImplicitCastExpr>(Ex))
7738 return false;
7739
7740 Expr *InnerE = Ex->IgnoreParenImpCasts();
7741 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
7742 const Type *Source =
7743 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
7744 if (Target->isDependentType())
7745 return false;
7746
7747 const BuiltinType *FloatCandidateBT =
7748 dyn_cast<BuiltinType>(ToBool ? Source : Target);
7749 const Type *BoolCandidateType = ToBool ? Target : Source;
7750
7751 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
7752 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
7753}
7754
7755void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
7756 SourceLocation CC) {
7757 unsigned NumArgs = TheCall->getNumArgs();
7758 for (unsigned i = 0; i < NumArgs; ++i) {
7759 Expr *CurrA = TheCall->getArg(i);
7760 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
7761 continue;
7762
7763 bool IsSwapped = ((i > 0) &&
7764 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
7765 IsSwapped |= ((i < (NumArgs - 1)) &&
7766 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
7767 if (IsSwapped) {
7768 // Warn on this floating-point to bool conversion.
7769 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
7770 CurrA->getType(), CC,
7771 diag::warn_impcast_floating_point_to_bool);
7772 }
7773 }
7774}
7775
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007776void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00007777 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
7778 E->getExprLoc()))
7779 return;
7780
Richard Trieu09d6b802016-01-08 23:35:06 +00007781 // Don't warn on functions which have return type nullptr_t.
7782 if (isa<CallExpr>(E))
7783 return;
7784
Richard Trieu5b993502014-10-15 03:42:06 +00007785 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
7786 const Expr::NullPointerConstantKind NullKind =
7787 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
7788 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
7789 return;
7790
7791 // Return if target type is a safe conversion.
7792 if (T->isAnyPointerType() || T->isBlockPointerType() ||
7793 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
7794 return;
7795
7796 SourceLocation Loc = E->getSourceRange().getBegin();
7797
Richard Trieu0a5e1662016-02-13 00:58:53 +00007798 // Venture through the macro stacks to get to the source of macro arguments.
7799 // The new location is a better location than the complete location that was
7800 // passed in.
7801 while (S.SourceMgr.isMacroArgExpansion(Loc))
7802 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
7803
7804 while (S.SourceMgr.isMacroArgExpansion(CC))
7805 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
7806
Richard Trieu5b993502014-10-15 03:42:06 +00007807 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +00007808 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
7809 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
7810 Loc, S.SourceMgr, S.getLangOpts());
7811 if (MacroName == "NULL")
7812 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
Richard Trieu5b993502014-10-15 03:42:06 +00007813 }
7814
7815 // Only warn if the null and context location are in the same macro expansion.
7816 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
7817 return;
7818
7819 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
7820 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
7821 << FixItHint::CreateReplacement(Loc,
7822 S.getFixItZeroLiteralForType(T, Loc));
7823}
7824
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007825void checkObjCArrayLiteral(Sema &S, QualType TargetType,
7826 ObjCArrayLiteral *ArrayLiteral);
7827void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
7828 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +00007829
7830/// Check a single element within a collection literal against the
7831/// target element type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007832void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
7833 Expr *Element, unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00007834 // Skip a bitcast to 'id' or qualified 'id'.
7835 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
7836 if (ICE->getCastKind() == CK_BitCast &&
7837 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
7838 Element = ICE->getSubExpr();
7839 }
7840
7841 QualType ElementType = Element->getType();
7842 ExprResult ElementResult(Element);
7843 if (ElementType->getAs<ObjCObjectPointerType>() &&
7844 S.CheckSingleAssignmentConstraints(TargetElementType,
7845 ElementResult,
7846 false, false)
7847 != Sema::Compatible) {
7848 S.Diag(Element->getLocStart(),
7849 diag::warn_objc_collection_literal_element)
7850 << ElementType << ElementKind << TargetElementType
7851 << Element->getSourceRange();
7852 }
7853
7854 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
7855 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
7856 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
7857 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
7858}
7859
7860/// Check an Objective-C array literal being converted to the given
7861/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007862void checkObjCArrayLiteral(Sema &S, QualType TargetType,
7863 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00007864 if (!S.NSArrayDecl)
7865 return;
7866
7867 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
7868 if (!TargetObjCPtr)
7869 return;
7870
7871 if (TargetObjCPtr->isUnspecialized() ||
7872 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
7873 != S.NSArrayDecl->getCanonicalDecl())
7874 return;
7875
7876 auto TypeArgs = TargetObjCPtr->getTypeArgs();
7877 if (TypeArgs.size() != 1)
7878 return;
7879
7880 QualType TargetElementType = TypeArgs[0];
7881 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
7882 checkObjCCollectionLiteralElement(S, TargetElementType,
7883 ArrayLiteral->getElement(I),
7884 0);
7885 }
7886}
7887
7888/// Check an Objective-C dictionary literal being converted to the given
7889/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007890void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
7891 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00007892 if (!S.NSDictionaryDecl)
7893 return;
7894
7895 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
7896 if (!TargetObjCPtr)
7897 return;
7898
7899 if (TargetObjCPtr->isUnspecialized() ||
7900 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
7901 != S.NSDictionaryDecl->getCanonicalDecl())
7902 return;
7903
7904 auto TypeArgs = TargetObjCPtr->getTypeArgs();
7905 if (TypeArgs.size() != 2)
7906 return;
7907
7908 QualType TargetKeyType = TypeArgs[0];
7909 QualType TargetObjectType = TypeArgs[1];
7910 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
7911 auto Element = DictionaryLiteral->getKeyValueElement(I);
7912 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
7913 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
7914 }
7915}
7916
Richard Trieufc404c72016-02-05 23:02:38 +00007917// Helper function to filter out cases for constant width constant conversion.
7918// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007919bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
7920 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +00007921 // If initializing from a constant, and the constant starts with '0',
7922 // then it is a binary, octal, or hexadecimal. Allow these constants
7923 // to fill all the bits, even if there is a sign change.
7924 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
7925 const char FirstLiteralCharacter =
7926 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
7927 if (FirstLiteralCharacter == '0')
7928 return false;
7929 }
7930
7931 // If the CC location points to a '{', and the type is char, then assume
7932 // assume it is an array initialization.
7933 if (CC.isValid() && T->isCharType()) {
7934 const char FirstContextCharacter =
7935 S.getSourceManager().getCharacterData(CC)[0];
7936 if (FirstContextCharacter == '{')
7937 return false;
7938 }
7939
7940 return true;
7941}
7942
John McCallcc7e5bf2010-05-06 08:58:33 +00007943void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00007944 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007945 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00007946
John McCallcc7e5bf2010-05-06 08:58:33 +00007947 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
7948 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
7949 if (Source == Target) return;
7950 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00007951
Chandler Carruthc22845a2011-07-26 05:40:03 +00007952 // If the conversion context location is invalid don't complain. We also
7953 // don't want to emit a warning if the issue occurs from the expansion of
7954 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
7955 // delay this check as long as possible. Once we detect we are in that
7956 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007957 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00007958 return;
7959
Richard Trieu021baa32011-09-23 20:10:00 +00007960 // Diagnose implicit casts to bool.
7961 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
7962 if (isa<StringLiteral>(E))
7963 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00007964 // and expressions, for instance, assert(0 && "error here"), are
7965 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00007966 return DiagnoseImpCast(S, E, T, CC,
7967 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00007968 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
7969 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
7970 // This covers the literal expressions that evaluate to Objective-C
7971 // objects.
7972 return DiagnoseImpCast(S, E, T, CC,
7973 diag::warn_impcast_objective_c_literal_to_bool);
7974 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00007975 if (Source->isPointerType() || Source->canDecayToPointerType()) {
7976 // Warn on pointer to bool conversion that is always true.
7977 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
7978 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00007979 }
Richard Trieu021baa32011-09-23 20:10:00 +00007980 }
John McCall263a48b2010-01-04 23:31:57 +00007981
Douglas Gregor5054cb02015-07-07 03:58:22 +00007982 // Check implicit casts from Objective-C collection literals to specialized
7983 // collection types, e.g., NSArray<NSString *> *.
7984 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
7985 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
7986 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
7987 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
7988
John McCall263a48b2010-01-04 23:31:57 +00007989 // Strip vector types.
7990 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007991 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007992 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007993 return;
John McCallacf0ee52010-10-08 02:01:28 +00007994 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007995 }
Chris Lattneree7286f2011-06-14 04:51:15 +00007996
7997 // If the vector cast is cast between two vectors of the same size, it is
7998 // a bitcast, not a conversion.
7999 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
8000 return;
John McCall263a48b2010-01-04 23:31:57 +00008001
8002 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
8003 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
8004 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00008005 if (auto VecTy = dyn_cast<VectorType>(Target))
8006 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00008007
8008 // Strip complex types.
8009 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008010 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008011 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008012 return;
8013
John McCallacf0ee52010-10-08 02:01:28 +00008014 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008015 }
John McCall263a48b2010-01-04 23:31:57 +00008016
8017 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
8018 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
8019 }
8020
8021 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
8022 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
8023
8024 // If the source is floating point...
8025 if (SourceBT && SourceBT->isFloatingPoint()) {
8026 // ...and the target is floating point...
8027 if (TargetBT && TargetBT->isFloatingPoint()) {
8028 // ...then warn if we're dropping FP rank.
8029
8030 // Builtin FP kinds are ordered by increasing FP rank.
8031 if (SourceBT->getKind() > TargetBT->getKind()) {
8032 // Don't warn about float constants that are precisely
8033 // representable in the target type.
8034 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00008035 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00008036 // Value might be a float, a float vector, or a float complex.
8037 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00008038 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
8039 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00008040 return;
8041 }
8042
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008043 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008044 return;
8045
John McCallacf0ee52010-10-08 02:01:28 +00008046 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +00008047 }
8048 // ... or possibly if we're increasing rank, too
8049 else if (TargetBT->getKind() > SourceBT->getKind()) {
8050 if (S.SourceMgr.isInSystemMacro(CC))
8051 return;
8052
8053 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +00008054 }
8055 return;
8056 }
8057
Richard Trieube234c32016-04-21 21:04:55 +00008058 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00008059 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008060 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008061 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00008062
Richard Trieube234c32016-04-21 21:04:55 +00008063 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00008064 }
John McCall263a48b2010-01-04 23:31:57 +00008065
Richard Smith54894fd2015-12-30 01:06:52 +00008066 // Detect the case where a call result is converted from floating-point to
8067 // to bool, and the final argument to the call is converted from bool, to
8068 // discover this typo:
8069 //
8070 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
8071 //
8072 // FIXME: This is an incredibly special case; is there some more general
8073 // way to detect this class of misplaced-parentheses bug?
8074 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008075 // Check last argument of function call to see if it is an
8076 // implicit cast from a type matching the type the result
8077 // is being cast to.
8078 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +00008079 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008080 Expr *LastA = CEx->getArg(NumArgs - 1);
8081 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +00008082 if (isa<ImplicitCastExpr>(LastA) &&
8083 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008084 // Warn on this floating-point to bool conversion
8085 DiagnoseImpCast(S, E, T, CC,
8086 diag::warn_impcast_floating_point_to_bool);
8087 }
8088 }
8089 }
John McCall263a48b2010-01-04 23:31:57 +00008090 return;
8091 }
8092
Richard Trieu5b993502014-10-15 03:42:06 +00008093 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00008094
David Blaikie9366d2b2012-06-19 21:19:06 +00008095 if (!Source->isIntegerType() || !Target->isIntegerType())
8096 return;
8097
David Blaikie7555b6a2012-05-15 16:56:36 +00008098 // TODO: remove this early return once the false positives for constant->bool
8099 // in templates, macros, etc, are reduced or removed.
8100 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
8101 return;
8102
John McCallcc7e5bf2010-05-06 08:58:33 +00008103 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00008104 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00008105
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008106 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00008107 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008108 // TODO: this should happen for bitfield stores, too.
8109 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +00008110 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008111 if (S.SourceMgr.isInSystemMacro(CC))
8112 return;
8113
John McCall18a2c2c2010-11-09 22:22:12 +00008114 std::string PrettySourceValue = Value.toString(10);
8115 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008116
Ted Kremenek33ba9952011-10-22 02:37:33 +00008117 S.DiagRuntimeBehavior(E->getExprLoc(), E,
8118 S.PDiag(diag::warn_impcast_integer_precision_constant)
8119 << PrettySourceValue << PrettyTargetValue
8120 << E->getType() << T << E->getSourceRange()
8121 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00008122 return;
8123 }
8124
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008125 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
8126 if (S.SourceMgr.isInSystemMacro(CC))
8127 return;
8128
David Blaikie9455da02012-04-12 22:40:54 +00008129 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00008130 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
8131 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00008132 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00008133 }
8134
Richard Trieudcb55572016-01-29 23:51:16 +00008135 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
8136 SourceRange.NonNegative && Source->isSignedIntegerType()) {
8137 // Warn when doing a signed to signed conversion, warn if the positive
8138 // source value is exactly the width of the target type, which will
8139 // cause a negative value to be stored.
8140
8141 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +00008142 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
8143 !S.SourceMgr.isInSystemMacro(CC)) {
8144 if (isSameWidthConstantConversion(S, E, T, CC)) {
8145 std::string PrettySourceValue = Value.toString(10);
8146 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +00008147
Richard Trieufc404c72016-02-05 23:02:38 +00008148 S.DiagRuntimeBehavior(
8149 E->getExprLoc(), E,
8150 S.PDiag(diag::warn_impcast_integer_precision_constant)
8151 << PrettySourceValue << PrettyTargetValue << E->getType() << T
8152 << E->getSourceRange() << clang::SourceRange(CC));
8153 return;
Richard Trieudcb55572016-01-29 23:51:16 +00008154 }
8155 }
Richard Trieufc404c72016-02-05 23:02:38 +00008156
Richard Trieudcb55572016-01-29 23:51:16 +00008157 // Fall through for non-constants to give a sign conversion warning.
8158 }
8159
John McCallcc7e5bf2010-05-06 08:58:33 +00008160 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
8161 (!TargetRange.NonNegative && SourceRange.NonNegative &&
8162 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008163 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008164 return;
8165
John McCallcc7e5bf2010-05-06 08:58:33 +00008166 unsigned DiagID = diag::warn_impcast_integer_sign;
8167
8168 // Traditionally, gcc has warned about this under -Wsign-compare.
8169 // We also want to warn about it in -Wconversion.
8170 // So if -Wconversion is off, use a completely identical diagnostic
8171 // in the sign-compare group.
8172 // The conditional-checking code will
8173 if (ICContext) {
8174 DiagID = diag::warn_impcast_integer_sign_conditional;
8175 *ICContext = true;
8176 }
8177
John McCallacf0ee52010-10-08 02:01:28 +00008178 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00008179 }
8180
Douglas Gregora78f1932011-02-22 02:45:07 +00008181 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00008182 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
8183 // type, to give us better diagnostics.
8184 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00008185 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00008186 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8187 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
8188 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
8189 SourceType = S.Context.getTypeDeclType(Enum);
8190 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
8191 }
8192 }
8193
Douglas Gregora78f1932011-02-22 02:45:07 +00008194 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
8195 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00008196 if (SourceEnum->getDecl()->hasNameForLinkage() &&
8197 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008198 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008199 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008200 return;
8201
Douglas Gregor364f7db2011-03-12 00:14:31 +00008202 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00008203 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008204 }
John McCall263a48b2010-01-04 23:31:57 +00008205}
8206
David Blaikie18e9ac72012-05-15 21:57:38 +00008207void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
8208 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00008209
8210void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00008211 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008212 E = E->IgnoreParenImpCasts();
8213
8214 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00008215 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00008216
John McCallacf0ee52010-10-08 02:01:28 +00008217 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008218 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00008219 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00008220}
8221
David Blaikie18e9ac72012-05-15 21:57:38 +00008222void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
8223 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00008224 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00008225
8226 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00008227 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
8228 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00008229
8230 // If -Wconversion would have warned about either of the candidates
8231 // for a signedness conversion to the context type...
8232 if (!Suspicious) return;
8233
8234 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008235 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00008236 return;
8237
John McCallcc7e5bf2010-05-06 08:58:33 +00008238 // ...then check whether it would have warned about either of the
8239 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00008240 if (E->getType() == T) return;
8241
8242 Suspicious = false;
8243 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
8244 E->getType(), CC, &Suspicious);
8245 if (!Suspicious)
8246 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00008247 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00008248}
8249
Richard Trieu65724892014-11-15 06:37:39 +00008250/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
8251/// Input argument E is a logical expression.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008252void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +00008253 if (S.getLangOpts().Bool)
8254 return;
8255 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
8256}
8257
John McCallcc7e5bf2010-05-06 08:58:33 +00008258/// AnalyzeImplicitConversions - Find and report any interesting
8259/// implicit conversions in the given expression. There are a couple
8260/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00008261void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00008262 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00008263 Expr *E = OrigE->IgnoreParenImpCasts();
8264
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00008265 if (E->isTypeDependent() || E->isValueDependent())
8266 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00008267
John McCallcc7e5bf2010-05-06 08:58:33 +00008268 // For conditional operators, we analyze the arguments as if they
8269 // were being fed directly into the output.
8270 if (isa<ConditionalOperator>(E)) {
8271 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00008272 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00008273 return;
8274 }
8275
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008276 // Check implicit argument conversions for function calls.
8277 if (CallExpr *Call = dyn_cast<CallExpr>(E))
8278 CheckImplicitArgumentConversions(S, Call, CC);
8279
John McCallcc7e5bf2010-05-06 08:58:33 +00008280 // Go ahead and check any implicit conversions we might have skipped.
8281 // The non-canonical typecheck is just an optimization;
8282 // CheckImplicitConversion will filter out dead implicit conversions.
8283 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00008284 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008285
8286 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +00008287
8288 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
8289 // The bound subexpressions in a PseudoObjectExpr are not reachable
8290 // as transitive children.
8291 // FIXME: Use a more uniform representation for this.
8292 for (auto *SE : POE->semantics())
8293 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
8294 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00008295 }
Richard Smithd7bed4d2015-11-22 02:57:17 +00008296
John McCallcc7e5bf2010-05-06 08:58:33 +00008297 // Skip past explicit casts.
8298 if (isa<ExplicitCastExpr>(E)) {
8299 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00008300 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008301 }
8302
John McCalld2a53122010-11-09 23:24:47 +00008303 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8304 // Do a somewhat different check with comparison operators.
8305 if (BO->isComparisonOp())
8306 return AnalyzeComparison(S, BO);
8307
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008308 // And with simple assignments.
8309 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00008310 return AnalyzeAssignment(S, BO);
8311 }
John McCallcc7e5bf2010-05-06 08:58:33 +00008312
8313 // These break the otherwise-useful invariant below. Fortunately,
8314 // we don't really need to recurse into them, because any internal
8315 // expressions should have been analyzed already when they were
8316 // built into statements.
8317 if (isa<StmtExpr>(E)) return;
8318
8319 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00008320 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00008321
8322 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00008323 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00008324 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00008325 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +00008326 for (Stmt *SubStmt : E->children()) {
8327 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00008328 if (!ChildExpr)
8329 continue;
8330
Richard Trieu955231d2014-01-25 01:10:35 +00008331 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00008332 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00008333 // Ignore checking string literals that are in logical and operators.
8334 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00008335 continue;
8336 AnalyzeImplicitConversions(S, ChildExpr, CC);
8337 }
Richard Trieu791b86e2014-11-19 06:08:18 +00008338
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00008339 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00008340 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
8341 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00008342 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00008343
8344 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
8345 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00008346 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00008347 }
Richard Trieu791b86e2014-11-19 06:08:18 +00008348
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00008349 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
8350 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00008351 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008352}
8353
8354} // end anonymous namespace
8355
Richard Trieuc1888e02014-06-28 23:25:37 +00008356// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
8357// Returns true when emitting a warning about taking the address of a reference.
8358static bool CheckForReference(Sema &SemaRef, const Expr *E,
Benjamin Kramer7320b992016-06-15 14:20:56 +00008359 const PartialDiagnostic &PD) {
Richard Trieuc1888e02014-06-28 23:25:37 +00008360 E = E->IgnoreParenImpCasts();
8361
8362 const FunctionDecl *FD = nullptr;
8363
8364 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8365 if (!DRE->getDecl()->getType()->isReferenceType())
8366 return false;
8367 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
8368 if (!M->getMemberDecl()->getType()->isReferenceType())
8369 return false;
8370 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00008371 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00008372 return false;
8373 FD = Call->getDirectCallee();
8374 } else {
8375 return false;
8376 }
8377
8378 SemaRef.Diag(E->getExprLoc(), PD);
8379
8380 // If possible, point to location of function.
8381 if (FD) {
8382 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
8383 }
8384
8385 return true;
8386}
8387
Richard Trieu4cbff5c2014-08-08 22:41:43 +00008388// Returns true if the SourceLocation is expanded from any macro body.
8389// Returns false if the SourceLocation is invalid, is from not in a macro
8390// expansion, or is from expanded from a top-level macro argument.
8391static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
8392 if (Loc.isInvalid())
8393 return false;
8394
8395 while (Loc.isMacroID()) {
8396 if (SM.isMacroBodyExpansion(Loc))
8397 return true;
8398 Loc = SM.getImmediateMacroCallerLoc(Loc);
8399 }
8400
8401 return false;
8402}
8403
Richard Trieu3bb8b562014-02-26 02:36:06 +00008404/// \brief Diagnose pointers that are always non-null.
8405/// \param E the expression containing the pointer
8406/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
8407/// compared to a null pointer
8408/// \param IsEqual True when the comparison is equal to a null pointer
8409/// \param Range Extra SourceRange to highlight in the diagnostic
8410void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
8411 Expr::NullPointerConstantKind NullKind,
8412 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00008413 if (!E)
8414 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008415
8416 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00008417 if (E->getExprLoc().isMacroID()) {
8418 const SourceManager &SM = getSourceManager();
8419 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
8420 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00008421 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00008422 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00008423 E = E->IgnoreImpCasts();
8424
8425 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
8426
Richard Trieuf7432752014-06-06 21:39:26 +00008427 if (isa<CXXThisExpr>(E)) {
8428 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
8429 : diag::warn_this_bool_conversion;
8430 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
8431 return;
8432 }
8433
Richard Trieu3bb8b562014-02-26 02:36:06 +00008434 bool IsAddressOf = false;
8435
8436 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
8437 if (UO->getOpcode() != UO_AddrOf)
8438 return;
8439 IsAddressOf = true;
8440 E = UO->getSubExpr();
8441 }
8442
Richard Trieuc1888e02014-06-28 23:25:37 +00008443 if (IsAddressOf) {
8444 unsigned DiagID = IsCompare
8445 ? diag::warn_address_of_reference_null_compare
8446 : diag::warn_address_of_reference_bool_conversion;
8447 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
8448 << IsEqual;
8449 if (CheckForReference(*this, E, PD)) {
8450 return;
8451 }
8452 }
8453
Nick Lewyckybc85ec82016-06-15 05:18:39 +00008454 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
8455 bool IsParam = isa<NonNullAttr>(NonnullAttr);
George Burgess IV850269a2015-12-08 22:02:00 +00008456 std::string Str;
8457 llvm::raw_string_ostream S(Str);
8458 E->printPretty(S, nullptr, getPrintingPolicy());
8459 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
8460 : diag::warn_cast_nonnull_to_bool;
8461 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
8462 << E->getSourceRange() << Range << IsEqual;
Nick Lewyckybc85ec82016-06-15 05:18:39 +00008463 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
George Burgess IV850269a2015-12-08 22:02:00 +00008464 };
8465
8466 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
8467 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
8468 if (auto *Callee = Call->getDirectCallee()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00008469 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
8470 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00008471 return;
8472 }
8473 }
8474 }
8475
Richard Trieu3bb8b562014-02-26 02:36:06 +00008476 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00008477 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008478 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
8479 D = R->getDecl();
8480 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
8481 D = M->getMemberDecl();
8482 }
8483
8484 // Weak Decls can be null.
8485 if (!D || D->isWeak())
8486 return;
George Burgess IV850269a2015-12-08 22:02:00 +00008487
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008488 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +00008489 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
8490 if (getCurFunction() &&
8491 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00008492 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
8493 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00008494 return;
8495 }
8496
8497 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
David Majnemera3debed2016-06-24 05:33:44 +00008498 auto ParamIter = llvm::find(FD->parameters(), PV);
George Burgess IV850269a2015-12-08 22:02:00 +00008499 assert(ParamIter != FD->param_end());
8500 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
8501
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008502 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
8503 if (!NonNull->args_size()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00008504 ComplainAboutNonnullParamOrCall(NonNull);
George Burgess IV850269a2015-12-08 22:02:00 +00008505 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008506 }
George Burgess IV850269a2015-12-08 22:02:00 +00008507
8508 for (unsigned ArgNo : NonNull->args()) {
8509 if (ArgNo == ParamNo) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00008510 ComplainAboutNonnullParamOrCall(NonNull);
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008511 return;
8512 }
George Burgess IV850269a2015-12-08 22:02:00 +00008513 }
8514 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008515 }
8516 }
George Burgess IV850269a2015-12-08 22:02:00 +00008517 }
8518
Richard Trieu3bb8b562014-02-26 02:36:06 +00008519 QualType T = D->getType();
8520 const bool IsArray = T->isArrayType();
8521 const bool IsFunction = T->isFunctionType();
8522
Richard Trieuc1888e02014-06-28 23:25:37 +00008523 // Address of function is used to silence the function warning.
8524 if (IsAddressOf && IsFunction) {
8525 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008526 }
8527
8528 // Found nothing.
8529 if (!IsAddressOf && !IsFunction && !IsArray)
8530 return;
8531
8532 // Pretty print the expression for the diagnostic.
8533 std::string Str;
8534 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00008535 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00008536
8537 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
8538 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +00008539 enum {
8540 AddressOf,
8541 FunctionPointer,
8542 ArrayPointer
8543 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008544 if (IsAddressOf)
8545 DiagType = AddressOf;
8546 else if (IsFunction)
8547 DiagType = FunctionPointer;
8548 else if (IsArray)
8549 DiagType = ArrayPointer;
8550 else
8551 llvm_unreachable("Could not determine diagnostic.");
8552 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
8553 << Range << IsEqual;
8554
8555 if (!IsFunction)
8556 return;
8557
8558 // Suggest '&' to silence the function warning.
8559 Diag(E->getExprLoc(), diag::note_function_warning_silence)
8560 << FixItHint::CreateInsertion(E->getLocStart(), "&");
8561
8562 // Check to see if '()' fixit should be emitted.
8563 QualType ReturnType;
8564 UnresolvedSet<4> NonTemplateOverloads;
8565 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
8566 if (ReturnType.isNull())
8567 return;
8568
8569 if (IsCompare) {
8570 // There are two cases here. If there is null constant, the only suggest
8571 // for a pointer return type. If the null is 0, then suggest if the return
8572 // type is a pointer or an integer type.
8573 if (!ReturnType->isPointerType()) {
8574 if (NullKind == Expr::NPCK_ZeroExpression ||
8575 NullKind == Expr::NPCK_ZeroLiteral) {
8576 if (!ReturnType->isIntegerType())
8577 return;
8578 } else {
8579 return;
8580 }
8581 }
8582 } else { // !IsCompare
8583 // For function to bool, only suggest if the function pointer has bool
8584 // return type.
8585 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
8586 return;
8587 }
8588 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00008589 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00008590}
8591
John McCallcc7e5bf2010-05-06 08:58:33 +00008592/// Diagnoses "dangerous" implicit conversions within the given
8593/// expression (which is a full expression). Implements -Wconversion
8594/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00008595///
8596/// \param CC the "context" location of the implicit conversion, i.e.
8597/// the most location of the syntactic entity requiring the implicit
8598/// conversion
8599void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008600 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00008601 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00008602 return;
8603
8604 // Don't diagnose for value- or type-dependent expressions.
8605 if (E->isTypeDependent() || E->isValueDependent())
8606 return;
8607
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008608 // Check for array bounds violations in cases where the check isn't triggered
8609 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
8610 // ArraySubscriptExpr is on the RHS of a variable initialization.
8611 CheckArrayAccess(E);
8612
John McCallacf0ee52010-10-08 02:01:28 +00008613 // This is not the right CC for (e.g.) a variable initialization.
8614 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008615}
8616
Richard Trieu65724892014-11-15 06:37:39 +00008617/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
8618/// Input argument E is a logical expression.
8619void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
8620 ::CheckBoolLikeConversion(*this, E, CC);
8621}
8622
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008623/// Diagnose when expression is an integer constant expression and its evaluation
8624/// results in integer overflow
8625void Sema::CheckForIntOverflow (Expr *E) {
Akira Hatanakadfe2156f2016-02-10 06:06:06 +00008626 // Use a work list to deal with nested struct initializers.
8627 SmallVector<Expr *, 2> Exprs(1, E);
8628
8629 do {
8630 Expr *E = Exprs.pop_back_val();
8631
8632 if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
8633 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
8634 continue;
8635 }
8636
8637 if (auto InitList = dyn_cast<InitListExpr>(E))
8638 Exprs.append(InitList->inits().begin(), InitList->inits().end());
8639 } while (!Exprs.empty());
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008640}
8641
Richard Smithc406cb72013-01-17 01:17:56 +00008642namespace {
8643/// \brief Visitor for expressions which looks for unsequenced operations on the
8644/// same object.
8645class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00008646 typedef EvaluatedExprVisitor<SequenceChecker> Base;
8647
Richard Smithc406cb72013-01-17 01:17:56 +00008648 /// \brief A tree of sequenced regions within an expression. Two regions are
8649 /// unsequenced if one is an ancestor or a descendent of the other. When we
8650 /// finish processing an expression with sequencing, such as a comma
8651 /// expression, we fold its tree nodes into its parent, since they are
8652 /// unsequenced with respect to nodes we will visit later.
8653 class SequenceTree {
8654 struct Value {
8655 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
8656 unsigned Parent : 31;
8657 bool Merged : 1;
8658 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008659 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00008660
8661 public:
8662 /// \brief A region within an expression which may be sequenced with respect
8663 /// to some other region.
8664 class Seq {
8665 explicit Seq(unsigned N) : Index(N) {}
8666 unsigned Index;
8667 friend class SequenceTree;
8668 public:
8669 Seq() : Index(0) {}
8670 };
8671
8672 SequenceTree() { Values.push_back(Value(0)); }
8673 Seq root() const { return Seq(0); }
8674
8675 /// \brief Create a new sequence of operations, which is an unsequenced
8676 /// subset of \p Parent. This sequence of operations is sequenced with
8677 /// respect to other children of \p Parent.
8678 Seq allocate(Seq Parent) {
8679 Values.push_back(Value(Parent.Index));
8680 return Seq(Values.size() - 1);
8681 }
8682
8683 /// \brief Merge a sequence of operations into its parent.
8684 void merge(Seq S) {
8685 Values[S.Index].Merged = true;
8686 }
8687
8688 /// \brief Determine whether two operations are unsequenced. This operation
8689 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
8690 /// should have been merged into its parent as appropriate.
8691 bool isUnsequenced(Seq Cur, Seq Old) {
8692 unsigned C = representative(Cur.Index);
8693 unsigned Target = representative(Old.Index);
8694 while (C >= Target) {
8695 if (C == Target)
8696 return true;
8697 C = Values[C].Parent;
8698 }
8699 return false;
8700 }
8701
8702 private:
8703 /// \brief Pick a representative for a sequence.
8704 unsigned representative(unsigned K) {
8705 if (Values[K].Merged)
8706 // Perform path compression as we go.
8707 return Values[K].Parent = representative(Values[K].Parent);
8708 return K;
8709 }
8710 };
8711
8712 /// An object for which we can track unsequenced uses.
8713 typedef NamedDecl *Object;
8714
8715 /// Different flavors of object usage which we track. We only track the
8716 /// least-sequenced usage of each kind.
8717 enum UsageKind {
8718 /// A read of an object. Multiple unsequenced reads are OK.
8719 UK_Use,
8720 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00008721 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00008722 UK_ModAsValue,
8723 /// A modification of an object which is not sequenced before the value
8724 /// computation of the expression, such as n++.
8725 UK_ModAsSideEffect,
8726
8727 UK_Count = UK_ModAsSideEffect + 1
8728 };
8729
8730 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00008731 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00008732 Expr *Use;
8733 SequenceTree::Seq Seq;
8734 };
8735
8736 struct UsageInfo {
8737 UsageInfo() : Diagnosed(false) {}
8738 Usage Uses[UK_Count];
8739 /// Have we issued a diagnostic for this variable already?
8740 bool Diagnosed;
8741 };
8742 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
8743
8744 Sema &SemaRef;
8745 /// Sequenced regions within the expression.
8746 SequenceTree Tree;
8747 /// Declaration modifications and references which we have seen.
8748 UsageInfoMap UsageMap;
8749 /// The region we are currently within.
8750 SequenceTree::Seq Region;
8751 /// Filled in with declarations which were modified as a side-effect
8752 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008753 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00008754 /// Expressions to check later. We defer checking these to reduce
8755 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008756 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00008757
8758 /// RAII object wrapping the visitation of a sequenced subexpression of an
8759 /// expression. At the end of this process, the side-effects of the evaluation
8760 /// become sequenced with respect to the value computation of the result, so
8761 /// we downgrade any UK_ModAsSideEffect within the evaluation to
8762 /// UK_ModAsValue.
8763 struct SequencedSubexpression {
8764 SequencedSubexpression(SequenceChecker &Self)
8765 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
8766 Self.ModAsSideEffect = &ModAsSideEffect;
8767 }
8768 ~SequencedSubexpression() {
David Majnemerf7e36092016-06-23 00:15:04 +00008769 for (auto &M : llvm::reverse(ModAsSideEffect)) {
8770 UsageInfo &U = Self.UsageMap[M.first];
Richard Smithe8efd992014-12-03 01:05:50 +00008771 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
David Majnemerf7e36092016-06-23 00:15:04 +00008772 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
8773 SideEffectUsage = M.second;
Richard Smithc406cb72013-01-17 01:17:56 +00008774 }
8775 Self.ModAsSideEffect = OldModAsSideEffect;
8776 }
8777
8778 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008779 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
8780 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00008781 };
8782
Richard Smith40238f02013-06-20 22:21:56 +00008783 /// RAII object wrapping the visitation of a subexpression which we might
8784 /// choose to evaluate as a constant. If any subexpression is evaluated and
8785 /// found to be non-constant, this allows us to suppress the evaluation of
8786 /// the outer expression.
8787 class EvaluationTracker {
8788 public:
8789 EvaluationTracker(SequenceChecker &Self)
8790 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
8791 Self.EvalTracker = this;
8792 }
8793 ~EvaluationTracker() {
8794 Self.EvalTracker = Prev;
8795 if (Prev)
8796 Prev->EvalOK &= EvalOK;
8797 }
8798
8799 bool evaluate(const Expr *E, bool &Result) {
8800 if (!EvalOK || E->isValueDependent())
8801 return false;
8802 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
8803 return EvalOK;
8804 }
8805
8806 private:
8807 SequenceChecker &Self;
8808 EvaluationTracker *Prev;
8809 bool EvalOK;
8810 } *EvalTracker;
8811
Richard Smithc406cb72013-01-17 01:17:56 +00008812 /// \brief Find the object which is produced by the specified expression,
8813 /// if any.
8814 Object getObject(Expr *E, bool Mod) const {
8815 E = E->IgnoreParenCasts();
8816 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
8817 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
8818 return getObject(UO->getSubExpr(), Mod);
8819 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8820 if (BO->getOpcode() == BO_Comma)
8821 return getObject(BO->getRHS(), Mod);
8822 if (Mod && BO->isAssignmentOp())
8823 return getObject(BO->getLHS(), Mod);
8824 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
8825 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
8826 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
8827 return ME->getMemberDecl();
8828 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8829 // FIXME: If this is a reference, map through to its value.
8830 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00008831 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00008832 }
8833
8834 /// \brief Note that an object was modified or used by an expression.
8835 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
8836 Usage &U = UI.Uses[UK];
8837 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
8838 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
8839 ModAsSideEffect->push_back(std::make_pair(O, U));
8840 U.Use = Ref;
8841 U.Seq = Region;
8842 }
8843 }
8844 /// \brief Check whether a modification or use conflicts with a prior usage.
8845 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
8846 bool IsModMod) {
8847 if (UI.Diagnosed)
8848 return;
8849
8850 const Usage &U = UI.Uses[OtherKind];
8851 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
8852 return;
8853
8854 Expr *Mod = U.Use;
8855 Expr *ModOrUse = Ref;
8856 if (OtherKind == UK_Use)
8857 std::swap(Mod, ModOrUse);
8858
8859 SemaRef.Diag(Mod->getExprLoc(),
8860 IsModMod ? diag::warn_unsequenced_mod_mod
8861 : diag::warn_unsequenced_mod_use)
8862 << O << SourceRange(ModOrUse->getExprLoc());
8863 UI.Diagnosed = true;
8864 }
8865
8866 void notePreUse(Object O, Expr *Use) {
8867 UsageInfo &U = UsageMap[O];
8868 // Uses conflict with other modifications.
8869 checkUsage(O, U, Use, UK_ModAsValue, false);
8870 }
8871 void notePostUse(Object O, Expr *Use) {
8872 UsageInfo &U = UsageMap[O];
8873 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
8874 addUsage(U, O, Use, UK_Use);
8875 }
8876
8877 void notePreMod(Object O, Expr *Mod) {
8878 UsageInfo &U = UsageMap[O];
8879 // Modifications conflict with other modifications and with uses.
8880 checkUsage(O, U, Mod, UK_ModAsValue, true);
8881 checkUsage(O, U, Mod, UK_Use, false);
8882 }
8883 void notePostMod(Object O, Expr *Use, UsageKind UK) {
8884 UsageInfo &U = UsageMap[O];
8885 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
8886 addUsage(U, O, Use, UK);
8887 }
8888
8889public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008890 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00008891 : Base(S.Context), SemaRef(S), Region(Tree.root()),
8892 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00008893 Visit(E);
8894 }
8895
8896 void VisitStmt(Stmt *S) {
8897 // Skip all statements which aren't expressions for now.
8898 }
8899
8900 void VisitExpr(Expr *E) {
8901 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00008902 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00008903 }
8904
8905 void VisitCastExpr(CastExpr *E) {
8906 Object O = Object();
8907 if (E->getCastKind() == CK_LValueToRValue)
8908 O = getObject(E->getSubExpr(), false);
8909
8910 if (O)
8911 notePreUse(O, E);
8912 VisitExpr(E);
8913 if (O)
8914 notePostUse(O, E);
8915 }
8916
8917 void VisitBinComma(BinaryOperator *BO) {
8918 // C++11 [expr.comma]p1:
8919 // Every value computation and side effect associated with the left
8920 // expression is sequenced before every value computation and side
8921 // effect associated with the right expression.
8922 SequenceTree::Seq LHS = Tree.allocate(Region);
8923 SequenceTree::Seq RHS = Tree.allocate(Region);
8924 SequenceTree::Seq OldRegion = Region;
8925
8926 {
8927 SequencedSubexpression SeqLHS(*this);
8928 Region = LHS;
8929 Visit(BO->getLHS());
8930 }
8931
8932 Region = RHS;
8933 Visit(BO->getRHS());
8934
8935 Region = OldRegion;
8936
8937 // Forget that LHS and RHS are sequenced. They are both unsequenced
8938 // with respect to other stuff.
8939 Tree.merge(LHS);
8940 Tree.merge(RHS);
8941 }
8942
8943 void VisitBinAssign(BinaryOperator *BO) {
8944 // The modification is sequenced after the value computation of the LHS
8945 // and RHS, so check it before inspecting the operands and update the
8946 // map afterwards.
8947 Object O = getObject(BO->getLHS(), true);
8948 if (!O)
8949 return VisitExpr(BO);
8950
8951 notePreMod(O, BO);
8952
8953 // C++11 [expr.ass]p7:
8954 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
8955 // only once.
8956 //
8957 // Therefore, for a compound assignment operator, O is considered used
8958 // everywhere except within the evaluation of E1 itself.
8959 if (isa<CompoundAssignOperator>(BO))
8960 notePreUse(O, BO);
8961
8962 Visit(BO->getLHS());
8963
8964 if (isa<CompoundAssignOperator>(BO))
8965 notePostUse(O, BO);
8966
8967 Visit(BO->getRHS());
8968
Richard Smith83e37bee2013-06-26 23:16:51 +00008969 // C++11 [expr.ass]p1:
8970 // the assignment is sequenced [...] before the value computation of the
8971 // assignment expression.
8972 // C11 6.5.16/3 has no such rule.
8973 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
8974 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00008975 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008976
Richard Smithc406cb72013-01-17 01:17:56 +00008977 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
8978 VisitBinAssign(CAO);
8979 }
8980
8981 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
8982 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
8983 void VisitUnaryPreIncDec(UnaryOperator *UO) {
8984 Object O = getObject(UO->getSubExpr(), true);
8985 if (!O)
8986 return VisitExpr(UO);
8987
8988 notePreMod(O, UO);
8989 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00008990 // C++11 [expr.pre.incr]p1:
8991 // the expression ++x is equivalent to x+=1
8992 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
8993 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00008994 }
8995
8996 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
8997 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
8998 void VisitUnaryPostIncDec(UnaryOperator *UO) {
8999 Object O = getObject(UO->getSubExpr(), true);
9000 if (!O)
9001 return VisitExpr(UO);
9002
9003 notePreMod(O, UO);
9004 Visit(UO->getSubExpr());
9005 notePostMod(O, UO, UK_ModAsSideEffect);
9006 }
9007
9008 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
9009 void VisitBinLOr(BinaryOperator *BO) {
9010 // The side-effects of the LHS of an '&&' are sequenced before the
9011 // value computation of the RHS, and hence before the value computation
9012 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
9013 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00009014 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00009015 {
9016 SequencedSubexpression Sequenced(*this);
9017 Visit(BO->getLHS());
9018 }
9019
9020 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00009021 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00009022 if (!Result)
9023 Visit(BO->getRHS());
9024 } else {
9025 // Check for unsequenced operations in the RHS, treating it as an
9026 // entirely separate evaluation.
9027 //
9028 // FIXME: If there are operations in the RHS which are unsequenced
9029 // with respect to operations outside the RHS, and those operations
9030 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00009031 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00009032 }
Richard Smithc406cb72013-01-17 01:17:56 +00009033 }
9034 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00009035 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00009036 {
9037 SequencedSubexpression Sequenced(*this);
9038 Visit(BO->getLHS());
9039 }
9040
9041 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00009042 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00009043 if (Result)
9044 Visit(BO->getRHS());
9045 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00009046 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00009047 }
Richard Smithc406cb72013-01-17 01:17:56 +00009048 }
9049
9050 // Only visit the condition, unless we can be sure which subexpression will
9051 // be chosen.
9052 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00009053 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00009054 {
9055 SequencedSubexpression Sequenced(*this);
9056 Visit(CO->getCond());
9057 }
Richard Smithc406cb72013-01-17 01:17:56 +00009058
9059 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00009060 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00009061 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00009062 else {
Richard Smithd33f5202013-01-17 23:18:09 +00009063 WorkList.push_back(CO->getTrueExpr());
9064 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00009065 }
Richard Smithc406cb72013-01-17 01:17:56 +00009066 }
9067
Richard Smithe3dbfe02013-06-30 10:40:20 +00009068 void VisitCallExpr(CallExpr *CE) {
9069 // C++11 [intro.execution]p15:
9070 // When calling a function [...], every value computation and side effect
9071 // associated with any argument expression, or with the postfix expression
9072 // designating the called function, is sequenced before execution of every
9073 // expression or statement in the body of the function [and thus before
9074 // the value computation of its result].
9075 SequencedSubexpression Sequenced(*this);
9076 Base::VisitCallExpr(CE);
9077
9078 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
9079 }
9080
Richard Smithc406cb72013-01-17 01:17:56 +00009081 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00009082 // This is a call, so all subexpressions are sequenced before the result.
9083 SequencedSubexpression Sequenced(*this);
9084
Richard Smithc406cb72013-01-17 01:17:56 +00009085 if (!CCE->isListInitialization())
9086 return VisitExpr(CCE);
9087
9088 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009089 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00009090 SequenceTree::Seq Parent = Region;
9091 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
9092 E = CCE->arg_end();
9093 I != E; ++I) {
9094 Region = Tree.allocate(Parent);
9095 Elts.push_back(Region);
9096 Visit(*I);
9097 }
9098
9099 // Forget that the initializers are sequenced.
9100 Region = Parent;
9101 for (unsigned I = 0; I < Elts.size(); ++I)
9102 Tree.merge(Elts[I]);
9103 }
9104
9105 void VisitInitListExpr(InitListExpr *ILE) {
9106 if (!SemaRef.getLangOpts().CPlusPlus11)
9107 return VisitExpr(ILE);
9108
9109 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009110 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00009111 SequenceTree::Seq Parent = Region;
9112 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
9113 Expr *E = ILE->getInit(I);
9114 if (!E) continue;
9115 Region = Tree.allocate(Parent);
9116 Elts.push_back(Region);
9117 Visit(E);
9118 }
9119
9120 // Forget that the initializers are sequenced.
9121 Region = Parent;
9122 for (unsigned I = 0; I < Elts.size(); ++I)
9123 Tree.merge(Elts[I]);
9124 }
9125};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009126} // end anonymous namespace
Richard Smithc406cb72013-01-17 01:17:56 +00009127
9128void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009129 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00009130 WorkList.push_back(E);
9131 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00009132 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00009133 SequenceChecker(*this, Item, WorkList);
9134 }
Richard Smithc406cb72013-01-17 01:17:56 +00009135}
9136
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009137void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
9138 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00009139 CheckImplicitConversions(E, CheckLoc);
9140 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009141 if (!IsConstexpr && !E->isValueDependent())
9142 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00009143}
9144
John McCall1f425642010-11-11 03:21:53 +00009145void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
9146 FieldDecl *BitField,
9147 Expr *Init) {
9148 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
9149}
9150
David Majnemer61a5bbf2015-04-07 22:08:51 +00009151static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
9152 SourceLocation Loc) {
9153 if (!PType->isVariablyModifiedType())
9154 return;
9155 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
9156 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
9157 return;
9158 }
David Majnemerdf8f73f2015-04-09 19:53:25 +00009159 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
9160 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
9161 return;
9162 }
David Majnemer61a5bbf2015-04-07 22:08:51 +00009163 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
9164 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
9165 return;
9166 }
9167
9168 const ArrayType *AT = S.Context.getAsArrayType(PType);
9169 if (!AT)
9170 return;
9171
9172 if (AT->getSizeModifier() != ArrayType::Star) {
9173 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
9174 return;
9175 }
9176
9177 S.Diag(Loc, diag::err_array_star_in_function_definition);
9178}
9179
Mike Stump0c2ec772010-01-21 03:59:47 +00009180/// CheckParmsForFunctionDef - Check that the parameters of the given
9181/// function are appropriate for the definition of a function. This
9182/// takes care of any checks that cannot be performed on the
9183/// declaration itself, e.g., that the types of each of the function
9184/// parameters are complete.
David Majnemer59f77922016-06-24 04:05:48 +00009185bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
Douglas Gregorb524d902010-11-01 18:37:59 +00009186 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00009187 bool HasInvalidParm = false;
David Majnemer59f77922016-06-24 04:05:48 +00009188 for (ParmVarDecl *Param : Parameters) {
Mike Stump0c2ec772010-01-21 03:59:47 +00009189 // C99 6.7.5.3p4: the parameters in a parameter type list in a
9190 // function declarator that is part of a function definition of
9191 // that function shall not have incomplete type.
9192 //
9193 // This is also C++ [dcl.fct]p6.
9194 if (!Param->isInvalidDecl() &&
9195 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00009196 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00009197 Param->setInvalidDecl();
9198 HasInvalidParm = true;
9199 }
9200
9201 // C99 6.9.1p5: If the declarator includes a parameter type list, the
9202 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00009203 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00009204 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00009205 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00009206 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00009207 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00009208
9209 // C99 6.7.5.3p12:
9210 // If the function declarator is not part of a definition of that
9211 // function, parameters may have incomplete type and may use the [*]
9212 // notation in their sequences of declarator specifiers to specify
9213 // variable length array types.
9214 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +00009215 // FIXME: This diagnostic should point the '[*]' if source-location
9216 // information is added for it.
9217 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00009218
9219 // MSVC destroys objects passed by value in the callee. Therefore a
9220 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00009221 // object's destructor. However, we don't perform any direct access check
9222 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00009223 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
9224 .getCXXABI()
9225 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00009226 if (!Param->isInvalidDecl()) {
9227 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
9228 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
9229 if (!ClassDecl->isInvalidDecl() &&
9230 !ClassDecl->hasIrrelevantDestructor() &&
9231 !ClassDecl->isDependentContext()) {
9232 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
9233 MarkFunctionReferenced(Param->getLocation(), Destructor);
9234 DiagnoseUseOfDecl(Destructor, Param->getLocation());
9235 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00009236 }
9237 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00009238 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009239
9240 // Parameters with the pass_object_size attribute only need to be marked
9241 // constant at function definitions. Because we lack information about
9242 // whether we're on a declaration or definition when we're instantiating the
9243 // attribute, we need to check for constness here.
9244 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
9245 if (!Param->getType().isConstQualified())
9246 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
9247 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +00009248 }
9249
9250 return HasInvalidParm;
9251}
John McCall2b5c1b22010-08-12 21:44:57 +00009252
9253/// CheckCastAlign - Implements -Wcast-align, which warns when a
9254/// pointer cast increases the alignment requirements.
9255void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
9256 // This is actually a lot of work to potentially be doing on every
9257 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009258 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00009259 return;
9260
9261 // Ignore dependent types.
9262 if (T->isDependentType() || Op->getType()->isDependentType())
9263 return;
9264
9265 // Require that the destination be a pointer type.
9266 const PointerType *DestPtr = T->getAs<PointerType>();
9267 if (!DestPtr) return;
9268
9269 // If the destination has alignment 1, we're done.
9270 QualType DestPointee = DestPtr->getPointeeType();
9271 if (DestPointee->isIncompleteType()) return;
9272 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
9273 if (DestAlign.isOne()) return;
9274
9275 // Require that the source be a pointer type.
9276 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
9277 if (!SrcPtr) return;
9278 QualType SrcPointee = SrcPtr->getPointeeType();
9279
9280 // Whitelist casts from cv void*. We already implicitly
9281 // whitelisted casts to cv void*, since they have alignment 1.
9282 // Also whitelist casts involving incomplete types, which implicitly
9283 // includes 'void'.
9284 if (SrcPointee->isIncompleteType()) return;
9285
9286 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
9287 if (SrcAlign >= DestAlign) return;
9288
9289 Diag(TRange.getBegin(), diag::warn_cast_align)
9290 << Op->getType() << T
9291 << static_cast<unsigned>(SrcAlign.getQuantity())
9292 << static_cast<unsigned>(DestAlign.getQuantity())
9293 << TRange << Op->getSourceRange();
9294}
9295
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009296static const Type* getElementType(const Expr *BaseExpr) {
9297 const Type* EltType = BaseExpr->getType().getTypePtr();
9298 if (EltType->isAnyPointerType())
9299 return EltType->getPointeeType().getTypePtr();
9300 else if (EltType->isArrayType())
9301 return EltType->getBaseElementTypeUnsafe();
9302 return EltType;
9303}
9304
Chandler Carruth28389f02011-08-05 09:10:50 +00009305/// \brief Check whether this array fits the idiom of a size-one tail padded
9306/// array member of a struct.
9307///
9308/// We avoid emitting out-of-bounds access warnings for such arrays as they are
9309/// commonly used to emulate flexible arrays in C89 code.
Benjamin Kramer7320b992016-06-15 14:20:56 +00009310static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
Chandler Carruth28389f02011-08-05 09:10:50 +00009311 const NamedDecl *ND) {
9312 if (Size != 1 || !ND) return false;
9313
9314 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
9315 if (!FD) return false;
9316
9317 // Don't consider sizes resulting from macro expansions or template argument
9318 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00009319
9320 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00009321 while (TInfo) {
9322 TypeLoc TL = TInfo->getTypeLoc();
9323 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00009324 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
9325 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00009326 TInfo = TDL->getTypeSourceInfo();
9327 continue;
9328 }
David Blaikie6adc78e2013-02-18 22:06:02 +00009329 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
9330 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00009331 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
9332 return false;
9333 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00009334 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00009335 }
Chandler Carruth28389f02011-08-05 09:10:50 +00009336
9337 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00009338 if (!RD) return false;
9339 if (RD->isUnion()) return false;
9340 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
9341 if (!CRD->isStandardLayout()) return false;
9342 }
Chandler Carruth28389f02011-08-05 09:10:50 +00009343
Benjamin Kramer8c543672011-08-06 03:04:42 +00009344 // See if this is the last field decl in the record.
9345 const Decl *D = FD;
9346 while ((D = D->getNextDeclInContext()))
9347 if (isa<FieldDecl>(D))
9348 return false;
9349 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00009350}
9351
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009352void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009353 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00009354 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009355 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009356 if (IndexExpr->isValueDependent())
9357 return;
9358
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00009359 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009360 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009361 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009362 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009363 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00009364 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00009365
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009366 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +00009367 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +00009368 return;
Richard Smith13f67182011-12-16 19:31:14 +00009369 if (IndexNegated)
9370 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00009371
Craig Topperc3ec1492014-05-26 06:22:03 +00009372 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00009373 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
9374 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00009375 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00009376 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00009377
Ted Kremeneke4b316c2011-02-23 23:06:04 +00009378 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00009379 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00009380 if (!size.isStrictlyPositive())
9381 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009382
9383 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00009384 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009385 // Make sure we're comparing apples to apples when comparing index to size
9386 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
9387 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00009388 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00009389 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009390 if (ptrarith_typesize != array_typesize) {
9391 // There's a cast to a different size type involved
9392 uint64_t ratio = array_typesize / ptrarith_typesize;
9393 // TODO: Be smarter about handling cases where array_typesize is not a
9394 // multiple of ptrarith_typesize
9395 if (ptrarith_typesize * ratio == array_typesize)
9396 size *= llvm::APInt(size.getBitWidth(), ratio);
9397 }
9398 }
9399
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009400 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009401 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00009402 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009403 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00009404
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009405 // For array subscripting the index must be less than size, but for pointer
9406 // arithmetic also allow the index (offset) to be equal to size since
9407 // computing the next address after the end of the array is legal and
9408 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009409 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00009410 return;
9411
9412 // Also don't warn for arrays of size 1 which are members of some
9413 // structure. These are often used to approximate flexible arrays in C89
9414 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009415 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00009416 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009417
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009418 // Suppress the warning if the subscript expression (as identified by the
9419 // ']' location) and the index expression are both from macro expansions
9420 // within a system header.
9421 if (ASE) {
9422 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
9423 ASE->getRBracketLoc());
9424 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
9425 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
9426 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00009427 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009428 return;
9429 }
9430 }
9431
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009432 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009433 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009434 DiagID = diag::warn_array_index_exceeds_bounds;
9435
9436 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
9437 PDiag(DiagID) << index.toString(10, true)
9438 << size.toString(10, true)
9439 << (unsigned)size.getLimitedValue(~0U)
9440 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009441 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009442 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009443 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009444 DiagID = diag::warn_ptr_arith_precedes_bounds;
9445 if (index.isNegative()) index = -index;
9446 }
9447
9448 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
9449 PDiag(DiagID) << index.toString(10, true)
9450 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00009451 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00009452
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00009453 if (!ND) {
9454 // Try harder to find a NamedDecl to point at in the note.
9455 while (const ArraySubscriptExpr *ASE =
9456 dyn_cast<ArraySubscriptExpr>(BaseExpr))
9457 BaseExpr = ASE->getBase()->IgnoreParenCasts();
9458 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
9459 ND = dyn_cast<NamedDecl>(DRE->getDecl());
9460 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
9461 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
9462 }
9463
Chandler Carruth1af88f12011-02-17 21:10:52 +00009464 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009465 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
9466 PDiag(diag::note_array_index_out_of_bounds)
9467 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00009468}
9469
Ted Kremenekdf26df72011-03-01 18:41:00 +00009470void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009471 int AllowOnePastEnd = 0;
9472 while (expr) {
9473 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00009474 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009475 case Stmt::ArraySubscriptExprClass: {
9476 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009477 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009478 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00009479 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009480 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +00009481 case Stmt::OMPArraySectionExprClass: {
9482 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
9483 if (ASE->getLowerBound())
9484 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
9485 /*ASE=*/nullptr, AllowOnePastEnd > 0);
9486 return;
9487 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009488 case Stmt::UnaryOperatorClass: {
9489 // Only unwrap the * and & unary operators
9490 const UnaryOperator *UO = cast<UnaryOperator>(expr);
9491 expr = UO->getSubExpr();
9492 switch (UO->getOpcode()) {
9493 case UO_AddrOf:
9494 AllowOnePastEnd++;
9495 break;
9496 case UO_Deref:
9497 AllowOnePastEnd--;
9498 break;
9499 default:
9500 return;
9501 }
9502 break;
9503 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00009504 case Stmt::ConditionalOperatorClass: {
9505 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
9506 if (const Expr *lhs = cond->getLHS())
9507 CheckArrayAccess(lhs);
9508 if (const Expr *rhs = cond->getRHS())
9509 CheckArrayAccess(rhs);
9510 return;
9511 }
9512 default:
9513 return;
9514 }
Peter Collingbourne91147592011-04-15 00:35:48 +00009515 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00009516}
John McCall31168b02011-06-15 23:02:42 +00009517
9518//===--- CHECK: Objective-C retain cycles ----------------------------------//
9519
9520namespace {
9521 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00009522 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00009523 VarDecl *Variable;
9524 SourceRange Range;
9525 SourceLocation Loc;
9526 bool Indirect;
9527
9528 void setLocsFrom(Expr *e) {
9529 Loc = e->getExprLoc();
9530 Range = e->getSourceRange();
9531 }
9532 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009533} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +00009534
9535/// Consider whether capturing the given variable can possibly lead to
9536/// a retain cycle.
9537static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00009538 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00009539 // lifetime. In MRR, it's captured strongly if the variable is
9540 // __block and has an appropriate type.
9541 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
9542 return false;
9543
9544 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009545 if (ref)
9546 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00009547 return true;
9548}
9549
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009550static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00009551 while (true) {
9552 e = e->IgnoreParens();
9553 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
9554 switch (cast->getCastKind()) {
9555 case CK_BitCast:
9556 case CK_LValueBitCast:
9557 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00009558 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00009559 e = cast->getSubExpr();
9560 continue;
9561
John McCall31168b02011-06-15 23:02:42 +00009562 default:
9563 return false;
9564 }
9565 }
9566
9567 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
9568 ObjCIvarDecl *ivar = ref->getDecl();
9569 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
9570 return false;
9571
9572 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009573 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00009574 return false;
9575
9576 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
9577 owner.Indirect = true;
9578 return true;
9579 }
9580
9581 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
9582 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
9583 if (!var) return false;
9584 return considerVariable(var, ref, owner);
9585 }
9586
John McCall31168b02011-06-15 23:02:42 +00009587 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
9588 if (member->isArrow()) return false;
9589
9590 // Don't count this as an indirect ownership.
9591 e = member->getBase();
9592 continue;
9593 }
9594
John McCallfe96e0b2011-11-06 09:01:30 +00009595 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
9596 // Only pay attention to pseudo-objects on property references.
9597 ObjCPropertyRefExpr *pre
9598 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
9599 ->IgnoreParens());
9600 if (!pre) return false;
9601 if (pre->isImplicitProperty()) return false;
9602 ObjCPropertyDecl *property = pre->getExplicitProperty();
9603 if (!property->isRetaining() &&
9604 !(property->getPropertyIvarDecl() &&
9605 property->getPropertyIvarDecl()->getType()
9606 .getObjCLifetime() == Qualifiers::OCL_Strong))
9607 return false;
9608
9609 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009610 if (pre->isSuperReceiver()) {
9611 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
9612 if (!owner.Variable)
9613 return false;
9614 owner.Loc = pre->getLocation();
9615 owner.Range = pre->getSourceRange();
9616 return true;
9617 }
John McCallfe96e0b2011-11-06 09:01:30 +00009618 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
9619 ->getSourceExpr());
9620 continue;
9621 }
9622
John McCall31168b02011-06-15 23:02:42 +00009623 // Array ivars?
9624
9625 return false;
9626 }
9627}
9628
9629namespace {
9630 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
9631 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
9632 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009633 Context(Context), Variable(variable), Capturer(nullptr),
9634 VarWillBeReased(false) {}
9635 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +00009636 VarDecl *Variable;
9637 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009638 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +00009639
9640 void VisitDeclRefExpr(DeclRefExpr *ref) {
9641 if (ref->getDecl() == Variable && !Capturer)
9642 Capturer = ref;
9643 }
9644
John McCall31168b02011-06-15 23:02:42 +00009645 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
9646 if (Capturer) return;
9647 Visit(ref->getBase());
9648 if (Capturer && ref->isFreeIvar())
9649 Capturer = ref;
9650 }
9651
9652 void VisitBlockExpr(BlockExpr *block) {
9653 // Look inside nested blocks
9654 if (block->getBlockDecl()->capturesVariable(Variable))
9655 Visit(block->getBlockDecl()->getBody());
9656 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00009657
9658 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
9659 if (Capturer) return;
9660 if (OVE->getSourceExpr())
9661 Visit(OVE->getSourceExpr());
9662 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009663 void VisitBinaryOperator(BinaryOperator *BinOp) {
9664 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
9665 return;
9666 Expr *LHS = BinOp->getLHS();
9667 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
9668 if (DRE->getDecl() != Variable)
9669 return;
9670 if (Expr *RHS = BinOp->getRHS()) {
9671 RHS = RHS->IgnoreParenCasts();
9672 llvm::APSInt Value;
9673 VarWillBeReased =
9674 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
9675 }
9676 }
9677 }
John McCall31168b02011-06-15 23:02:42 +00009678 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009679} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +00009680
9681/// Check whether the given argument is a block which captures a
9682/// variable.
9683static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
9684 assert(owner.Variable && owner.Loc.isValid());
9685
9686 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00009687
9688 // Look through [^{...} copy] and Block_copy(^{...}).
9689 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
9690 Selector Cmd = ME->getSelector();
9691 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
9692 e = ME->getInstanceReceiver();
9693 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +00009694 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +00009695 e = e->IgnoreParenCasts();
9696 }
9697 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
9698 if (CE->getNumArgs() == 1) {
9699 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00009700 if (Fn) {
9701 const IdentifierInfo *FnI = Fn->getIdentifier();
9702 if (FnI && FnI->isStr("_Block_copy")) {
9703 e = CE->getArg(0)->IgnoreParenCasts();
9704 }
9705 }
Jordan Rose67e887c2012-09-17 17:54:30 +00009706 }
9707 }
9708
John McCall31168b02011-06-15 23:02:42 +00009709 BlockExpr *block = dyn_cast<BlockExpr>(e);
9710 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +00009711 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00009712
9713 FindCaptureVisitor visitor(S.Context, owner.Variable);
9714 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009715 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +00009716}
9717
9718static void diagnoseRetainCycle(Sema &S, Expr *capturer,
9719 RetainCycleOwner &owner) {
9720 assert(capturer);
9721 assert(owner.Variable && owner.Loc.isValid());
9722
9723 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
9724 << owner.Variable << capturer->getSourceRange();
9725 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
9726 << owner.Indirect << owner.Range;
9727}
9728
9729/// Check for a keyword selector that starts with the word 'add' or
9730/// 'set'.
9731static bool isSetterLikeSelector(Selector sel) {
9732 if (sel.isUnarySelector()) return false;
9733
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009734 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00009735 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00009736 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00009737 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00009738 else if (str.startswith("add")) {
9739 // Specially whitelist 'addOperationWithBlock:'.
9740 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
9741 return false;
9742 str = str.substr(3);
9743 }
John McCall31168b02011-06-15 23:02:42 +00009744 else
9745 return false;
9746
9747 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00009748 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00009749}
9750
Benjamin Kramer3a743452015-03-09 15:03:32 +00009751static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
9752 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009753 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
9754 Message->getReceiverInterface(),
9755 NSAPI::ClassId_NSMutableArray);
9756 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009757 return None;
9758 }
9759
9760 Selector Sel = Message->getSelector();
9761
9762 Optional<NSAPI::NSArrayMethodKind> MKOpt =
9763 S.NSAPIObj->getNSArrayMethodKind(Sel);
9764 if (!MKOpt) {
9765 return None;
9766 }
9767
9768 NSAPI::NSArrayMethodKind MK = *MKOpt;
9769
9770 switch (MK) {
9771 case NSAPI::NSMutableArr_addObject:
9772 case NSAPI::NSMutableArr_insertObjectAtIndex:
9773 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
9774 return 0;
9775 case NSAPI::NSMutableArr_replaceObjectAtIndex:
9776 return 1;
9777
9778 default:
9779 return None;
9780 }
9781
9782 return None;
9783}
9784
9785static
9786Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
9787 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009788 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
9789 Message->getReceiverInterface(),
9790 NSAPI::ClassId_NSMutableDictionary);
9791 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009792 return None;
9793 }
9794
9795 Selector Sel = Message->getSelector();
9796
9797 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
9798 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
9799 if (!MKOpt) {
9800 return None;
9801 }
9802
9803 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
9804
9805 switch (MK) {
9806 case NSAPI::NSMutableDict_setObjectForKey:
9807 case NSAPI::NSMutableDict_setValueForKey:
9808 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
9809 return 0;
9810
9811 default:
9812 return None;
9813 }
9814
9815 return None;
9816}
9817
9818static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009819 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
9820 Message->getReceiverInterface(),
9821 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +00009822
Alex Denisov5dfac812015-08-06 04:51:14 +00009823 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
9824 Message->getReceiverInterface(),
9825 NSAPI::ClassId_NSMutableOrderedSet);
9826 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009827 return None;
9828 }
9829
9830 Selector Sel = Message->getSelector();
9831
9832 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
9833 if (!MKOpt) {
9834 return None;
9835 }
9836
9837 NSAPI::NSSetMethodKind MK = *MKOpt;
9838
9839 switch (MK) {
9840 case NSAPI::NSMutableSet_addObject:
9841 case NSAPI::NSOrderedSet_setObjectAtIndex:
9842 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
9843 case NSAPI::NSOrderedSet_insertObjectAtIndex:
9844 return 0;
9845 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
9846 return 1;
9847 }
9848
9849 return None;
9850}
9851
9852void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
9853 if (!Message->isInstanceMessage()) {
9854 return;
9855 }
9856
9857 Optional<int> ArgOpt;
9858
9859 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
9860 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
9861 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
9862 return;
9863 }
9864
9865 int ArgIndex = *ArgOpt;
9866
Alex Denisove1d882c2015-03-04 17:55:52 +00009867 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
9868 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
9869 Arg = OE->getSourceExpr()->IgnoreImpCasts();
9870 }
9871
Alex Denisov5dfac812015-08-06 04:51:14 +00009872 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009873 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009874 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009875 Diag(Message->getSourceRange().getBegin(),
9876 diag::warn_objc_circular_container)
Alex Denisov5dfac812015-08-06 04:51:14 +00009877 << ArgRE->getDecl()->getName() << StringRef("super");
Alex Denisove1d882c2015-03-04 17:55:52 +00009878 }
9879 }
Alex Denisov5dfac812015-08-06 04:51:14 +00009880 } else {
9881 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
9882
9883 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
9884 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
9885 }
9886
9887 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
9888 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
9889 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
9890 ValueDecl *Decl = ReceiverRE->getDecl();
9891 Diag(Message->getSourceRange().getBegin(),
9892 diag::warn_objc_circular_container)
9893 << Decl->getName() << Decl->getName();
9894 if (!ArgRE->isObjCSelfExpr()) {
9895 Diag(Decl->getLocation(),
9896 diag::note_objc_circular_container_declared_here)
9897 << Decl->getName();
9898 }
9899 }
9900 }
9901 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
9902 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
9903 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
9904 ObjCIvarDecl *Decl = IvarRE->getDecl();
9905 Diag(Message->getSourceRange().getBegin(),
9906 diag::warn_objc_circular_container)
9907 << Decl->getName() << Decl->getName();
9908 Diag(Decl->getLocation(),
9909 diag::note_objc_circular_container_declared_here)
9910 << Decl->getName();
9911 }
Alex Denisove1d882c2015-03-04 17:55:52 +00009912 }
9913 }
9914 }
Alex Denisove1d882c2015-03-04 17:55:52 +00009915}
9916
John McCall31168b02011-06-15 23:02:42 +00009917/// Check a message send to see if it's likely to cause a retain cycle.
9918void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
9919 // Only check instance methods whose selector looks like a setter.
9920 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
9921 return;
9922
9923 // Try to find a variable that the receiver is strongly owned by.
9924 RetainCycleOwner owner;
9925 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009926 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00009927 return;
9928 } else {
9929 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
9930 owner.Variable = getCurMethodDecl()->getSelfDecl();
9931 owner.Loc = msg->getSuperLoc();
9932 owner.Range = msg->getSuperLoc();
9933 }
9934
9935 // Check whether the receiver is captured by any of the arguments.
9936 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
9937 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
9938 return diagnoseRetainCycle(*this, capturer, owner);
9939}
9940
9941/// Check a property assign to see if it's likely to cause a retain cycle.
9942void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
9943 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009944 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00009945 return;
9946
9947 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
9948 diagnoseRetainCycle(*this, capturer, owner);
9949}
9950
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009951void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
9952 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +00009953 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009954 return;
9955
9956 // Because we don't have an expression for the variable, we have to set the
9957 // location explicitly here.
9958 Owner.Loc = Var->getLocation();
9959 Owner.Range = Var->getSourceRange();
9960
9961 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
9962 diagnoseRetainCycle(*this, Capturer, Owner);
9963}
9964
Ted Kremenek9304da92012-12-21 08:04:28 +00009965static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
9966 Expr *RHS, bool isProperty) {
9967 // Check if RHS is an Objective-C object literal, which also can get
9968 // immediately zapped in a weak reference. Note that we explicitly
9969 // allow ObjCStringLiterals, since those are designed to never really die.
9970 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009971
Ted Kremenek64873352012-12-21 22:46:35 +00009972 // This enum needs to match with the 'select' in
9973 // warn_objc_arc_literal_assign (off-by-1).
9974 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
9975 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
9976 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009977
9978 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00009979 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00009980 << (isProperty ? 0 : 1)
9981 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009982
9983 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00009984}
9985
Ted Kremenekc1f014a2012-12-21 19:45:30 +00009986static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
9987 Qualifiers::ObjCLifetime LT,
9988 Expr *RHS, bool isProperty) {
9989 // Strip off any implicit cast added to get to the one ARC-specific.
9990 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
9991 if (cast->getCastKind() == CK_ARCConsumeObject) {
9992 S.Diag(Loc, diag::warn_arc_retained_assign)
9993 << (LT == Qualifiers::OCL_ExplicitNone)
9994 << (isProperty ? 0 : 1)
9995 << RHS->getSourceRange();
9996 return true;
9997 }
9998 RHS = cast->getSubExpr();
9999 }
10000
10001 if (LT == Qualifiers::OCL_Weak &&
10002 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
10003 return true;
10004
10005 return false;
10006}
10007
Ted Kremenekb36234d2012-12-21 08:04:20 +000010008bool Sema::checkUnsafeAssigns(SourceLocation Loc,
10009 QualType LHS, Expr *RHS) {
10010 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
10011
10012 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
10013 return false;
10014
10015 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
10016 return true;
10017
10018 return false;
10019}
10020
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010021void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
10022 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010023 QualType LHSType;
10024 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +000010025 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010026 ObjCPropertyRefExpr *PRE
10027 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
10028 if (PRE && !PRE->isImplicitProperty()) {
10029 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
10030 if (PD)
10031 LHSType = PD->getType();
10032 }
10033
10034 if (LHSType.isNull())
10035 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +000010036
10037 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
10038
10039 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010040 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +000010041 getCurFunction()->markSafeWeakUse(LHS);
10042 }
10043
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010044 if (checkUnsafeAssigns(Loc, LHSType, RHS))
10045 return;
Jordan Rose657b5f42012-09-28 22:21:35 +000010046
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010047 // FIXME. Check for other life times.
10048 if (LT != Qualifiers::OCL_None)
10049 return;
10050
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010051 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010052 if (PRE->isImplicitProperty())
10053 return;
10054 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
10055 if (!PD)
10056 return;
10057
Bill Wendling44426052012-12-20 19:22:21 +000010058 unsigned Attributes = PD->getPropertyAttributes();
10059 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010060 // when 'assign' attribute was not explicitly specified
10061 // by user, ignore it and rely on property type itself
10062 // for lifetime info.
10063 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
10064 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
10065 LHSType->isObjCRetainableType())
10066 return;
10067
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010068 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +000010069 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010070 Diag(Loc, diag::warn_arc_retained_property_assign)
10071 << RHS->getSourceRange();
10072 return;
10073 }
10074 RHS = cast->getSubExpr();
10075 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010076 }
Bill Wendling44426052012-12-20 19:22:21 +000010077 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +000010078 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
10079 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +000010080 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010081 }
10082}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010083
10084//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
10085
10086namespace {
10087bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
10088 SourceLocation StmtLoc,
10089 const NullStmt *Body) {
10090 // Do not warn if the body is a macro that expands to nothing, e.g:
10091 //
10092 // #define CALL(x)
10093 // if (condition)
10094 // CALL(0);
10095 //
10096 if (Body->hasLeadingEmptyMacro())
10097 return false;
10098
10099 // Get line numbers of statement and body.
10100 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +000010101 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010102 &StmtLineInvalid);
10103 if (StmtLineInvalid)
10104 return false;
10105
10106 bool BodyLineInvalid;
10107 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
10108 &BodyLineInvalid);
10109 if (BodyLineInvalid)
10110 return false;
10111
10112 // Warn if null statement and body are on the same line.
10113 if (StmtLine != BodyLine)
10114 return false;
10115
10116 return true;
10117}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010118} // end anonymous namespace
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010119
10120void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
10121 const Stmt *Body,
10122 unsigned DiagID) {
10123 // Since this is a syntactic check, don't emit diagnostic for template
10124 // instantiations, this just adds noise.
10125 if (CurrentInstantiationScope)
10126 return;
10127
10128 // The body should be a null statement.
10129 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
10130 if (!NBody)
10131 return;
10132
10133 // Do the usual checks.
10134 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
10135 return;
10136
10137 Diag(NBody->getSemiLoc(), DiagID);
10138 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
10139}
10140
10141void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
10142 const Stmt *PossibleBody) {
10143 assert(!CurrentInstantiationScope); // Ensured by caller
10144
10145 SourceLocation StmtLoc;
10146 const Stmt *Body;
10147 unsigned DiagID;
10148 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
10149 StmtLoc = FS->getRParenLoc();
10150 Body = FS->getBody();
10151 DiagID = diag::warn_empty_for_body;
10152 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
10153 StmtLoc = WS->getCond()->getSourceRange().getEnd();
10154 Body = WS->getBody();
10155 DiagID = diag::warn_empty_while_body;
10156 } else
10157 return; // Neither `for' nor `while'.
10158
10159 // The body should be a null statement.
10160 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
10161 if (!NBody)
10162 return;
10163
10164 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010165 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010166 return;
10167
10168 // Do the usual checks.
10169 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
10170 return;
10171
10172 // `for(...);' and `while(...);' are popular idioms, so in order to keep
10173 // noise level low, emit diagnostics only if for/while is followed by a
10174 // CompoundStmt, e.g.:
10175 // for (int i = 0; i < n; i++);
10176 // {
10177 // a(i);
10178 // }
10179 // or if for/while is followed by a statement with more indentation
10180 // than for/while itself:
10181 // for (int i = 0; i < n; i++);
10182 // a(i);
10183 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
10184 if (!ProbableTypo) {
10185 bool BodyColInvalid;
10186 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
10187 PossibleBody->getLocStart(),
10188 &BodyColInvalid);
10189 if (BodyColInvalid)
10190 return;
10191
10192 bool StmtColInvalid;
10193 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
10194 S->getLocStart(),
10195 &StmtColInvalid);
10196 if (StmtColInvalid)
10197 return;
10198
10199 if (BodyCol > StmtCol)
10200 ProbableTypo = true;
10201 }
10202
10203 if (ProbableTypo) {
10204 Diag(NBody->getSemiLoc(), DiagID);
10205 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
10206 }
10207}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010208
Richard Trieu36d0b2b2015-01-13 02:32:02 +000010209//===--- CHECK: Warn on self move with std::move. -------------------------===//
10210
10211/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
10212void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
10213 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +000010214 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
10215 return;
10216
10217 if (!ActiveTemplateInstantiations.empty())
10218 return;
10219
10220 // Strip parens and casts away.
10221 LHSExpr = LHSExpr->IgnoreParenImpCasts();
10222 RHSExpr = RHSExpr->IgnoreParenImpCasts();
10223
10224 // Check for a call expression
10225 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
10226 if (!CE || CE->getNumArgs() != 1)
10227 return;
10228
10229 // Check for a call to std::move
10230 const FunctionDecl *FD = CE->getDirectCallee();
10231 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
10232 !FD->getIdentifier()->isStr("move"))
10233 return;
10234
10235 // Get argument from std::move
10236 RHSExpr = CE->getArg(0);
10237
10238 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
10239 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
10240
10241 // Two DeclRefExpr's, check that the decls are the same.
10242 if (LHSDeclRef && RHSDeclRef) {
10243 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
10244 return;
10245 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
10246 RHSDeclRef->getDecl()->getCanonicalDecl())
10247 return;
10248
10249 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10250 << LHSExpr->getSourceRange()
10251 << RHSExpr->getSourceRange();
10252 return;
10253 }
10254
10255 // Member variables require a different approach to check for self moves.
10256 // MemberExpr's are the same if every nested MemberExpr refers to the same
10257 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
10258 // the base Expr's are CXXThisExpr's.
10259 const Expr *LHSBase = LHSExpr;
10260 const Expr *RHSBase = RHSExpr;
10261 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
10262 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
10263 if (!LHSME || !RHSME)
10264 return;
10265
10266 while (LHSME && RHSME) {
10267 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
10268 RHSME->getMemberDecl()->getCanonicalDecl())
10269 return;
10270
10271 LHSBase = LHSME->getBase();
10272 RHSBase = RHSME->getBase();
10273 LHSME = dyn_cast<MemberExpr>(LHSBase);
10274 RHSME = dyn_cast<MemberExpr>(RHSBase);
10275 }
10276
10277 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
10278 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
10279 if (LHSDeclRef && RHSDeclRef) {
10280 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
10281 return;
10282 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
10283 RHSDeclRef->getDecl()->getCanonicalDecl())
10284 return;
10285
10286 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10287 << LHSExpr->getSourceRange()
10288 << RHSExpr->getSourceRange();
10289 return;
10290 }
10291
10292 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
10293 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10294 << LHSExpr->getSourceRange()
10295 << RHSExpr->getSourceRange();
10296}
10297
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010298//===--- Layout compatibility ----------------------------------------------//
10299
10300namespace {
10301
10302bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
10303
10304/// \brief Check if two enumeration types are layout-compatible.
10305bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
10306 // C++11 [dcl.enum] p8:
10307 // Two enumeration types are layout-compatible if they have the same
10308 // underlying type.
10309 return ED1->isComplete() && ED2->isComplete() &&
10310 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
10311}
10312
10313/// \brief Check if two fields are layout-compatible.
10314bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
10315 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
10316 return false;
10317
10318 if (Field1->isBitField() != Field2->isBitField())
10319 return false;
10320
10321 if (Field1->isBitField()) {
10322 // Make sure that the bit-fields are the same length.
10323 unsigned Bits1 = Field1->getBitWidthValue(C);
10324 unsigned Bits2 = Field2->getBitWidthValue(C);
10325
10326 if (Bits1 != Bits2)
10327 return false;
10328 }
10329
10330 return true;
10331}
10332
10333/// \brief Check if two standard-layout structs are layout-compatible.
10334/// (C++11 [class.mem] p17)
10335bool isLayoutCompatibleStruct(ASTContext &C,
10336 RecordDecl *RD1,
10337 RecordDecl *RD2) {
10338 // If both records are C++ classes, check that base classes match.
10339 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
10340 // If one of records is a CXXRecordDecl we are in C++ mode,
10341 // thus the other one is a CXXRecordDecl, too.
10342 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
10343 // Check number of base classes.
10344 if (D1CXX->getNumBases() != D2CXX->getNumBases())
10345 return false;
10346
10347 // Check the base classes.
10348 for (CXXRecordDecl::base_class_const_iterator
10349 Base1 = D1CXX->bases_begin(),
10350 BaseEnd1 = D1CXX->bases_end(),
10351 Base2 = D2CXX->bases_begin();
10352 Base1 != BaseEnd1;
10353 ++Base1, ++Base2) {
10354 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
10355 return false;
10356 }
10357 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
10358 // If only RD2 is a C++ class, it should have zero base classes.
10359 if (D2CXX->getNumBases() > 0)
10360 return false;
10361 }
10362
10363 // Check the fields.
10364 RecordDecl::field_iterator Field2 = RD2->field_begin(),
10365 Field2End = RD2->field_end(),
10366 Field1 = RD1->field_begin(),
10367 Field1End = RD1->field_end();
10368 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
10369 if (!isLayoutCompatible(C, *Field1, *Field2))
10370 return false;
10371 }
10372 if (Field1 != Field1End || Field2 != Field2End)
10373 return false;
10374
10375 return true;
10376}
10377
10378/// \brief Check if two standard-layout unions are layout-compatible.
10379/// (C++11 [class.mem] p18)
10380bool isLayoutCompatibleUnion(ASTContext &C,
10381 RecordDecl *RD1,
10382 RecordDecl *RD2) {
10383 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010384 for (auto *Field2 : RD2->fields())
10385 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010386
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010387 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010388 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
10389 I = UnmatchedFields.begin(),
10390 E = UnmatchedFields.end();
10391
10392 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010393 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010394 bool Result = UnmatchedFields.erase(*I);
10395 (void) Result;
10396 assert(Result);
10397 break;
10398 }
10399 }
10400 if (I == E)
10401 return false;
10402 }
10403
10404 return UnmatchedFields.empty();
10405}
10406
10407bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
10408 if (RD1->isUnion() != RD2->isUnion())
10409 return false;
10410
10411 if (RD1->isUnion())
10412 return isLayoutCompatibleUnion(C, RD1, RD2);
10413 else
10414 return isLayoutCompatibleStruct(C, RD1, RD2);
10415}
10416
10417/// \brief Check if two types are layout-compatible in C++11 sense.
10418bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
10419 if (T1.isNull() || T2.isNull())
10420 return false;
10421
10422 // C++11 [basic.types] p11:
10423 // If two types T1 and T2 are the same type, then T1 and T2 are
10424 // layout-compatible types.
10425 if (C.hasSameType(T1, T2))
10426 return true;
10427
10428 T1 = T1.getCanonicalType().getUnqualifiedType();
10429 T2 = T2.getCanonicalType().getUnqualifiedType();
10430
10431 const Type::TypeClass TC1 = T1->getTypeClass();
10432 const Type::TypeClass TC2 = T2->getTypeClass();
10433
10434 if (TC1 != TC2)
10435 return false;
10436
10437 if (TC1 == Type::Enum) {
10438 return isLayoutCompatible(C,
10439 cast<EnumType>(T1)->getDecl(),
10440 cast<EnumType>(T2)->getDecl());
10441 } else if (TC1 == Type::Record) {
10442 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
10443 return false;
10444
10445 return isLayoutCompatible(C,
10446 cast<RecordType>(T1)->getDecl(),
10447 cast<RecordType>(T2)->getDecl());
10448 }
10449
10450 return false;
10451}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010452} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010453
10454//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
10455
10456namespace {
10457/// \brief Given a type tag expression find the type tag itself.
10458///
10459/// \param TypeExpr Type tag expression, as it appears in user's code.
10460///
10461/// \param VD Declaration of an identifier that appears in a type tag.
10462///
10463/// \param MagicValue Type tag magic value.
10464bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
10465 const ValueDecl **VD, uint64_t *MagicValue) {
10466 while(true) {
10467 if (!TypeExpr)
10468 return false;
10469
10470 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
10471
10472 switch (TypeExpr->getStmtClass()) {
10473 case Stmt::UnaryOperatorClass: {
10474 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
10475 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
10476 TypeExpr = UO->getSubExpr();
10477 continue;
10478 }
10479 return false;
10480 }
10481
10482 case Stmt::DeclRefExprClass: {
10483 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
10484 *VD = DRE->getDecl();
10485 return true;
10486 }
10487
10488 case Stmt::IntegerLiteralClass: {
10489 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
10490 llvm::APInt MagicValueAPInt = IL->getValue();
10491 if (MagicValueAPInt.getActiveBits() <= 64) {
10492 *MagicValue = MagicValueAPInt.getZExtValue();
10493 return true;
10494 } else
10495 return false;
10496 }
10497
10498 case Stmt::BinaryConditionalOperatorClass:
10499 case Stmt::ConditionalOperatorClass: {
10500 const AbstractConditionalOperator *ACO =
10501 cast<AbstractConditionalOperator>(TypeExpr);
10502 bool Result;
10503 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
10504 if (Result)
10505 TypeExpr = ACO->getTrueExpr();
10506 else
10507 TypeExpr = ACO->getFalseExpr();
10508 continue;
10509 }
10510 return false;
10511 }
10512
10513 case Stmt::BinaryOperatorClass: {
10514 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
10515 if (BO->getOpcode() == BO_Comma) {
10516 TypeExpr = BO->getRHS();
10517 continue;
10518 }
10519 return false;
10520 }
10521
10522 default:
10523 return false;
10524 }
10525 }
10526}
10527
10528/// \brief Retrieve the C type corresponding to type tag TypeExpr.
10529///
10530/// \param TypeExpr Expression that specifies a type tag.
10531///
10532/// \param MagicValues Registered magic values.
10533///
10534/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
10535/// kind.
10536///
10537/// \param TypeInfo Information about the corresponding C type.
10538///
10539/// \returns true if the corresponding C type was found.
10540bool GetMatchingCType(
10541 const IdentifierInfo *ArgumentKind,
10542 const Expr *TypeExpr, const ASTContext &Ctx,
10543 const llvm::DenseMap<Sema::TypeTagMagicValue,
10544 Sema::TypeTagData> *MagicValues,
10545 bool &FoundWrongKind,
10546 Sema::TypeTagData &TypeInfo) {
10547 FoundWrongKind = false;
10548
10549 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000010550 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010551
10552 uint64_t MagicValue;
10553
10554 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
10555 return false;
10556
10557 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000010558 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010559 if (I->getArgumentKind() != ArgumentKind) {
10560 FoundWrongKind = true;
10561 return false;
10562 }
10563 TypeInfo.Type = I->getMatchingCType();
10564 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
10565 TypeInfo.MustBeNull = I->getMustBeNull();
10566 return true;
10567 }
10568 return false;
10569 }
10570
10571 if (!MagicValues)
10572 return false;
10573
10574 llvm::DenseMap<Sema::TypeTagMagicValue,
10575 Sema::TypeTagData>::const_iterator I =
10576 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
10577 if (I == MagicValues->end())
10578 return false;
10579
10580 TypeInfo = I->second;
10581 return true;
10582}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010583} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010584
10585void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
10586 uint64_t MagicValue, QualType Type,
10587 bool LayoutCompatible,
10588 bool MustBeNull) {
10589 if (!TypeTagForDatatypeMagicValues)
10590 TypeTagForDatatypeMagicValues.reset(
10591 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
10592
10593 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
10594 (*TypeTagForDatatypeMagicValues)[Magic] =
10595 TypeTagData(Type, LayoutCompatible, MustBeNull);
10596}
10597
10598namespace {
10599bool IsSameCharType(QualType T1, QualType T2) {
10600 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
10601 if (!BT1)
10602 return false;
10603
10604 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
10605 if (!BT2)
10606 return false;
10607
10608 BuiltinType::Kind T1Kind = BT1->getKind();
10609 BuiltinType::Kind T2Kind = BT2->getKind();
10610
10611 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
10612 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
10613 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
10614 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
10615}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010616} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010617
10618void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
10619 const Expr * const *ExprArgs) {
10620 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
10621 bool IsPointerAttr = Attr->getIsPointer();
10622
10623 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
10624 bool FoundWrongKind;
10625 TypeTagData TypeInfo;
10626 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
10627 TypeTagForDatatypeMagicValues.get(),
10628 FoundWrongKind, TypeInfo)) {
10629 if (FoundWrongKind)
10630 Diag(TypeTagExpr->getExprLoc(),
10631 diag::warn_type_tag_for_datatype_wrong_kind)
10632 << TypeTagExpr->getSourceRange();
10633 return;
10634 }
10635
10636 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
10637 if (IsPointerAttr) {
10638 // Skip implicit cast of pointer to `void *' (as a function argument).
10639 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000010640 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000010641 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010642 ArgumentExpr = ICE->getSubExpr();
10643 }
10644 QualType ArgumentType = ArgumentExpr->getType();
10645
10646 // Passing a `void*' pointer shouldn't trigger a warning.
10647 if (IsPointerAttr && ArgumentType->isVoidPointerType())
10648 return;
10649
10650 if (TypeInfo.MustBeNull) {
10651 // Type tag with matching void type requires a null pointer.
10652 if (!ArgumentExpr->isNullPointerConstant(Context,
10653 Expr::NPC_ValueDependentIsNotNull)) {
10654 Diag(ArgumentExpr->getExprLoc(),
10655 diag::warn_type_safety_null_pointer_required)
10656 << ArgumentKind->getName()
10657 << ArgumentExpr->getSourceRange()
10658 << TypeTagExpr->getSourceRange();
10659 }
10660 return;
10661 }
10662
10663 QualType RequiredType = TypeInfo.Type;
10664 if (IsPointerAttr)
10665 RequiredType = Context.getPointerType(RequiredType);
10666
10667 bool mismatch = false;
10668 if (!TypeInfo.LayoutCompatible) {
10669 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
10670
10671 // C++11 [basic.fundamental] p1:
10672 // Plain char, signed char, and unsigned char are three distinct types.
10673 //
10674 // But we treat plain `char' as equivalent to `signed char' or `unsigned
10675 // char' depending on the current char signedness mode.
10676 if (mismatch)
10677 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
10678 RequiredType->getPointeeType())) ||
10679 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
10680 mismatch = false;
10681 } else
10682 if (IsPointerAttr)
10683 mismatch = !isLayoutCompatible(Context,
10684 ArgumentType->getPointeeType(),
10685 RequiredType->getPointeeType());
10686 else
10687 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
10688
10689 if (mismatch)
10690 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000010691 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010692 << TypeInfo.LayoutCompatible << RequiredType
10693 << ArgumentExpr->getSourceRange()
10694 << TypeTagExpr->getSourceRange();
10695}