blob: dc91b93f202be970f9c01307afb11be98531651e [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
John McCalldadc5752010-08-24 06:29:42 +0000458ExprResult
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000459Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
460 CallExpr *TheCall) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000461 ExprResult TheCallResult(TheCall);
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000462
Chris Lattner3be167f2010-10-01 23:23:24 +0000463 // Find out if any arguments are required to be integer constant expressions.
464 unsigned ICEArguments = 0;
465 ASTContext::GetBuiltinTypeError Error;
466 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
467 if (Error != ASTContext::GE_None)
468 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
469
470 // If any arguments are required to be ICE's, check and diagnose.
471 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
472 // Skip arguments not required to be ICE's.
473 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
474
475 llvm::APSInt Result;
476 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
477 return true;
478 ICEArguments &= ~(1 << ArgNo);
479 }
480
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000481 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000482 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000483 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000484 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000485 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000486 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000487 break;
Ted Kremeneka174c522008-07-09 17:58:53 +0000488 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000489 case Builtin::BI__builtin_va_start:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000490 if (SemaBuiltinVAStart(TheCall))
491 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000492 break;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000493 case Builtin::BI__va_start: {
494 switch (Context.getTargetInfo().getTriple().getArch()) {
495 case llvm::Triple::arm:
496 case llvm::Triple::thumb:
497 if (SemaBuiltinVAStartARM(TheCall))
498 return ExprError();
499 break;
500 default:
501 if (SemaBuiltinVAStart(TheCall))
502 return ExprError();
503 break;
504 }
505 break;
506 }
Chris Lattner2da14fb2007-12-20 00:26:33 +0000507 case Builtin::BI__builtin_isgreater:
508 case Builtin::BI__builtin_isgreaterequal:
509 case Builtin::BI__builtin_isless:
510 case Builtin::BI__builtin_islessequal:
511 case Builtin::BI__builtin_islessgreater:
512 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000513 if (SemaBuiltinUnorderedCompare(TheCall))
514 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000515 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000516 case Builtin::BI__builtin_fpclassify:
517 if (SemaBuiltinFPClassification(TheCall, 6))
518 return ExprError();
519 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000520 case Builtin::BI__builtin_isfinite:
521 case Builtin::BI__builtin_isinf:
522 case Builtin::BI__builtin_isinf_sign:
523 case Builtin::BI__builtin_isnan:
524 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000525 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000526 return ExprError();
527 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000528 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000529 return SemaBuiltinShuffleVector(TheCall);
530 // TheCall will be freed by the smart pointer here, but that's fine, since
531 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000532 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000533 if (SemaBuiltinPrefetch(TheCall))
534 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000535 break;
Hal Finkelf0417332014-07-17 14:25:55 +0000536 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +0000537 case Builtin::BI__builtin_assume:
Hal Finkelf0417332014-07-17 14:25:55 +0000538 if (SemaBuiltinAssume(TheCall))
539 return ExprError();
540 break;
Hal Finkelbcc06082014-09-07 22:58:14 +0000541 case Builtin::BI__builtin_assume_aligned:
542 if (SemaBuiltinAssumeAligned(TheCall))
543 return ExprError();
544 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000545 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000546 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000547 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000548 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000549 case Builtin::BI__builtin_longjmp:
550 if (SemaBuiltinLongjmp(TheCall))
551 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000552 break;
Joerg Sonnenberger27173282015-03-11 23:46:32 +0000553 case Builtin::BI__builtin_setjmp:
554 if (SemaBuiltinSetjmp(TheCall))
555 return ExprError();
556 break;
David Majnemerc403a1c2015-03-20 17:03:35 +0000557 case Builtin::BI_setjmp:
558 case Builtin::BI_setjmpex:
559 if (checkArgCount(*this, TheCall, 1))
560 return true;
561 break;
John McCallbebede42011-02-26 05:39:39 +0000562
563 case Builtin::BI__builtin_classify_type:
564 if (checkArgCount(*this, TheCall, 1)) return true;
565 TheCall->setType(Context.IntTy);
566 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000567 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000568 if (checkArgCount(*this, TheCall, 1)) return true;
569 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000570 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000571 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000572 case Builtin::BI__sync_fetch_and_add_1:
573 case Builtin::BI__sync_fetch_and_add_2:
574 case Builtin::BI__sync_fetch_and_add_4:
575 case Builtin::BI__sync_fetch_and_add_8:
576 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000577 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000578 case Builtin::BI__sync_fetch_and_sub_1:
579 case Builtin::BI__sync_fetch_and_sub_2:
580 case Builtin::BI__sync_fetch_and_sub_4:
581 case Builtin::BI__sync_fetch_and_sub_8:
582 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000583 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000584 case Builtin::BI__sync_fetch_and_or_1:
585 case Builtin::BI__sync_fetch_and_or_2:
586 case Builtin::BI__sync_fetch_and_or_4:
587 case Builtin::BI__sync_fetch_and_or_8:
588 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000589 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000590 case Builtin::BI__sync_fetch_and_and_1:
591 case Builtin::BI__sync_fetch_and_and_2:
592 case Builtin::BI__sync_fetch_and_and_4:
593 case Builtin::BI__sync_fetch_and_and_8:
594 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000595 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000596 case Builtin::BI__sync_fetch_and_xor_1:
597 case Builtin::BI__sync_fetch_and_xor_2:
598 case Builtin::BI__sync_fetch_and_xor_4:
599 case Builtin::BI__sync_fetch_and_xor_8:
600 case Builtin::BI__sync_fetch_and_xor_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000601 case Builtin::BI__sync_fetch_and_nand:
602 case Builtin::BI__sync_fetch_and_nand_1:
603 case Builtin::BI__sync_fetch_and_nand_2:
604 case Builtin::BI__sync_fetch_and_nand_4:
605 case Builtin::BI__sync_fetch_and_nand_8:
606 case Builtin::BI__sync_fetch_and_nand_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000607 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000608 case Builtin::BI__sync_add_and_fetch_1:
609 case Builtin::BI__sync_add_and_fetch_2:
610 case Builtin::BI__sync_add_and_fetch_4:
611 case Builtin::BI__sync_add_and_fetch_8:
612 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000613 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000614 case Builtin::BI__sync_sub_and_fetch_1:
615 case Builtin::BI__sync_sub_and_fetch_2:
616 case Builtin::BI__sync_sub_and_fetch_4:
617 case Builtin::BI__sync_sub_and_fetch_8:
618 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000619 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000620 case Builtin::BI__sync_and_and_fetch_1:
621 case Builtin::BI__sync_and_and_fetch_2:
622 case Builtin::BI__sync_and_and_fetch_4:
623 case Builtin::BI__sync_and_and_fetch_8:
624 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000625 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000626 case Builtin::BI__sync_or_and_fetch_1:
627 case Builtin::BI__sync_or_and_fetch_2:
628 case Builtin::BI__sync_or_and_fetch_4:
629 case Builtin::BI__sync_or_and_fetch_8:
630 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000631 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000632 case Builtin::BI__sync_xor_and_fetch_1:
633 case Builtin::BI__sync_xor_and_fetch_2:
634 case Builtin::BI__sync_xor_and_fetch_4:
635 case Builtin::BI__sync_xor_and_fetch_8:
636 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000637 case Builtin::BI__sync_nand_and_fetch:
638 case Builtin::BI__sync_nand_and_fetch_1:
639 case Builtin::BI__sync_nand_and_fetch_2:
640 case Builtin::BI__sync_nand_and_fetch_4:
641 case Builtin::BI__sync_nand_and_fetch_8:
642 case Builtin::BI__sync_nand_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000643 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000644 case Builtin::BI__sync_val_compare_and_swap_1:
645 case Builtin::BI__sync_val_compare_and_swap_2:
646 case Builtin::BI__sync_val_compare_and_swap_4:
647 case Builtin::BI__sync_val_compare_and_swap_8:
648 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000649 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000650 case Builtin::BI__sync_bool_compare_and_swap_1:
651 case Builtin::BI__sync_bool_compare_and_swap_2:
652 case Builtin::BI__sync_bool_compare_and_swap_4:
653 case Builtin::BI__sync_bool_compare_and_swap_8:
654 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000655 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000656 case Builtin::BI__sync_lock_test_and_set_1:
657 case Builtin::BI__sync_lock_test_and_set_2:
658 case Builtin::BI__sync_lock_test_and_set_4:
659 case Builtin::BI__sync_lock_test_and_set_8:
660 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000661 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000662 case Builtin::BI__sync_lock_release_1:
663 case Builtin::BI__sync_lock_release_2:
664 case Builtin::BI__sync_lock_release_4:
665 case Builtin::BI__sync_lock_release_8:
666 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000667 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000668 case Builtin::BI__sync_swap_1:
669 case Builtin::BI__sync_swap_2:
670 case Builtin::BI__sync_swap_4:
671 case Builtin::BI__sync_swap_8:
672 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000673 return SemaBuiltinAtomicOverloaded(TheCallResult);
Michael Zolotukhin84df1232015-09-08 23:52:33 +0000674 case Builtin::BI__builtin_nontemporal_load:
675 case Builtin::BI__builtin_nontemporal_store:
676 return SemaBuiltinNontemporalOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +0000677#define BUILTIN(ID, TYPE, ATTRS)
678#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
679 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000680 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +0000681#include "clang/Basic/Builtins.def"
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000682 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000683 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000684 return ExprError();
685 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +0000686 case Builtin::BI__builtin_addressof:
687 if (SemaBuiltinAddressof(*this, TheCall))
688 return ExprError();
689 break;
John McCall03107a42015-10-29 20:48:01 +0000690 case Builtin::BI__builtin_add_overflow:
691 case Builtin::BI__builtin_sub_overflow:
692 case Builtin::BI__builtin_mul_overflow:
Craig Toppera86e70d2015-11-07 06:16:14 +0000693 if (SemaBuiltinOverflow(*this, TheCall))
694 return ExprError();
695 break;
Richard Smith760520b2014-06-03 23:27:44 +0000696 case Builtin::BI__builtin_operator_new:
697 case Builtin::BI__builtin_operator_delete:
698 if (!getLangOpts().CPlusPlus) {
699 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
700 << (BuiltinID == Builtin::BI__builtin_operator_new
701 ? "__builtin_operator_new"
702 : "__builtin_operator_delete")
703 << "C++";
704 return ExprError();
705 }
706 // CodeGen assumes it can find the global new and delete to call,
707 // so ensure that they are declared.
708 DeclareGlobalNewDelete();
709 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000710
711 // check secure string manipulation functions where overflows
712 // are detectable at compile time
713 case Builtin::BI__builtin___memcpy_chk:
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000714 case Builtin::BI__builtin___memmove_chk:
715 case Builtin::BI__builtin___memset_chk:
716 case Builtin::BI__builtin___strlcat_chk:
717 case Builtin::BI__builtin___strlcpy_chk:
718 case Builtin::BI__builtin___strncat_chk:
719 case Builtin::BI__builtin___strncpy_chk:
720 case Builtin::BI__builtin___stpncpy_chk:
721 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
722 break;
Steven Wu566c14e2014-09-24 04:37:33 +0000723 case Builtin::BI__builtin___memccpy_chk:
724 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
725 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000726 case Builtin::BI__builtin___snprintf_chk:
727 case Builtin::BI__builtin___vsnprintf_chk:
728 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
729 break;
Peter Collingbournef7706832014-12-12 23:41:25 +0000730 case Builtin::BI__builtin_call_with_static_chain:
731 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
732 return ExprError();
733 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000734 case Builtin::BI__exception_code:
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000735 case Builtin::BI_exception_code:
Reid Kleckner1d59f992015-01-22 01:36:17 +0000736 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
737 diag::err_seh___except_block))
738 return ExprError();
739 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000740 case Builtin::BI__exception_info:
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000741 case Builtin::BI_exception_info:
Reid Kleckner1d59f992015-01-22 01:36:17 +0000742 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
743 diag::err_seh___except_filter))
744 return ExprError();
745 break;
David Majnemerba3e5ec2015-03-13 18:26:17 +0000746 case Builtin::BI__GetExceptionInfo:
747 if (checkArgCount(*this, TheCall, 1))
748 return ExprError();
749
750 if (CheckCXXThrowOperand(
751 TheCall->getLocStart(),
752 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
753 TheCall))
754 return ExprError();
755
756 TheCall->setType(Context.VoidPtrTy);
757 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000758 case Builtin::BIread_pipe:
759 case Builtin::BIwrite_pipe:
760 // Since those two functions are declared with var args, we need a semantic
761 // check for the argument.
762 if (SemaBuiltinRWPipe(*this, TheCall))
763 return ExprError();
764 break;
765 case Builtin::BIreserve_read_pipe:
766 case Builtin::BIreserve_write_pipe:
767 case Builtin::BIwork_group_reserve_read_pipe:
768 case Builtin::BIwork_group_reserve_write_pipe:
769 case Builtin::BIsub_group_reserve_read_pipe:
770 case Builtin::BIsub_group_reserve_write_pipe:
771 if (SemaBuiltinReserveRWPipe(*this, TheCall))
772 return ExprError();
773 // Since return type of reserve_read/write_pipe built-in function is
774 // reserve_id_t, which is not defined in the builtin def file , we used int
775 // as return type and need to override the return type of these functions.
776 TheCall->setType(Context.OCLReserveIDTy);
777 break;
778 case Builtin::BIcommit_read_pipe:
779 case Builtin::BIcommit_write_pipe:
780 case Builtin::BIwork_group_commit_read_pipe:
781 case Builtin::BIwork_group_commit_write_pipe:
782 case Builtin::BIsub_group_commit_read_pipe:
783 case Builtin::BIsub_group_commit_write_pipe:
784 if (SemaBuiltinCommitRWPipe(*this, TheCall))
785 return ExprError();
786 break;
787 case Builtin::BIget_pipe_num_packets:
788 case Builtin::BIget_pipe_max_packets:
789 if (SemaBuiltinPipePackets(*this, TheCall))
790 return ExprError();
791 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000792 }
Richard Smith760520b2014-06-03 23:27:44 +0000793
Nate Begeman4904e322010-06-08 02:47:44 +0000794 // Since the target specific builtins for each arch overlap, only check those
795 // of the arch we are compiling for.
Artem Belevich9674a642015-09-22 17:23:05 +0000796 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000797 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +0000798 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000799 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000800 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000801 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000802 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
803 return ExprError();
804 break;
Tim Northover25e8a672014-05-24 12:51:25 +0000805 case llvm::Triple::aarch64:
806 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +0000807 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +0000808 return ExprError();
809 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000810 case llvm::Triple::mips:
811 case llvm::Triple::mipsel:
812 case llvm::Triple::mips64:
813 case llvm::Triple::mips64el:
814 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
815 return ExprError();
816 break;
Ulrich Weigand3a610eb2015-04-01 12:54:25 +0000817 case llvm::Triple::systemz:
818 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
819 return ExprError();
820 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000821 case llvm::Triple::x86:
822 case llvm::Triple::x86_64:
823 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
824 return ExprError();
825 break;
Kit Bartone50adcb2015-03-30 19:40:59 +0000826 case llvm::Triple::ppc:
827 case llvm::Triple::ppc64:
828 case llvm::Triple::ppc64le:
829 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
830 return ExprError();
831 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000832 default:
833 break;
834 }
835 }
836
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000837 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +0000838}
839
Nate Begeman91e1fea2010-06-14 05:21:25 +0000840// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +0000841static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +0000842 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +0000843 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +0000844 switch (Type.getEltType()) {
845 case NeonTypeFlags::Int8:
846 case NeonTypeFlags::Poly8:
847 return shift ? 7 : (8 << IsQuad) - 1;
848 case NeonTypeFlags::Int16:
849 case NeonTypeFlags::Poly16:
850 return shift ? 15 : (4 << IsQuad) - 1;
851 case NeonTypeFlags::Int32:
852 return shift ? 31 : (2 << IsQuad) - 1;
853 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +0000854 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +0000855 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000856 case NeonTypeFlags::Poly128:
857 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +0000858 case NeonTypeFlags::Float16:
859 assert(!shift && "cannot shift float types!");
860 return (4 << IsQuad) - 1;
861 case NeonTypeFlags::Float32:
862 assert(!shift && "cannot shift float types!");
863 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000864 case NeonTypeFlags::Float64:
865 assert(!shift && "cannot shift float types!");
866 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000867 }
David Blaikie8a40f702012-01-17 06:56:22 +0000868 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +0000869}
870
Bob Wilsone4d77232011-11-08 05:04:11 +0000871/// getNeonEltType - Return the QualType corresponding to the elements of
872/// the vector type specified by the NeonTypeFlags. This is used to check
873/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +0000874static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +0000875 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +0000876 switch (Flags.getEltType()) {
877 case NeonTypeFlags::Int8:
878 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
879 case NeonTypeFlags::Int16:
880 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
881 case NeonTypeFlags::Int32:
882 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
883 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +0000884 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +0000885 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
886 else
887 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
888 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000889 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +0000890 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000891 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +0000892 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +0000893 case NeonTypeFlags::Poly64:
Kevin Qin78b86532015-05-14 08:18:05 +0000894 if (IsInt64Long)
895 return Context.UnsignedLongTy;
896 else
897 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000898 case NeonTypeFlags::Poly128:
899 break;
Bob Wilsone4d77232011-11-08 05:04:11 +0000900 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +0000901 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000902 case NeonTypeFlags::Float32:
903 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +0000904 case NeonTypeFlags::Float64:
905 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000906 }
David Blaikie8a40f702012-01-17 06:56:22 +0000907 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +0000908}
909
Tim Northover12670412014-02-19 10:37:05 +0000910bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +0000911 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +0000912 uint64_t mask = 0;
913 unsigned TV = 0;
914 int PtrArgNum = -1;
915 bool HasConstPtr = false;
916 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +0000917#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000918#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000919#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000920 }
921
922 // For NEON intrinsics which are overloaded on vector element type, validate
923 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +0000924 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000925 if (mask) {
926 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
927 return true;
928
929 TV = Result.getLimitedValue(64);
930 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
931 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +0000932 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +0000933 }
934
935 if (PtrArgNum >= 0) {
936 // Check that pointer arguments have the specified type.
937 Expr *Arg = TheCall->getArg(PtrArgNum);
938 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
939 Arg = ICE->getSubExpr();
940 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
941 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +0000942
Tim Northovera2ee4332014-03-29 15:09:45 +0000943 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Tim Northover40956e62014-07-23 12:32:58 +0000944 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
Tim Northovera2ee4332014-03-29 15:09:45 +0000945 bool IsInt64Long =
946 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
947 QualType EltTy =
948 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +0000949 if (HasConstPtr)
950 EltTy = EltTy.withConst();
951 QualType LHSTy = Context.getPointerType(EltTy);
952 AssignConvertType ConvTy;
953 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
954 if (RHS.isInvalid())
955 return true;
956 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
957 RHS.get(), AA_Assigning))
958 return true;
959 }
960
961 // For NEON intrinsics which take an immediate value as part of the
962 // instruction, range check them here.
963 unsigned i = 0, l = 0, u = 0;
964 switch (BuiltinID) {
965 default:
966 return false;
Tim Northover12670412014-02-19 10:37:05 +0000967#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000968#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000969#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000970 }
Tim Northover2fe823a2013-08-01 09:23:19 +0000971
Richard Sandiford28940af2014-04-16 08:47:51 +0000972 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +0000973}
974
Tim Northovera2ee4332014-03-29 15:09:45 +0000975bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
976 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +0000977 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000978 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +0000979 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000980 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +0000981 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000982 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
983 BuiltinID == AArch64::BI__builtin_arm_strex ||
984 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +0000985 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +0000986 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000987 BuiltinID == ARM::BI__builtin_arm_ldaex ||
988 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
989 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +0000990
991 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
992
993 // Ensure that we have the proper number of arguments.
994 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
995 return true;
996
997 // Inspect the pointer argument of the atomic builtin. This should always be
998 // a pointer type, whose element is an integral scalar or pointer type.
999 // Because it is a pointer type, we don't have to worry about any implicit
1000 // casts here.
1001 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1002 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1003 if (PointerArgRes.isInvalid())
1004 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001005 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001006
1007 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1008 if (!pointerType) {
1009 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1010 << PointerArg->getType() << PointerArg->getSourceRange();
1011 return true;
1012 }
1013
1014 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1015 // task is to insert the appropriate casts into the AST. First work out just
1016 // what the appropriate type is.
1017 QualType ValType = pointerType->getPointeeType();
1018 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1019 if (IsLdrex)
1020 AddrType.addConst();
1021
1022 // Issue a warning if the cast is dodgy.
1023 CastKind CastNeeded = CK_NoOp;
1024 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1025 CastNeeded = CK_BitCast;
1026 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1027 << PointerArg->getType()
1028 << Context.getPointerType(AddrType)
1029 << AA_Passing << PointerArg->getSourceRange();
1030 }
1031
1032 // Finally, do the cast and replace the argument with the corrected version.
1033 AddrType = Context.getPointerType(AddrType);
1034 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1035 if (PointerArgRes.isInvalid())
1036 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001037 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001038
1039 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1040
1041 // In general, we allow ints, floats and pointers to be loaded and stored.
1042 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1043 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1044 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1045 << PointerArg->getType() << PointerArg->getSourceRange();
1046 return true;
1047 }
1048
1049 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +00001050 if (Context.getTypeSize(ValType) > MaxWidth) {
1051 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +00001052 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1053 << PointerArg->getType() << PointerArg->getSourceRange();
1054 return true;
1055 }
1056
1057 switch (ValType.getObjCLifetime()) {
1058 case Qualifiers::OCL_None:
1059 case Qualifiers::OCL_ExplicitNone:
1060 // okay
1061 break;
1062
1063 case Qualifiers::OCL_Weak:
1064 case Qualifiers::OCL_Strong:
1065 case Qualifiers::OCL_Autoreleasing:
1066 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1067 << ValType << PointerArg->getSourceRange();
1068 return true;
1069 }
1070
Tim Northover6aacd492013-07-16 09:47:53 +00001071 if (IsLdrex) {
1072 TheCall->setType(ValType);
1073 return false;
1074 }
1075
1076 // Initialize the argument to be stored.
1077 ExprResult ValArg = TheCall->getArg(0);
1078 InitializedEntity Entity = InitializedEntity::InitializeParameter(
1079 Context, ValType, /*consume*/ false);
1080 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1081 if (ValArg.isInvalid())
1082 return true;
Tim Northover6aacd492013-07-16 09:47:53 +00001083 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +00001084
1085 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1086 // but the custom checker bypasses all default analysis.
1087 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +00001088 return false;
1089}
1090
Nate Begeman4904e322010-06-08 02:47:44 +00001091bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +00001092 llvm::APSInt Result;
1093
Tim Northover6aacd492013-07-16 09:47:53 +00001094 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001095 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1096 BuiltinID == ARM::BI__builtin_arm_strex ||
1097 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001098 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +00001099 }
1100
Yi Kong26d104a2014-08-13 19:18:14 +00001101 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1102 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1103 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1104 }
1105
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001106 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1107 BuiltinID == ARM::BI__builtin_arm_wsr64)
1108 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1109
1110 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1111 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1112 BuiltinID == ARM::BI__builtin_arm_wsr ||
1113 BuiltinID == ARM::BI__builtin_arm_wsrp)
1114 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1115
Tim Northover12670412014-02-19 10:37:05 +00001116 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1117 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +00001118
Yi Kong4efadfb2014-07-03 16:01:25 +00001119 // For intrinsics which take an immediate value as part of the instruction,
1120 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +00001121 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +00001122 switch (BuiltinID) {
1123 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +00001124 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
1125 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +00001126 case ARM::BI__builtin_arm_vcvtr_f:
1127 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +00001128 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +00001129 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +00001130 case ARM::BI__builtin_arm_isb:
1131 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001132 }
Nate Begemand773fe62010-06-13 04:47:52 +00001133
Nate Begemanf568b072010-08-03 21:32:34 +00001134 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +00001135 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001136}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001137
Tim Northover573cbee2014-05-24 12:52:07 +00001138bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +00001139 CallExpr *TheCall) {
1140 llvm::APSInt Result;
1141
Tim Northover573cbee2014-05-24 12:52:07 +00001142 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001143 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1144 BuiltinID == AArch64::BI__builtin_arm_strex ||
1145 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001146 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1147 }
1148
Yi Konga5548432014-08-13 19:18:20 +00001149 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1150 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1151 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1152 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1153 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1154 }
1155
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001156 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1157 BuiltinID == AArch64::BI__builtin_arm_wsr64)
Tim Northover54e50002016-04-13 17:08:55 +00001158 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001159
1160 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1161 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1162 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1163 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1164 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1165
Tim Northovera2ee4332014-03-29 15:09:45 +00001166 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1167 return true;
1168
Yi Kong19a29ac2014-07-17 10:52:06 +00001169 // For intrinsics which take an immediate value as part of the instruction,
1170 // range check them here.
1171 unsigned i = 0, l = 0, u = 0;
1172 switch (BuiltinID) {
1173 default: return false;
1174 case AArch64::BI__builtin_arm_dmb:
1175 case AArch64::BI__builtin_arm_dsb:
1176 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1177 }
1178
Yi Kong19a29ac2014-07-17 10:52:06 +00001179 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +00001180}
1181
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001182bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1183 unsigned i = 0, l = 0, u = 0;
1184 switch (BuiltinID) {
1185 default: return false;
1186 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1187 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +00001188 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1189 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1190 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1191 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1192 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001193 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001194
Richard Sandiford28940af2014-04-16 08:47:51 +00001195 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001196}
1197
Kit Bartone50adcb2015-03-30 19:40:59 +00001198bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1199 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00001200 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1201 BuiltinID == PPC::BI__builtin_divdeu ||
1202 BuiltinID == PPC::BI__builtin_bpermd;
1203 bool IsTarget64Bit = Context.getTargetInfo()
1204 .getTypeWidth(Context
1205 .getTargetInfo()
1206 .getIntPtrType()) == 64;
1207 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1208 BuiltinID == PPC::BI__builtin_divweu ||
1209 BuiltinID == PPC::BI__builtin_divde ||
1210 BuiltinID == PPC::BI__builtin_divdeu;
1211
1212 if (Is64BitBltin && !IsTarget64Bit)
1213 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1214 << TheCall->getSourceRange();
1215
1216 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1217 (BuiltinID == PPC::BI__builtin_bpermd &&
1218 !Context.getTargetInfo().hasFeature("bpermd")))
1219 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1220 << TheCall->getSourceRange();
1221
Kit Bartone50adcb2015-03-30 19:40:59 +00001222 switch (BuiltinID) {
1223 default: return false;
1224 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1225 case PPC::BI__builtin_altivec_crypto_vshasigmad:
1226 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1227 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1228 case PPC::BI__builtin_tbegin:
1229 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1230 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1231 case PPC::BI__builtin_tabortwc:
1232 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1233 case PPC::BI__builtin_tabortwci:
1234 case PPC::BI__builtin_tabortdci:
1235 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1236 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1237 }
1238 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1239}
1240
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001241bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1242 CallExpr *TheCall) {
1243 if (BuiltinID == SystemZ::BI__builtin_tabort) {
1244 Expr *Arg = TheCall->getArg(0);
1245 llvm::APSInt AbortCode(32);
1246 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1247 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1248 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1249 << Arg->getSourceRange();
1250 }
1251
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001252 // For intrinsics which take an immediate value as part of the instruction,
1253 // range check them here.
1254 unsigned i = 0, l = 0, u = 0;
1255 switch (BuiltinID) {
1256 default: return false;
1257 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1258 case SystemZ::BI__builtin_s390_verimb:
1259 case SystemZ::BI__builtin_s390_verimh:
1260 case SystemZ::BI__builtin_s390_verimf:
1261 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1262 case SystemZ::BI__builtin_s390_vfaeb:
1263 case SystemZ::BI__builtin_s390_vfaeh:
1264 case SystemZ::BI__builtin_s390_vfaef:
1265 case SystemZ::BI__builtin_s390_vfaebs:
1266 case SystemZ::BI__builtin_s390_vfaehs:
1267 case SystemZ::BI__builtin_s390_vfaefs:
1268 case SystemZ::BI__builtin_s390_vfaezb:
1269 case SystemZ::BI__builtin_s390_vfaezh:
1270 case SystemZ::BI__builtin_s390_vfaezf:
1271 case SystemZ::BI__builtin_s390_vfaezbs:
1272 case SystemZ::BI__builtin_s390_vfaezhs:
1273 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1274 case SystemZ::BI__builtin_s390_vfidb:
1275 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1276 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1277 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1278 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1279 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1280 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1281 case SystemZ::BI__builtin_s390_vstrcb:
1282 case SystemZ::BI__builtin_s390_vstrch:
1283 case SystemZ::BI__builtin_s390_vstrcf:
1284 case SystemZ::BI__builtin_s390_vstrczb:
1285 case SystemZ::BI__builtin_s390_vstrczh:
1286 case SystemZ::BI__builtin_s390_vstrczf:
1287 case SystemZ::BI__builtin_s390_vstrcbs:
1288 case SystemZ::BI__builtin_s390_vstrchs:
1289 case SystemZ::BI__builtin_s390_vstrcfs:
1290 case SystemZ::BI__builtin_s390_vstrczbs:
1291 case SystemZ::BI__builtin_s390_vstrczhs:
1292 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1293 }
1294 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001295}
1296
Craig Topper5ba2c502015-11-07 08:08:31 +00001297/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1298/// This checks that the target supports __builtin_cpu_supports and
1299/// that the string argument is constant and valid.
1300static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1301 Expr *Arg = TheCall->getArg(0);
1302
1303 // Check if the argument is a string literal.
1304 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1305 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1306 << Arg->getSourceRange();
1307
1308 // Check the contents of the string.
1309 StringRef Feature =
1310 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1311 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1312 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1313 << Arg->getSourceRange();
1314 return false;
1315}
1316
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001317bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Craig Topper39c87102016-05-18 03:18:12 +00001318 int i = 0, l = 0, u = 0;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001319 switch (BuiltinID) {
Richard Trieucc3949d2016-02-18 22:34:54 +00001320 default:
1321 return false;
Eric Christopherd9832702015-06-29 21:00:05 +00001322 case X86::BI__builtin_cpu_supports:
Craig Topper5ba2c502015-11-07 08:08:31 +00001323 return SemaBuiltinCpuSupports(*this, TheCall);
Charles Davisc7d5c942015-09-17 20:55:33 +00001324 case X86::BI__builtin_ms_va_start:
1325 return SemaBuiltinMSVAStart(TheCall);
Craig Topper39c87102016-05-18 03:18:12 +00001326 case X86::BI__builtin_ia32_extractf64x4_mask:
1327 case X86::BI__builtin_ia32_extracti64x4_mask:
1328 case X86::BI__builtin_ia32_extractf32x8_mask:
1329 case X86::BI__builtin_ia32_extracti32x8_mask:
1330 case X86::BI__builtin_ia32_extractf64x2_256_mask:
1331 case X86::BI__builtin_ia32_extracti64x2_256_mask:
1332 case X86::BI__builtin_ia32_extractf32x4_256_mask:
1333 case X86::BI__builtin_ia32_extracti32x4_256_mask:
1334 i = 1; l = 0; u = 1;
1335 break;
Richard Trieucc3949d2016-02-18 22:34:54 +00001336 case X86::BI_mm_prefetch:
Craig Topper39c87102016-05-18 03:18:12 +00001337 case X86::BI__builtin_ia32_extractf32x4_mask:
1338 case X86::BI__builtin_ia32_extracti32x4_mask:
1339 case X86::BI__builtin_ia32_vpermilpd_mask:
1340 case X86::BI__builtin_ia32_vpermilps_mask:
1341 case X86::BI__builtin_ia32_extractf64x2_512_mask:
1342 case X86::BI__builtin_ia32_extracti64x2_512_mask:
1343 i = 1; l = 0; u = 3;
1344 break;
1345 case X86::BI__builtin_ia32_insertf32x8_mask:
1346 case X86::BI__builtin_ia32_inserti32x8_mask:
1347 case X86::BI__builtin_ia32_insertf64x4_mask:
1348 case X86::BI__builtin_ia32_inserti64x4_mask:
1349 case X86::BI__builtin_ia32_insertf64x2_256_mask:
1350 case X86::BI__builtin_ia32_inserti64x2_256_mask:
1351 case X86::BI__builtin_ia32_insertf32x4_256_mask:
1352 case X86::BI__builtin_ia32_inserti32x4_256_mask:
1353 i = 2; l = 0; u = 1;
Richard Trieucc3949d2016-02-18 22:34:54 +00001354 break;
1355 case X86::BI__builtin_ia32_sha1rnds4:
Craig Topper39c87102016-05-18 03:18:12 +00001356 case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
1357 case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
1358 case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
1359 case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
1360 case X86::BI__builtin_ia32_shufpd128_mask:
1361 case X86::BI__builtin_ia32_insertf64x2_512_mask:
1362 case X86::BI__builtin_ia32_inserti64x2_512_mask:
1363 case X86::BI__builtin_ia32_insertf32x4_mask:
1364 case X86::BI__builtin_ia32_inserti32x4_mask:
1365 i = 2; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00001366 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00001367 case X86::BI__builtin_ia32_vpermil2pd:
1368 case X86::BI__builtin_ia32_vpermil2pd256:
1369 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00001370 case X86::BI__builtin_ia32_vpermil2ps256:
Craig Topper39c87102016-05-18 03:18:12 +00001371 i = 3; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00001372 break;
Craig Topper95b0d732015-01-25 23:30:05 +00001373 case X86::BI__builtin_ia32_cmpb128_mask:
1374 case X86::BI__builtin_ia32_cmpw128_mask:
1375 case X86::BI__builtin_ia32_cmpd128_mask:
1376 case X86::BI__builtin_ia32_cmpq128_mask:
1377 case X86::BI__builtin_ia32_cmpb256_mask:
1378 case X86::BI__builtin_ia32_cmpw256_mask:
1379 case X86::BI__builtin_ia32_cmpd256_mask:
1380 case X86::BI__builtin_ia32_cmpq256_mask:
1381 case X86::BI__builtin_ia32_cmpb512_mask:
1382 case X86::BI__builtin_ia32_cmpw512_mask:
1383 case X86::BI__builtin_ia32_cmpd512_mask:
1384 case X86::BI__builtin_ia32_cmpq512_mask:
1385 case X86::BI__builtin_ia32_ucmpb128_mask:
1386 case X86::BI__builtin_ia32_ucmpw128_mask:
1387 case X86::BI__builtin_ia32_ucmpd128_mask:
1388 case X86::BI__builtin_ia32_ucmpq128_mask:
1389 case X86::BI__builtin_ia32_ucmpb256_mask:
1390 case X86::BI__builtin_ia32_ucmpw256_mask:
1391 case X86::BI__builtin_ia32_ucmpd256_mask:
1392 case X86::BI__builtin_ia32_ucmpq256_mask:
1393 case X86::BI__builtin_ia32_ucmpb512_mask:
1394 case X86::BI__builtin_ia32_ucmpw512_mask:
1395 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00001396 case X86::BI__builtin_ia32_ucmpq512_mask:
Craig Topper8dd7d0d2015-02-13 06:04:48 +00001397 case X86::BI__builtin_ia32_vpcomub:
1398 case X86::BI__builtin_ia32_vpcomuw:
1399 case X86::BI__builtin_ia32_vpcomud:
1400 case X86::BI__builtin_ia32_vpcomuq:
1401 case X86::BI__builtin_ia32_vpcomb:
1402 case X86::BI__builtin_ia32_vpcomw:
1403 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00001404 case X86::BI__builtin_ia32_vpcomq:
Craig Topper39c87102016-05-18 03:18:12 +00001405 i = 2; l = 0; u = 7;
1406 break;
1407 case X86::BI__builtin_ia32_roundps:
1408 case X86::BI__builtin_ia32_roundpd:
1409 case X86::BI__builtin_ia32_roundps256:
1410 case X86::BI__builtin_ia32_roundpd256:
1411 case X86::BI__builtin_ia32_vpermilpd256_mask:
1412 case X86::BI__builtin_ia32_vpermilps256_mask:
1413 i = 1; l = 0; u = 15;
1414 break;
1415 case X86::BI__builtin_ia32_roundss:
1416 case X86::BI__builtin_ia32_roundsd:
1417 case X86::BI__builtin_ia32_rangepd128_mask:
1418 case X86::BI__builtin_ia32_rangepd256_mask:
1419 case X86::BI__builtin_ia32_rangepd512_mask:
1420 case X86::BI__builtin_ia32_rangeps128_mask:
1421 case X86::BI__builtin_ia32_rangeps256_mask:
1422 case X86::BI__builtin_ia32_rangeps512_mask:
1423 case X86::BI__builtin_ia32_getmantsd_round_mask:
1424 case X86::BI__builtin_ia32_getmantss_round_mask:
1425 case X86::BI__builtin_ia32_shufpd256_mask:
1426 i = 2; l = 0; u = 15;
1427 break;
1428 case X86::BI__builtin_ia32_cmpps:
1429 case X86::BI__builtin_ia32_cmpss:
1430 case X86::BI__builtin_ia32_cmppd:
1431 case X86::BI__builtin_ia32_cmpsd:
1432 case X86::BI__builtin_ia32_cmpps256:
1433 case X86::BI__builtin_ia32_cmppd256:
1434 case X86::BI__builtin_ia32_cmpps128_mask:
1435 case X86::BI__builtin_ia32_cmppd128_mask:
1436 case X86::BI__builtin_ia32_cmpps256_mask:
1437 case X86::BI__builtin_ia32_cmppd256_mask:
1438 case X86::BI__builtin_ia32_cmpps512_mask:
1439 case X86::BI__builtin_ia32_cmppd512_mask:
1440 case X86::BI__builtin_ia32_cmpsd_mask:
1441 case X86::BI__builtin_ia32_cmpss_mask:
1442 i = 2; l = 0; u = 31;
1443 break;
1444 case X86::BI__builtin_ia32_xabort:
1445 i = 0; l = -128; u = 255;
1446 break;
1447 case X86::BI__builtin_ia32_pshufw:
1448 case X86::BI__builtin_ia32_aeskeygenassist128:
1449 i = 1; l = -128; u = 255;
1450 break;
1451 case X86::BI__builtin_ia32_vcvtps2ph:
1452 case X86::BI__builtin_ia32_vcvtps2ph256:
1453 case X86::BI__builtin_ia32_vcvtps2ph512:
1454 case X86::BI__builtin_ia32_rndscaleps_128_mask:
1455 case X86::BI__builtin_ia32_rndscalepd_128_mask:
1456 case X86::BI__builtin_ia32_rndscaleps_256_mask:
1457 case X86::BI__builtin_ia32_rndscalepd_256_mask:
1458 case X86::BI__builtin_ia32_rndscaleps_mask:
1459 case X86::BI__builtin_ia32_rndscalepd_mask:
1460 case X86::BI__builtin_ia32_reducepd128_mask:
1461 case X86::BI__builtin_ia32_reducepd256_mask:
1462 case X86::BI__builtin_ia32_reducepd512_mask:
1463 case X86::BI__builtin_ia32_reduceps128_mask:
1464 case X86::BI__builtin_ia32_reduceps256_mask:
1465 case X86::BI__builtin_ia32_reduceps512_mask:
1466 case X86::BI__builtin_ia32_prold512_mask:
1467 case X86::BI__builtin_ia32_prolq512_mask:
1468 case X86::BI__builtin_ia32_prold128_mask:
1469 case X86::BI__builtin_ia32_prold256_mask:
1470 case X86::BI__builtin_ia32_prolq128_mask:
1471 case X86::BI__builtin_ia32_prolq256_mask:
1472 case X86::BI__builtin_ia32_prord128_mask:
1473 case X86::BI__builtin_ia32_prord256_mask:
1474 case X86::BI__builtin_ia32_prorq128_mask:
1475 case X86::BI__builtin_ia32_prorq256_mask:
1476 case X86::BI__builtin_ia32_pshufhw512_mask:
1477 case X86::BI__builtin_ia32_pshuflw512_mask:
1478 case X86::BI__builtin_ia32_pshufhw128_mask:
1479 case X86::BI__builtin_ia32_pshufhw256_mask:
1480 case X86::BI__builtin_ia32_pshuflw128_mask:
1481 case X86::BI__builtin_ia32_pshuflw256_mask:
1482 case X86::BI__builtin_ia32_psllwi512_mask:
1483 case X86::BI__builtin_ia32_psllwi128_mask:
1484 case X86::BI__builtin_ia32_psllwi256_mask:
1485 case X86::BI__builtin_ia32_psrldi128_mask:
1486 case X86::BI__builtin_ia32_psrldi256_mask:
1487 case X86::BI__builtin_ia32_psrldi512_mask:
1488 case X86::BI__builtin_ia32_psrlqi128_mask:
1489 case X86::BI__builtin_ia32_psrlqi256_mask:
1490 case X86::BI__builtin_ia32_psrlqi512_mask:
1491 case X86::BI__builtin_ia32_psrawi512_mask:
1492 case X86::BI__builtin_ia32_psrawi128_mask:
1493 case X86::BI__builtin_ia32_psrawi256_mask:
1494 case X86::BI__builtin_ia32_psrlwi512_mask:
1495 case X86::BI__builtin_ia32_psrlwi128_mask:
1496 case X86::BI__builtin_ia32_psrlwi256_mask:
1497 case X86::BI__builtin_ia32_vpermilpd512_mask:
1498 case X86::BI__builtin_ia32_vpermilps512_mask:
1499 case X86::BI__builtin_ia32_psradi128_mask:
1500 case X86::BI__builtin_ia32_psradi256_mask:
1501 case X86::BI__builtin_ia32_psradi512_mask:
1502 case X86::BI__builtin_ia32_psraqi128_mask:
1503 case X86::BI__builtin_ia32_psraqi256_mask:
1504 case X86::BI__builtin_ia32_psraqi512_mask:
1505 case X86::BI__builtin_ia32_pslldi128_mask:
1506 case X86::BI__builtin_ia32_pslldi256_mask:
1507 case X86::BI__builtin_ia32_pslldi512_mask:
1508 case X86::BI__builtin_ia32_psllqi128_mask:
1509 case X86::BI__builtin_ia32_psllqi256_mask:
1510 case X86::BI__builtin_ia32_psllqi512_mask:
1511 case X86::BI__builtin_ia32_permdf512_mask:
1512 case X86::BI__builtin_ia32_permdi512_mask:
1513 case X86::BI__builtin_ia32_permdf256_mask:
1514 case X86::BI__builtin_ia32_permdi256_mask:
1515 case X86::BI__builtin_ia32_fpclasspd128_mask:
1516 case X86::BI__builtin_ia32_fpclasspd256_mask:
1517 case X86::BI__builtin_ia32_fpclassps128_mask:
1518 case X86::BI__builtin_ia32_fpclassps256_mask:
1519 case X86::BI__builtin_ia32_fpclassps512_mask:
1520 case X86::BI__builtin_ia32_fpclasspd512_mask:
1521 case X86::BI__builtin_ia32_fpclasssd_mask:
1522 case X86::BI__builtin_ia32_fpclassss_mask:
1523 case X86::BI__builtin_ia32_pshufd512_mask:
1524 case X86::BI__builtin_ia32_pshufd256_mask:
1525 case X86::BI__builtin_ia32_pshufd128_mask:
1526 i = 1; l = 0; u = 255;
1527 break;
1528 case X86::BI__builtin_ia32_palignr:
1529 case X86::BI__builtin_ia32_insertps128:
1530 case X86::BI__builtin_ia32_dpps:
1531 case X86::BI__builtin_ia32_dppd:
1532 case X86::BI__builtin_ia32_dpps256:
1533 case X86::BI__builtin_ia32_mpsadbw128:
1534 case X86::BI__builtin_ia32_mpsadbw256:
1535 case X86::BI__builtin_ia32_pcmpistrm128:
1536 case X86::BI__builtin_ia32_pcmpistri128:
1537 case X86::BI__builtin_ia32_pcmpistria128:
1538 case X86::BI__builtin_ia32_pcmpistric128:
1539 case X86::BI__builtin_ia32_pcmpistrio128:
1540 case X86::BI__builtin_ia32_pcmpistris128:
1541 case X86::BI__builtin_ia32_pcmpistriz128:
1542 case X86::BI__builtin_ia32_pclmulqdq128:
1543 case X86::BI__builtin_ia32_vperm2f128_pd256:
1544 case X86::BI__builtin_ia32_vperm2f128_ps256:
1545 case X86::BI__builtin_ia32_vperm2f128_si256:
1546 case X86::BI__builtin_ia32_permti256:
1547 i = 2; l = -128; u = 255;
1548 break;
1549 case X86::BI__builtin_ia32_palignr128:
1550 case X86::BI__builtin_ia32_palignr256:
1551 case X86::BI__builtin_ia32_palignr128_mask:
1552 case X86::BI__builtin_ia32_palignr256_mask:
1553 case X86::BI__builtin_ia32_palignr512_mask:
1554 case X86::BI__builtin_ia32_alignq512_mask:
1555 case X86::BI__builtin_ia32_alignd512_mask:
1556 case X86::BI__builtin_ia32_alignd128_mask:
1557 case X86::BI__builtin_ia32_alignd256_mask:
1558 case X86::BI__builtin_ia32_alignq128_mask:
1559 case X86::BI__builtin_ia32_alignq256_mask:
1560 case X86::BI__builtin_ia32_vcomisd:
1561 case X86::BI__builtin_ia32_vcomiss:
1562 case X86::BI__builtin_ia32_shuf_f32x4_mask:
1563 case X86::BI__builtin_ia32_shuf_f64x2_mask:
1564 case X86::BI__builtin_ia32_shuf_i32x4_mask:
1565 case X86::BI__builtin_ia32_shuf_i64x2_mask:
1566 case X86::BI__builtin_ia32_shufpd512_mask:
1567 case X86::BI__builtin_ia32_shufps128_mask:
1568 case X86::BI__builtin_ia32_shufps256_mask:
1569 case X86::BI__builtin_ia32_shufps512_mask:
1570 case X86::BI__builtin_ia32_dbpsadbw128_mask:
1571 case X86::BI__builtin_ia32_dbpsadbw256_mask:
1572 case X86::BI__builtin_ia32_dbpsadbw512_mask:
1573 i = 2; l = 0; u = 255;
1574 break;
1575 case X86::BI__builtin_ia32_fixupimmpd512_mask:
1576 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
1577 case X86::BI__builtin_ia32_fixupimmps512_mask:
1578 case X86::BI__builtin_ia32_fixupimmps512_maskz:
1579 case X86::BI__builtin_ia32_fixupimmsd_mask:
1580 case X86::BI__builtin_ia32_fixupimmsd_maskz:
1581 case X86::BI__builtin_ia32_fixupimmss_mask:
1582 case X86::BI__builtin_ia32_fixupimmss_maskz:
1583 case X86::BI__builtin_ia32_fixupimmpd128_mask:
1584 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
1585 case X86::BI__builtin_ia32_fixupimmpd256_mask:
1586 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
1587 case X86::BI__builtin_ia32_fixupimmps128_mask:
1588 case X86::BI__builtin_ia32_fixupimmps128_maskz:
1589 case X86::BI__builtin_ia32_fixupimmps256_mask:
1590 case X86::BI__builtin_ia32_fixupimmps256_maskz:
1591 case X86::BI__builtin_ia32_pternlogd512_mask:
1592 case X86::BI__builtin_ia32_pternlogd512_maskz:
1593 case X86::BI__builtin_ia32_pternlogq512_mask:
1594 case X86::BI__builtin_ia32_pternlogq512_maskz:
1595 case X86::BI__builtin_ia32_pternlogd128_mask:
1596 case X86::BI__builtin_ia32_pternlogd128_maskz:
1597 case X86::BI__builtin_ia32_pternlogd256_mask:
1598 case X86::BI__builtin_ia32_pternlogd256_maskz:
1599 case X86::BI__builtin_ia32_pternlogq128_mask:
1600 case X86::BI__builtin_ia32_pternlogq128_maskz:
1601 case X86::BI__builtin_ia32_pternlogq256_mask:
1602 case X86::BI__builtin_ia32_pternlogq256_maskz:
1603 i = 3; l = 0; u = 255;
1604 break;
1605 case X86::BI__builtin_ia32_pcmpestrm128:
1606 case X86::BI__builtin_ia32_pcmpestri128:
1607 case X86::BI__builtin_ia32_pcmpestria128:
1608 case X86::BI__builtin_ia32_pcmpestric128:
1609 case X86::BI__builtin_ia32_pcmpestrio128:
1610 case X86::BI__builtin_ia32_pcmpestris128:
1611 case X86::BI__builtin_ia32_pcmpestriz128:
1612 i = 4; l = -128; u = 255;
1613 break;
1614 case X86::BI__builtin_ia32_rndscalesd_round_mask:
1615 case X86::BI__builtin_ia32_rndscaless_round_mask:
1616 i = 4; l = 0; u = 255;
Richard Trieucc3949d2016-02-18 22:34:54 +00001617 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001618 }
Craig Topperdd84ec52014-12-27 07:00:08 +00001619 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001620}
1621
Richard Smith55ce3522012-06-25 20:30:08 +00001622/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
1623/// parameter with the FormatAttr's correct format_idx and firstDataArg.
1624/// Returns true when the format fits the function and the FormatStringInfo has
1625/// been populated.
1626bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
1627 FormatStringInfo *FSI) {
1628 FSI->HasVAListArg = Format->getFirstArg() == 0;
1629 FSI->FormatIdx = Format->getFormatIdx() - 1;
1630 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001631
Richard Smith55ce3522012-06-25 20:30:08 +00001632 // The way the format attribute works in GCC, the implicit this argument
1633 // of member functions is counted. However, it doesn't appear in our own
1634 // lists, so decrement format_idx in that case.
1635 if (IsCXXMember) {
1636 if(FSI->FormatIdx == 0)
1637 return false;
1638 --FSI->FormatIdx;
1639 if (FSI->FirstDataArg != 0)
1640 --FSI->FirstDataArg;
1641 }
1642 return true;
1643}
Mike Stump11289f42009-09-09 15:08:12 +00001644
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001645/// Checks if a the given expression evaluates to null.
1646///
1647/// \brief Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00001648static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001649 // If the expression has non-null type, it doesn't evaluate to null.
1650 if (auto nullability
1651 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
1652 if (*nullability == NullabilityKind::NonNull)
1653 return false;
1654 }
1655
Ted Kremeneka146db32014-01-17 06:24:47 +00001656 // As a special case, transparent unions initialized with zero are
1657 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001658 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00001659 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
1660 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001661 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00001662 if (const InitListExpr *ILE =
1663 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001664 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00001665 }
1666
1667 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00001668 return (!Expr->isValueDependent() &&
1669 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
1670 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001671}
1672
1673static void CheckNonNullArgument(Sema &S,
1674 const Expr *ArgExpr,
1675 SourceLocation CallSiteLoc) {
1676 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00001677 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
1678 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00001679}
1680
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001681bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
1682 FormatStringInfo FSI;
1683 if ((GetFormatStringType(Format) == FST_NSString) &&
1684 getFormatStringInfo(Format, false, &FSI)) {
1685 Idx = FSI.FormatIdx;
1686 return true;
1687 }
1688 return false;
1689}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001690/// \brief Diagnose use of %s directive in an NSString which is being passed
1691/// as formatting string to formatting method.
1692static void
1693DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
1694 const NamedDecl *FDecl,
1695 Expr **Args,
1696 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001697 unsigned Idx = 0;
1698 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001699 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
1700 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001701 Idx = 2;
1702 Format = true;
1703 }
1704 else
1705 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
1706 if (S.GetFormatNSStringIdx(I, Idx)) {
1707 Format = true;
1708 break;
1709 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001710 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001711 if (!Format || NumArgs <= Idx)
1712 return;
1713 const Expr *FormatExpr = Args[Idx];
1714 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
1715 FormatExpr = CSCE->getSubExpr();
1716 const StringLiteral *FormatString;
1717 if (const ObjCStringLiteral *OSL =
1718 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
1719 FormatString = OSL->getString();
1720 else
1721 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
1722 if (!FormatString)
1723 return;
1724 if (S.FormatStringHasSArg(FormatString)) {
1725 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
1726 << "%s" << 1 << 1;
1727 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
1728 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001729 }
1730}
1731
Douglas Gregorb4866e82015-06-19 18:13:19 +00001732/// Determine whether the given type has a non-null nullability annotation.
1733static bool isNonNullType(ASTContext &ctx, QualType type) {
1734 if (auto nullability = type->getNullability(ctx))
1735 return *nullability == NullabilityKind::NonNull;
1736
1737 return false;
1738}
1739
Ted Kremenek2bc73332014-01-17 06:24:43 +00001740static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00001741 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00001742 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00001743 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00001744 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001745 assert((FDecl || Proto) && "Need a function declaration or prototype");
1746
Ted Kremenek9aedc152014-01-17 06:24:56 +00001747 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00001748 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00001749 if (FDecl) {
1750 // Handle the nonnull attribute on the function/method declaration itself.
1751 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
1752 if (!NonNull->args_size()) {
1753 // Easy case: all pointer arguments are nonnull.
1754 for (const auto *Arg : Args)
1755 if (S.isValidPointerAttrType(Arg->getType()))
1756 CheckNonNullArgument(S, Arg, CallSiteLoc);
1757 return;
1758 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001759
Douglas Gregorb4866e82015-06-19 18:13:19 +00001760 for (unsigned Val : NonNull->args()) {
1761 if (Val >= Args.size())
1762 continue;
1763 if (NonNullArgs.empty())
1764 NonNullArgs.resize(Args.size());
1765 NonNullArgs.set(Val);
1766 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001767 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00001768 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00001769
Douglas Gregorb4866e82015-06-19 18:13:19 +00001770 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
1771 // Handle the nonnull attribute on the parameters of the
1772 // function/method.
1773 ArrayRef<ParmVarDecl*> parms;
1774 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
1775 parms = FD->parameters();
1776 else
1777 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
1778
1779 unsigned ParamIndex = 0;
1780 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
1781 I != E; ++I, ++ParamIndex) {
1782 const ParmVarDecl *PVD = *I;
1783 if (PVD->hasAttr<NonNullAttr>() ||
1784 isNonNullType(S.Context, PVD->getType())) {
1785 if (NonNullArgs.empty())
1786 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00001787
Douglas Gregorb4866e82015-06-19 18:13:19 +00001788 NonNullArgs.set(ParamIndex);
1789 }
1790 }
1791 } else {
1792 // If we have a non-function, non-method declaration but no
1793 // function prototype, try to dig out the function prototype.
1794 if (!Proto) {
1795 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
1796 QualType type = VD->getType().getNonReferenceType();
1797 if (auto pointerType = type->getAs<PointerType>())
1798 type = pointerType->getPointeeType();
1799 else if (auto blockType = type->getAs<BlockPointerType>())
1800 type = blockType->getPointeeType();
1801 // FIXME: data member pointers?
1802
1803 // Dig out the function prototype, if there is one.
1804 Proto = type->getAs<FunctionProtoType>();
1805 }
1806 }
1807
1808 // Fill in non-null argument information from the nullability
1809 // information on the parameter types (if we have them).
1810 if (Proto) {
1811 unsigned Index = 0;
1812 for (auto paramType : Proto->getParamTypes()) {
1813 if (isNonNullType(S.Context, paramType)) {
1814 if (NonNullArgs.empty())
1815 NonNullArgs.resize(Args.size());
1816
1817 NonNullArgs.set(Index);
1818 }
1819
1820 ++Index;
1821 }
1822 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00001823 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001824
Douglas Gregorb4866e82015-06-19 18:13:19 +00001825 // Check for non-null arguments.
1826 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
1827 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00001828 if (NonNullArgs[ArgIndex])
1829 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00001830 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00001831}
1832
Richard Smith55ce3522012-06-25 20:30:08 +00001833/// Handles the checks for format strings, non-POD arguments to vararg
1834/// functions, and NULL arguments passed to non-NULL parameters.
Douglas Gregorb4866e82015-06-19 18:13:19 +00001835void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
1836 ArrayRef<const Expr *> Args, bool IsMemberFunction,
Alp Toker9cacbab2014-01-20 20:26:09 +00001837 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +00001838 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00001839 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00001840 if (CurContext->isDependentContext())
1841 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001842
Ted Kremenekb8176da2010-09-09 04:33:05 +00001843 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00001844 llvm::SmallBitVector CheckedVarArgs;
1845 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001846 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001847 // Only create vector if there are format attributes.
1848 CheckedVarArgs.resize(Args.size());
1849
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001850 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00001851 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001852 }
Richard Smithd7293d72013-08-05 18:49:43 +00001853 }
Richard Smith55ce3522012-06-25 20:30:08 +00001854
1855 // Refuse POD arguments that weren't caught by the format string
1856 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +00001857 if (CallType != VariadicDoesNotApply) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001858 unsigned NumParams = Proto ? Proto->getNumParams()
1859 : FDecl && isa<FunctionDecl>(FDecl)
1860 ? cast<FunctionDecl>(FDecl)->getNumParams()
1861 : FDecl && isa<ObjCMethodDecl>(FDecl)
1862 ? cast<ObjCMethodDecl>(FDecl)->param_size()
1863 : 0;
1864
Alp Toker9cacbab2014-01-20 20:26:09 +00001865 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001866 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00001867 if (const Expr *Arg = Args[ArgIdx]) {
1868 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
1869 checkVariadicArgument(Arg, CallType);
1870 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001871 }
Richard Smithd7293d72013-08-05 18:49:43 +00001872 }
Mike Stump11289f42009-09-09 15:08:12 +00001873
Douglas Gregorb4866e82015-06-19 18:13:19 +00001874 if (FDecl || Proto) {
1875 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001876
Richard Trieu41bc0992013-06-22 00:20:41 +00001877 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00001878 if (FDecl) {
1879 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
1880 CheckArgumentWithTypeTag(I, Args.data());
1881 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001882 }
Richard Smith55ce3522012-06-25 20:30:08 +00001883}
1884
1885/// CheckConstructorCall - Check a constructor call for correctness and safety
1886/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00001887void Sema::CheckConstructorCall(FunctionDecl *FDecl,
1888 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00001889 const FunctionProtoType *Proto,
1890 SourceLocation Loc) {
1891 VariadicCallType CallType =
1892 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Douglas Gregorb4866e82015-06-19 18:13:19 +00001893 checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(),
1894 CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00001895}
1896
1897/// CheckFunctionCall - Check a direct function call for various correctness
1898/// and safety properties not strictly enforced by the C type system.
1899bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
1900 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001901 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
1902 isa<CXXMethodDecl>(FDecl);
1903 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
1904 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00001905 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
1906 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00001907 Expr** Args = TheCall->getArgs();
1908 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +00001909 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001910 // If this is a call to a member operator, hide the first argument
1911 // from checkCall.
1912 // FIXME: Our choice of AST representation here is less than ideal.
1913 ++Args;
1914 --NumArgs;
1915 }
Douglas Gregorb4866e82015-06-19 18:13:19 +00001916 checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00001917 IsMemberFunction, TheCall->getRParenLoc(),
1918 TheCall->getCallee()->getSourceRange(), CallType);
1919
1920 IdentifierInfo *FnInfo = FDecl->getIdentifier();
1921 // None of the checks below are needed for functions that don't have
1922 // simple names (e.g., C++ conversion functions).
1923 if (!FnInfo)
1924 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001925
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001926 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001927 if (getLangOpts().ObjC1)
1928 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001929
Anna Zaks22122702012-01-17 00:37:07 +00001930 unsigned CMId = FDecl->getMemoryFunctionKind();
1931 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00001932 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00001933
Anna Zaks201d4892012-01-13 21:52:01 +00001934 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00001935 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00001936 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00001937 else if (CMId == Builtin::BIstrncat)
1938 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00001939 else
Anna Zaks22122702012-01-17 00:37:07 +00001940 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00001941
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001942 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00001943}
1944
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001945bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00001946 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00001947 VariadicCallType CallType =
1948 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001949
Douglas Gregorb4866e82015-06-19 18:13:19 +00001950 checkCall(Method, nullptr, Args,
1951 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
1952 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001953
1954 return false;
1955}
1956
Richard Trieu664c4c62013-06-20 21:03:13 +00001957bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
1958 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00001959 QualType Ty;
1960 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00001961 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00001962 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00001963 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00001964 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001965 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001966
Douglas Gregorb4866e82015-06-19 18:13:19 +00001967 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
1968 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001969 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001970
Richard Trieu664c4c62013-06-20 21:03:13 +00001971 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00001972 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00001973 CallType = VariadicDoesNotApply;
1974 } else if (Ty->isBlockPointerType()) {
1975 CallType = VariadicBlock;
1976 } else { // Ty->isFunctionPointerType()
1977 CallType = VariadicFunction;
1978 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001979
Douglas Gregorb4866e82015-06-19 18:13:19 +00001980 checkCall(NDecl, Proto,
1981 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
1982 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00001983 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00001984
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001985 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001986}
1987
Richard Trieu41bc0992013-06-22 00:20:41 +00001988/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
1989/// such as function pointers returned from functions.
1990bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001991 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00001992 TheCall->getCallee());
Douglas Gregorb4866e82015-06-19 18:13:19 +00001993 checkCall(/*FDecl=*/nullptr, Proto,
Craig Topper8c2a2a02014-08-30 16:55:39 +00001994 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00001995 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00001996 TheCall->getCallee()->getSourceRange(), CallType);
1997
1998 return false;
1999}
2000
Tim Northovere94a34c2014-03-11 10:49:14 +00002001static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
JF Bastiendda2cb12016-04-18 18:01:49 +00002002 if (!llvm::isValidAtomicOrderingCABI(Ordering))
Tim Northovere94a34c2014-03-11 10:49:14 +00002003 return false;
2004
JF Bastiendda2cb12016-04-18 18:01:49 +00002005 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
Tim Northovere94a34c2014-03-11 10:49:14 +00002006 switch (Op) {
2007 case AtomicExpr::AO__c11_atomic_init:
2008 llvm_unreachable("There is no ordering argument for an init");
2009
2010 case AtomicExpr::AO__c11_atomic_load:
2011 case AtomicExpr::AO__atomic_load_n:
2012 case AtomicExpr::AO__atomic_load:
JF Bastiendda2cb12016-04-18 18:01:49 +00002013 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2014 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002015
2016 case AtomicExpr::AO__c11_atomic_store:
2017 case AtomicExpr::AO__atomic_store:
2018 case AtomicExpr::AO__atomic_store_n:
JF Bastiendda2cb12016-04-18 18:01:49 +00002019 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2020 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2021 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002022
2023 default:
2024 return true;
2025 }
2026}
2027
Richard Smithfeea8832012-04-12 05:08:17 +00002028ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2029 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002030 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2031 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002032
Richard Smithfeea8832012-04-12 05:08:17 +00002033 // All these operations take one of the following forms:
2034 enum {
2035 // C __c11_atomic_init(A *, C)
2036 Init,
2037 // C __c11_atomic_load(A *, int)
2038 Load,
2039 // void __atomic_load(A *, CP, int)
Eric Fiselier8d662442016-03-30 23:39:56 +00002040 LoadCopy,
2041 // void __atomic_store(A *, CP, int)
Richard Smithfeea8832012-04-12 05:08:17 +00002042 Copy,
2043 // C __c11_atomic_add(A *, M, int)
2044 Arithmetic,
2045 // C __atomic_exchange_n(A *, CP, int)
2046 Xchg,
2047 // void __atomic_exchange(A *, C *, CP, int)
2048 GNUXchg,
2049 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2050 C11CmpXchg,
2051 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2052 GNUCmpXchg
2053 } Form = Init;
Eric Fiselier8d662442016-03-30 23:39:56 +00002054 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2055 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
Richard Smithfeea8832012-04-12 05:08:17 +00002056 // where:
2057 // C is an appropriate type,
2058 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2059 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2060 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2061 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002062
Gabor Horvath98bd0982015-03-16 09:59:54 +00002063 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2064 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2065 AtomicExpr::AO__atomic_load,
2066 "need to update code for modified C11 atomics");
Richard Smithfeea8832012-04-12 05:08:17 +00002067 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
2068 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
2069 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2070 Op == AtomicExpr::AO__atomic_store_n ||
2071 Op == AtomicExpr::AO__atomic_exchange_n ||
2072 Op == AtomicExpr::AO__atomic_compare_exchange_n;
2073 bool IsAddSub = false;
2074
2075 switch (Op) {
2076 case AtomicExpr::AO__c11_atomic_init:
2077 Form = Init;
2078 break;
2079
2080 case AtomicExpr::AO__c11_atomic_load:
2081 case AtomicExpr::AO__atomic_load_n:
2082 Form = Load;
2083 break;
2084
Richard Smithfeea8832012-04-12 05:08:17 +00002085 case AtomicExpr::AO__atomic_load:
Eric Fiselier8d662442016-03-30 23:39:56 +00002086 Form = LoadCopy;
2087 break;
2088
2089 case AtomicExpr::AO__c11_atomic_store:
Richard Smithfeea8832012-04-12 05:08:17 +00002090 case AtomicExpr::AO__atomic_store:
2091 case AtomicExpr::AO__atomic_store_n:
2092 Form = Copy;
2093 break;
2094
2095 case AtomicExpr::AO__c11_atomic_fetch_add:
2096 case AtomicExpr::AO__c11_atomic_fetch_sub:
2097 case AtomicExpr::AO__atomic_fetch_add:
2098 case AtomicExpr::AO__atomic_fetch_sub:
2099 case AtomicExpr::AO__atomic_add_fetch:
2100 case AtomicExpr::AO__atomic_sub_fetch:
2101 IsAddSub = true;
2102 // Fall through.
2103 case AtomicExpr::AO__c11_atomic_fetch_and:
2104 case AtomicExpr::AO__c11_atomic_fetch_or:
2105 case AtomicExpr::AO__c11_atomic_fetch_xor:
2106 case AtomicExpr::AO__atomic_fetch_and:
2107 case AtomicExpr::AO__atomic_fetch_or:
2108 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00002109 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00002110 case AtomicExpr::AO__atomic_and_fetch:
2111 case AtomicExpr::AO__atomic_or_fetch:
2112 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00002113 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00002114 Form = Arithmetic;
2115 break;
2116
2117 case AtomicExpr::AO__c11_atomic_exchange:
2118 case AtomicExpr::AO__atomic_exchange_n:
2119 Form = Xchg;
2120 break;
2121
2122 case AtomicExpr::AO__atomic_exchange:
2123 Form = GNUXchg;
2124 break;
2125
2126 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
2127 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
2128 Form = C11CmpXchg;
2129 break;
2130
2131 case AtomicExpr::AO__atomic_compare_exchange:
2132 case AtomicExpr::AO__atomic_compare_exchange_n:
2133 Form = GNUCmpXchg;
2134 break;
2135 }
2136
2137 // Check we have the right number of arguments.
2138 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002139 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00002140 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002141 << TheCall->getCallee()->getSourceRange();
2142 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00002143 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
2144 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002145 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00002146 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002147 << TheCall->getCallee()->getSourceRange();
2148 return ExprError();
2149 }
2150
Richard Smithfeea8832012-04-12 05:08:17 +00002151 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002152 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002153 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
2154 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
2155 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00002156 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002157 << Ptr->getType() << Ptr->getSourceRange();
2158 return ExprError();
2159 }
2160
Richard Smithfeea8832012-04-12 05:08:17 +00002161 // For a __c11 builtin, this should be a pointer to an _Atomic type.
2162 QualType AtomTy = pointerType->getPointeeType(); // 'A'
2163 QualType ValType = AtomTy; // 'C'
2164 if (IsC11) {
2165 if (!AtomTy->isAtomicType()) {
2166 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
2167 << Ptr->getType() << Ptr->getSourceRange();
2168 return ExprError();
2169 }
Richard Smithe00921a2012-09-15 06:09:58 +00002170 if (AtomTy.isConstQualified()) {
2171 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
2172 << Ptr->getType() << Ptr->getSourceRange();
2173 return ExprError();
2174 }
Richard Smithfeea8832012-04-12 05:08:17 +00002175 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiselier8d662442016-03-30 23:39:56 +00002176 } else if (Form != Load && Form != LoadCopy) {
Eric Fiseliera3a7c562015-10-04 00:11:02 +00002177 if (ValType.isConstQualified()) {
2178 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
2179 << Ptr->getType() << Ptr->getSourceRange();
2180 return ExprError();
2181 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002182 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002183
Richard Smithfeea8832012-04-12 05:08:17 +00002184 // For an arithmetic operation, the implied arithmetic must be well-formed.
2185 if (Form == Arithmetic) {
2186 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
2187 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
2188 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2189 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2190 return ExprError();
2191 }
2192 if (!IsAddSub && !ValType->isIntegerType()) {
2193 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
2194 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2195 return ExprError();
2196 }
David Majnemere85cff82015-01-28 05:48:06 +00002197 if (IsC11 && ValType->isPointerType() &&
2198 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
2199 diag::err_incomplete_type)) {
2200 return ExprError();
2201 }
Richard Smithfeea8832012-04-12 05:08:17 +00002202 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
2203 // For __atomic_*_n operations, the value type must be a scalar integral or
2204 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002205 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00002206 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2207 return ExprError();
2208 }
2209
Eli Friedmanaa769812013-09-11 03:49:34 +00002210 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
2211 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00002212 // For GNU atomics, require a trivially-copyable type. This is not part of
2213 // the GNU atomics specification, but we enforce it for sanity.
2214 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002215 << Ptr->getType() << Ptr->getSourceRange();
2216 return ExprError();
2217 }
2218
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002219 switch (ValType.getObjCLifetime()) {
2220 case Qualifiers::OCL_None:
2221 case Qualifiers::OCL_ExplicitNone:
2222 // okay
2223 break;
2224
2225 case Qualifiers::OCL_Weak:
2226 case Qualifiers::OCL_Strong:
2227 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00002228 // FIXME: Can this happen? By this point, ValType should be known
2229 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002230 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
2231 << ValType << Ptr->getSourceRange();
2232 return ExprError();
2233 }
2234
David Majnemerc6eb6502015-06-03 00:26:35 +00002235 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
2236 // volatile-ness of the pointee-type inject itself into the result or the
Eric Fiselier8d662442016-03-30 23:39:56 +00002237 // other operands. Similarly atomic_load can take a pointer to a const 'A'.
David Majnemerc6eb6502015-06-03 00:26:35 +00002238 ValType.removeLocalVolatile();
Eric Fiselier8d662442016-03-30 23:39:56 +00002239 ValType.removeLocalConst();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002240 QualType ResultType = ValType;
Eric Fiselier8d662442016-03-30 23:39:56 +00002241 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002242 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00002243 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002244 ResultType = Context.BoolTy;
2245
Richard Smithfeea8832012-04-12 05:08:17 +00002246 // The type of a parameter passed 'by value'. In the GNU atomics, such
2247 // arguments are actually passed as pointers.
2248 QualType ByValType = ValType; // 'CP'
2249 if (!IsC11 && !IsN)
2250 ByValType = Ptr->getType();
2251
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002252 // The first argument --- the pointer --- has a fixed type; we
2253 // deduce the types of the rest of the arguments accordingly. Walk
2254 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00002255 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002256 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00002257 if (i < NumVals[Form] + 1) {
2258 switch (i) {
2259 case 1:
2260 // The second argument is the non-atomic operand. For arithmetic, this
2261 // is always passed by value, and for a compare_exchange it is always
2262 // passed by address. For the rest, GNU uses by-address and C11 uses
2263 // by-value.
2264 assert(Form != Load);
2265 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
2266 Ty = ValType;
2267 else if (Form == Copy || Form == Xchg)
2268 Ty = ByValType;
2269 else if (Form == Arithmetic)
2270 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00002271 else {
2272 Expr *ValArg = TheCall->getArg(i);
2273 unsigned AS = 0;
2274 // Keep address space of non-atomic pointer type.
2275 if (const PointerType *PtrTy =
2276 ValArg->getType()->getAs<PointerType>()) {
2277 AS = PtrTy->getPointeeType().getAddressSpace();
2278 }
2279 Ty = Context.getPointerType(
2280 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
2281 }
Richard Smithfeea8832012-04-12 05:08:17 +00002282 break;
2283 case 2:
2284 // The third argument to compare_exchange / GNU exchange is a
2285 // (pointer to a) desired value.
2286 Ty = ByValType;
2287 break;
2288 case 3:
2289 // The fourth argument to GNU compare_exchange is a 'weak' flag.
2290 Ty = Context.BoolTy;
2291 break;
2292 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002293 } else {
2294 // The order(s) are always converted to int.
2295 Ty = Context.IntTy;
2296 }
Richard Smithfeea8832012-04-12 05:08:17 +00002297
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002298 InitializedEntity Entity =
2299 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00002300 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002301 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2302 if (Arg.isInvalid())
2303 return true;
2304 TheCall->setArg(i, Arg.get());
2305 }
2306
Richard Smithfeea8832012-04-12 05:08:17 +00002307 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002308 SmallVector<Expr*, 5> SubExprs;
2309 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00002310 switch (Form) {
2311 case Init:
2312 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00002313 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00002314 break;
2315 case Load:
2316 SubExprs.push_back(TheCall->getArg(1)); // Order
2317 break;
Eric Fiselier8d662442016-03-30 23:39:56 +00002318 case LoadCopy:
Richard Smithfeea8832012-04-12 05:08:17 +00002319 case Copy:
2320 case Arithmetic:
2321 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002322 SubExprs.push_back(TheCall->getArg(2)); // Order
2323 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00002324 break;
2325 case GNUXchg:
2326 // Note, AtomicExpr::getVal2() has a special case for this atomic.
2327 SubExprs.push_back(TheCall->getArg(3)); // Order
2328 SubExprs.push_back(TheCall->getArg(1)); // Val1
2329 SubExprs.push_back(TheCall->getArg(2)); // Val2
2330 break;
2331 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002332 SubExprs.push_back(TheCall->getArg(3)); // Order
2333 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002334 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00002335 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00002336 break;
2337 case GNUCmpXchg:
2338 SubExprs.push_back(TheCall->getArg(4)); // Order
2339 SubExprs.push_back(TheCall->getArg(1)); // Val1
2340 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
2341 SubExprs.push_back(TheCall->getArg(2)); // Val2
2342 SubExprs.push_back(TheCall->getArg(3)); // Weak
2343 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002344 }
Tim Northovere94a34c2014-03-11 10:49:14 +00002345
2346 if (SubExprs.size() >= 2 && Form != Init) {
2347 llvm::APSInt Result(32);
2348 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
2349 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00002350 Diag(SubExprs[1]->getLocStart(),
2351 diag::warn_atomic_op_has_invalid_memory_order)
2352 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00002353 }
2354
Fariborz Jahanian615de762013-05-28 17:37:39 +00002355 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
2356 SubExprs, ResultType, Op,
2357 TheCall->getRParenLoc());
2358
2359 if ((Op == AtomicExpr::AO__c11_atomic_load ||
2360 (Op == AtomicExpr::AO__c11_atomic_store)) &&
2361 Context.AtomicUsesUnsupportedLibcall(AE))
2362 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
2363 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002364
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002365 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002366}
2367
John McCall29ad95b2011-08-27 01:09:30 +00002368/// checkBuiltinArgument - Given a call to a builtin function, perform
2369/// normal type-checking on the given argument, updating the call in
2370/// place. This is useful when a builtin function requires custom
2371/// type-checking for some of its arguments but not necessarily all of
2372/// them.
2373///
2374/// Returns true on error.
2375static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
2376 FunctionDecl *Fn = E->getDirectCallee();
2377 assert(Fn && "builtin call without direct callee!");
2378
2379 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
2380 InitializedEntity Entity =
2381 InitializedEntity::InitializeParameter(S.Context, Param);
2382
2383 ExprResult Arg = E->getArg(0);
2384 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
2385 if (Arg.isInvalid())
2386 return true;
2387
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002388 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00002389 return false;
2390}
2391
Chris Lattnerdc046542009-05-08 06:58:22 +00002392/// SemaBuiltinAtomicOverloaded - We have a call to a function like
2393/// __sync_fetch_and_add, which is an overloaded function based on the pointer
2394/// type of its first argument. The main ActOnCallExpr routines have already
2395/// promoted the types of arguments because all of these calls are prototyped as
2396/// void(...).
2397///
2398/// This function goes through and does final semantic checking for these
2399/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00002400ExprResult
2401Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002402 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00002403 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2404 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2405
2406 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002407 if (TheCall->getNumArgs() < 1) {
2408 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2409 << 0 << 1 << TheCall->getNumArgs()
2410 << TheCall->getCallee()->getSourceRange();
2411 return ExprError();
2412 }
Mike Stump11289f42009-09-09 15:08:12 +00002413
Chris Lattnerdc046542009-05-08 06:58:22 +00002414 // Inspect the first argument of the atomic builtin. This should always be
2415 // a pointer type, whose element is an integral scalar or pointer type.
2416 // Because it is a pointer type, we don't have to worry about any implicit
2417 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002418 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00002419 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00002420 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
2421 if (FirstArgResult.isInvalid())
2422 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002423 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00002424 TheCall->setArg(0, FirstArg);
2425
John McCall31168b02011-06-15 23:02:42 +00002426 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
2427 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002428 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
2429 << FirstArg->getType() << FirstArg->getSourceRange();
2430 return ExprError();
2431 }
Mike Stump11289f42009-09-09 15:08:12 +00002432
John McCall31168b02011-06-15 23:02:42 +00002433 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00002434 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002435 !ValType->isBlockPointerType()) {
2436 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
2437 << FirstArg->getType() << FirstArg->getSourceRange();
2438 return ExprError();
2439 }
Chris Lattnerdc046542009-05-08 06:58:22 +00002440
John McCall31168b02011-06-15 23:02:42 +00002441 switch (ValType.getObjCLifetime()) {
2442 case Qualifiers::OCL_None:
2443 case Qualifiers::OCL_ExplicitNone:
2444 // okay
2445 break;
2446
2447 case Qualifiers::OCL_Weak:
2448 case Qualifiers::OCL_Strong:
2449 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00002450 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00002451 << ValType << FirstArg->getSourceRange();
2452 return ExprError();
2453 }
2454
John McCallb50451a2011-10-05 07:41:44 +00002455 // Strip any qualifiers off ValType.
2456 ValType = ValType.getUnqualifiedType();
2457
Chandler Carruth3973af72010-07-18 20:54:12 +00002458 // The majority of builtins return a value, but a few have special return
2459 // types, so allow them to override appropriately below.
2460 QualType ResultType = ValType;
2461
Chris Lattnerdc046542009-05-08 06:58:22 +00002462 // We need to figure out which concrete builtin this maps onto. For example,
2463 // __sync_fetch_and_add with a 2 byte object turns into
2464 // __sync_fetch_and_add_2.
2465#define BUILTIN_ROW(x) \
2466 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
2467 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00002468
Chris Lattnerdc046542009-05-08 06:58:22 +00002469 static const unsigned BuiltinIndices[][5] = {
2470 BUILTIN_ROW(__sync_fetch_and_add),
2471 BUILTIN_ROW(__sync_fetch_and_sub),
2472 BUILTIN_ROW(__sync_fetch_and_or),
2473 BUILTIN_ROW(__sync_fetch_and_and),
2474 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00002475 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00002476
Chris Lattnerdc046542009-05-08 06:58:22 +00002477 BUILTIN_ROW(__sync_add_and_fetch),
2478 BUILTIN_ROW(__sync_sub_and_fetch),
2479 BUILTIN_ROW(__sync_and_and_fetch),
2480 BUILTIN_ROW(__sync_or_and_fetch),
2481 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00002482 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00002483
Chris Lattnerdc046542009-05-08 06:58:22 +00002484 BUILTIN_ROW(__sync_val_compare_and_swap),
2485 BUILTIN_ROW(__sync_bool_compare_and_swap),
2486 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00002487 BUILTIN_ROW(__sync_lock_release),
2488 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00002489 };
Mike Stump11289f42009-09-09 15:08:12 +00002490#undef BUILTIN_ROW
2491
Chris Lattnerdc046542009-05-08 06:58:22 +00002492 // Determine the index of the size.
2493 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00002494 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00002495 case 1: SizeIndex = 0; break;
2496 case 2: SizeIndex = 1; break;
2497 case 4: SizeIndex = 2; break;
2498 case 8: SizeIndex = 3; break;
2499 case 16: SizeIndex = 4; break;
2500 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002501 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
2502 << FirstArg->getType() << FirstArg->getSourceRange();
2503 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00002504 }
Mike Stump11289f42009-09-09 15:08:12 +00002505
Chris Lattnerdc046542009-05-08 06:58:22 +00002506 // Each of these builtins has one pointer argument, followed by some number of
2507 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
2508 // that we ignore. Find out which row of BuiltinIndices to read from as well
2509 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00002510 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00002511 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00002512 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00002513 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00002514 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00002515 case Builtin::BI__sync_fetch_and_add:
2516 case Builtin::BI__sync_fetch_and_add_1:
2517 case Builtin::BI__sync_fetch_and_add_2:
2518 case Builtin::BI__sync_fetch_and_add_4:
2519 case Builtin::BI__sync_fetch_and_add_8:
2520 case Builtin::BI__sync_fetch_and_add_16:
2521 BuiltinIndex = 0;
2522 break;
2523
2524 case Builtin::BI__sync_fetch_and_sub:
2525 case Builtin::BI__sync_fetch_and_sub_1:
2526 case Builtin::BI__sync_fetch_and_sub_2:
2527 case Builtin::BI__sync_fetch_and_sub_4:
2528 case Builtin::BI__sync_fetch_and_sub_8:
2529 case Builtin::BI__sync_fetch_and_sub_16:
2530 BuiltinIndex = 1;
2531 break;
2532
2533 case Builtin::BI__sync_fetch_and_or:
2534 case Builtin::BI__sync_fetch_and_or_1:
2535 case Builtin::BI__sync_fetch_and_or_2:
2536 case Builtin::BI__sync_fetch_and_or_4:
2537 case Builtin::BI__sync_fetch_and_or_8:
2538 case Builtin::BI__sync_fetch_and_or_16:
2539 BuiltinIndex = 2;
2540 break;
2541
2542 case Builtin::BI__sync_fetch_and_and:
2543 case Builtin::BI__sync_fetch_and_and_1:
2544 case Builtin::BI__sync_fetch_and_and_2:
2545 case Builtin::BI__sync_fetch_and_and_4:
2546 case Builtin::BI__sync_fetch_and_and_8:
2547 case Builtin::BI__sync_fetch_and_and_16:
2548 BuiltinIndex = 3;
2549 break;
Mike Stump11289f42009-09-09 15:08:12 +00002550
Douglas Gregor73722482011-11-28 16:30:08 +00002551 case Builtin::BI__sync_fetch_and_xor:
2552 case Builtin::BI__sync_fetch_and_xor_1:
2553 case Builtin::BI__sync_fetch_and_xor_2:
2554 case Builtin::BI__sync_fetch_and_xor_4:
2555 case Builtin::BI__sync_fetch_and_xor_8:
2556 case Builtin::BI__sync_fetch_and_xor_16:
2557 BuiltinIndex = 4;
2558 break;
2559
Hal Finkeld2208b52014-10-02 20:53:50 +00002560 case Builtin::BI__sync_fetch_and_nand:
2561 case Builtin::BI__sync_fetch_and_nand_1:
2562 case Builtin::BI__sync_fetch_and_nand_2:
2563 case Builtin::BI__sync_fetch_and_nand_4:
2564 case Builtin::BI__sync_fetch_and_nand_8:
2565 case Builtin::BI__sync_fetch_and_nand_16:
2566 BuiltinIndex = 5;
2567 WarnAboutSemanticsChange = true;
2568 break;
2569
Douglas Gregor73722482011-11-28 16:30:08 +00002570 case Builtin::BI__sync_add_and_fetch:
2571 case Builtin::BI__sync_add_and_fetch_1:
2572 case Builtin::BI__sync_add_and_fetch_2:
2573 case Builtin::BI__sync_add_and_fetch_4:
2574 case Builtin::BI__sync_add_and_fetch_8:
2575 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002576 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00002577 break;
2578
2579 case Builtin::BI__sync_sub_and_fetch:
2580 case Builtin::BI__sync_sub_and_fetch_1:
2581 case Builtin::BI__sync_sub_and_fetch_2:
2582 case Builtin::BI__sync_sub_and_fetch_4:
2583 case Builtin::BI__sync_sub_and_fetch_8:
2584 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002585 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00002586 break;
2587
2588 case Builtin::BI__sync_and_and_fetch:
2589 case Builtin::BI__sync_and_and_fetch_1:
2590 case Builtin::BI__sync_and_and_fetch_2:
2591 case Builtin::BI__sync_and_and_fetch_4:
2592 case Builtin::BI__sync_and_and_fetch_8:
2593 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002594 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00002595 break;
2596
2597 case Builtin::BI__sync_or_and_fetch:
2598 case Builtin::BI__sync_or_and_fetch_1:
2599 case Builtin::BI__sync_or_and_fetch_2:
2600 case Builtin::BI__sync_or_and_fetch_4:
2601 case Builtin::BI__sync_or_and_fetch_8:
2602 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002603 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00002604 break;
2605
2606 case Builtin::BI__sync_xor_and_fetch:
2607 case Builtin::BI__sync_xor_and_fetch_1:
2608 case Builtin::BI__sync_xor_and_fetch_2:
2609 case Builtin::BI__sync_xor_and_fetch_4:
2610 case Builtin::BI__sync_xor_and_fetch_8:
2611 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002612 BuiltinIndex = 10;
2613 break;
2614
2615 case Builtin::BI__sync_nand_and_fetch:
2616 case Builtin::BI__sync_nand_and_fetch_1:
2617 case Builtin::BI__sync_nand_and_fetch_2:
2618 case Builtin::BI__sync_nand_and_fetch_4:
2619 case Builtin::BI__sync_nand_and_fetch_8:
2620 case Builtin::BI__sync_nand_and_fetch_16:
2621 BuiltinIndex = 11;
2622 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00002623 break;
Mike Stump11289f42009-09-09 15:08:12 +00002624
Chris Lattnerdc046542009-05-08 06:58:22 +00002625 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00002626 case Builtin::BI__sync_val_compare_and_swap_1:
2627 case Builtin::BI__sync_val_compare_and_swap_2:
2628 case Builtin::BI__sync_val_compare_and_swap_4:
2629 case Builtin::BI__sync_val_compare_and_swap_8:
2630 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002631 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00002632 NumFixed = 2;
2633 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002634
Chris Lattnerdc046542009-05-08 06:58:22 +00002635 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00002636 case Builtin::BI__sync_bool_compare_and_swap_1:
2637 case Builtin::BI__sync_bool_compare_and_swap_2:
2638 case Builtin::BI__sync_bool_compare_and_swap_4:
2639 case Builtin::BI__sync_bool_compare_and_swap_8:
2640 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002641 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00002642 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00002643 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00002644 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002645
2646 case Builtin::BI__sync_lock_test_and_set:
2647 case Builtin::BI__sync_lock_test_and_set_1:
2648 case Builtin::BI__sync_lock_test_and_set_2:
2649 case Builtin::BI__sync_lock_test_and_set_4:
2650 case Builtin::BI__sync_lock_test_and_set_8:
2651 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002652 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00002653 break;
2654
Chris Lattnerdc046542009-05-08 06:58:22 +00002655 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00002656 case Builtin::BI__sync_lock_release_1:
2657 case Builtin::BI__sync_lock_release_2:
2658 case Builtin::BI__sync_lock_release_4:
2659 case Builtin::BI__sync_lock_release_8:
2660 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002661 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00002662 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00002663 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00002664 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002665
2666 case Builtin::BI__sync_swap:
2667 case Builtin::BI__sync_swap_1:
2668 case Builtin::BI__sync_swap_2:
2669 case Builtin::BI__sync_swap_4:
2670 case Builtin::BI__sync_swap_8:
2671 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002672 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00002673 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00002674 }
Mike Stump11289f42009-09-09 15:08:12 +00002675
Chris Lattnerdc046542009-05-08 06:58:22 +00002676 // Now that we know how many fixed arguments we expect, first check that we
2677 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002678 if (TheCall->getNumArgs() < 1+NumFixed) {
2679 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2680 << 0 << 1+NumFixed << TheCall->getNumArgs()
2681 << TheCall->getCallee()->getSourceRange();
2682 return ExprError();
2683 }
Mike Stump11289f42009-09-09 15:08:12 +00002684
Hal Finkeld2208b52014-10-02 20:53:50 +00002685 if (WarnAboutSemanticsChange) {
2686 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
2687 << TheCall->getCallee()->getSourceRange();
2688 }
2689
Chris Lattner5b9241b2009-05-08 15:36:58 +00002690 // Get the decl for the concrete builtin from this, we can tell what the
2691 // concrete integer type we should convert to is.
2692 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Eric Christopher02d5d862015-08-06 01:01:12 +00002693 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00002694 FunctionDecl *NewBuiltinDecl;
2695 if (NewBuiltinID == BuiltinID)
2696 NewBuiltinDecl = FDecl;
2697 else {
2698 // Perform builtin lookup to avoid redeclaring it.
2699 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
2700 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
2701 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
2702 assert(Res.getFoundDecl());
2703 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00002704 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00002705 return ExprError();
2706 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002707
John McCallcf142162010-08-07 06:22:56 +00002708 // The first argument --- the pointer --- has a fixed type; we
2709 // deduce the types of the rest of the arguments accordingly. Walk
2710 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00002711 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00002712 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00002713
Chris Lattnerdc046542009-05-08 06:58:22 +00002714 // GCC does an implicit conversion to the pointer or integer ValType. This
2715 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00002716 // Initialize the argument.
2717 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2718 ValType, /*consume*/ false);
2719 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00002720 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002721 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002722
Chris Lattnerdc046542009-05-08 06:58:22 +00002723 // Okay, we have something that *can* be converted to the right type. Check
2724 // to see if there is a potentially weird extension going on here. This can
2725 // happen when you do an atomic operation on something like an char* and
2726 // pass in 42. The 42 gets converted to char. This is even more strange
2727 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00002728 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002729 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00002730 }
Mike Stump11289f42009-09-09 15:08:12 +00002731
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002732 ASTContext& Context = this->getASTContext();
2733
2734 // Create a new DeclRefExpr to refer to the new decl.
2735 DeclRefExpr* NewDRE = DeclRefExpr::Create(
2736 Context,
2737 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00002738 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002739 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00002740 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002741 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00002742 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002743 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00002744
Chris Lattnerdc046542009-05-08 06:58:22 +00002745 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00002746 // FIXME: This loses syntactic information.
2747 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
2748 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
2749 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002750 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00002751
Chandler Carruthbc8cab12010-07-18 07:23:17 +00002752 // Change the result type of the call to match the original value type. This
2753 // is arbitrary, but the codegen for these builtins ins design to handle it
2754 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00002755 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002756
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002757 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00002758}
2759
Michael Zolotukhin84df1232015-09-08 23:52:33 +00002760/// SemaBuiltinNontemporalOverloaded - We have a call to
2761/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
2762/// overloaded function based on the pointer type of its last argument.
2763///
2764/// This function goes through and does final semantic checking for these
2765/// builtins.
2766ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
2767 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
2768 DeclRefExpr *DRE =
2769 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2770 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2771 unsigned BuiltinID = FDecl->getBuiltinID();
2772 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
2773 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
2774 "Unexpected nontemporal load/store builtin!");
2775 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
2776 unsigned numArgs = isStore ? 2 : 1;
2777
2778 // Ensure that we have the proper number of arguments.
2779 if (checkArgCount(*this, TheCall, numArgs))
2780 return ExprError();
2781
2782 // Inspect the last argument of the nontemporal builtin. This should always
2783 // be a pointer type, from which we imply the type of the memory access.
2784 // Because it is a pointer type, we don't have to worry about any implicit
2785 // casts here.
2786 Expr *PointerArg = TheCall->getArg(numArgs - 1);
2787 ExprResult PointerArgResult =
2788 DefaultFunctionArrayLvalueConversion(PointerArg);
2789
2790 if (PointerArgResult.isInvalid())
2791 return ExprError();
2792 PointerArg = PointerArgResult.get();
2793 TheCall->setArg(numArgs - 1, PointerArg);
2794
2795 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2796 if (!pointerType) {
2797 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
2798 << PointerArg->getType() << PointerArg->getSourceRange();
2799 return ExprError();
2800 }
2801
2802 QualType ValType = pointerType->getPointeeType();
2803
2804 // Strip any qualifiers off ValType.
2805 ValType = ValType.getUnqualifiedType();
2806 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2807 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
2808 !ValType->isVectorType()) {
2809 Diag(DRE->getLocStart(),
2810 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
2811 << PointerArg->getType() << PointerArg->getSourceRange();
2812 return ExprError();
2813 }
2814
2815 if (!isStore) {
2816 TheCall->setType(ValType);
2817 return TheCallResult;
2818 }
2819
2820 ExprResult ValArg = TheCall->getArg(0);
2821 InitializedEntity Entity = InitializedEntity::InitializeParameter(
2822 Context, ValType, /*consume*/ false);
2823 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2824 if (ValArg.isInvalid())
2825 return ExprError();
2826
2827 TheCall->setArg(0, ValArg.get());
2828 TheCall->setType(Context.VoidTy);
2829 return TheCallResult;
2830}
2831
Chris Lattner6436fb62009-02-18 06:01:06 +00002832/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00002833/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00002834/// Note: It might also make sense to do the UTF-16 conversion here (would
2835/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00002836bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00002837 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00002838 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
2839
Douglas Gregorfb65e592011-07-27 05:40:30 +00002840 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002841 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
2842 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00002843 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00002844 }
Mike Stump11289f42009-09-09 15:08:12 +00002845
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002846 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002847 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002848 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002849 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00002850 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002851 UTF16 *ToPtr = &ToBuf[0];
2852
2853 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2854 &ToPtr, ToPtr + NumBytes,
2855 strictConversion);
2856 // Check for conversion failure.
2857 if (Result != conversionOK)
2858 Diag(Arg->getLocStart(),
2859 diag::warn_cfstring_truncated) << Arg->getSourceRange();
2860 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00002861 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002862}
2863
Charles Davisc7d5c942015-09-17 20:55:33 +00002864/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
2865/// for validity. Emit an error and return true on failure; return false
2866/// on success.
2867bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00002868 Expr *Fn = TheCall->getCallee();
2869 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00002870 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002871 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002872 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2873 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00002874 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002875 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00002876 return true;
2877 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002878
2879 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00002880 return Diag(TheCall->getLocEnd(),
2881 diag::err_typecheck_call_too_few_args_at_least)
2882 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002883 }
2884
John McCall29ad95b2011-08-27 01:09:30 +00002885 // Type-check the first argument normally.
2886 if (checkBuiltinArgument(*this, TheCall, 0))
2887 return true;
2888
Chris Lattnere202e6a2007-12-20 00:05:45 +00002889 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00002890 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00002891 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00002892 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00002893 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00002894 else if (FunctionDecl *FD = getCurFunctionDecl())
2895 isVariadic = FD->isVariadic();
2896 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002897 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00002898
Chris Lattnere202e6a2007-12-20 00:05:45 +00002899 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002900 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2901 return true;
2902 }
Mike Stump11289f42009-09-09 15:08:12 +00002903
Chris Lattner43be2e62007-12-19 23:59:04 +00002904 // Verify that the second argument to the builtin is the last argument of the
2905 // current function or method.
2906 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00002907 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002908
Nico Weber9eea7642013-05-24 23:31:57 +00002909 // These are valid if SecondArgIsLastNamedArgument is false after the next
2910 // block.
2911 QualType Type;
2912 SourceLocation ParamLoc;
Aaron Ballman1de59c52016-04-24 13:30:21 +00002913 bool IsCRegister = false;
Nico Weber9eea7642013-05-24 23:31:57 +00002914
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002915 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
2916 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002917 // FIXME: This isn't correct for methods (results in bogus warning).
2918 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002919 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00002920 if (CurBlock)
2921 LastArg = *(CurBlock->TheDecl->param_end()-1);
2922 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00002923 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002924 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002925 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002926 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00002927
2928 Type = PV->getType();
2929 ParamLoc = PV->getLocation();
Aaron Ballman1de59c52016-04-24 13:30:21 +00002930 IsCRegister =
2931 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
Chris Lattner43be2e62007-12-19 23:59:04 +00002932 }
2933 }
Mike Stump11289f42009-09-09 15:08:12 +00002934
Chris Lattner43be2e62007-12-19 23:59:04 +00002935 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002936 Diag(TheCall->getArg(1)->getLocStart(),
Aaron Ballman05164812016-04-18 18:10:53 +00002937 diag::warn_second_arg_of_va_start_not_last_named_param);
Aaron Ballman1de59c52016-04-24 13:30:21 +00002938 else if (IsCRegister || Type->isReferenceType() ||
2939 Type->isPromotableIntegerType() ||
2940 Type->isSpecificBuiltinType(BuiltinType::Float)) {
2941 unsigned Reason = 0;
2942 if (Type->isReferenceType()) Reason = 1;
2943 else if (IsCRegister) Reason = 2;
2944 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
Nico Weber9eea7642013-05-24 23:31:57 +00002945 Diag(ParamLoc, diag::note_parameter_type) << Type;
2946 }
2947
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00002948 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00002949 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00002950}
Chris Lattner43be2e62007-12-19 23:59:04 +00002951
Charles Davisc7d5c942015-09-17 20:55:33 +00002952/// Check the arguments to '__builtin_va_start' for validity, and that
2953/// it was called from a function of the native ABI.
2954/// Emit an error and return true on failure; return false on success.
2955bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
2956 // On x86-64 Unix, don't allow this in Win64 ABI functions.
2957 // On x64 Windows, don't allow this in System V ABI functions.
2958 // (Yes, that means there's no corresponding way to support variadic
2959 // System V ABI functions on Windows.)
2960 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) {
2961 unsigned OS = Context.getTargetInfo().getTriple().getOS();
2962 clang::CallingConv CC = CC_C;
2963 if (const FunctionDecl *FD = getCurFunctionDecl())
2964 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
2965 if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) ||
2966 (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64))
2967 return Diag(TheCall->getCallee()->getLocStart(),
2968 diag::err_va_start_used_in_wrong_abi_function)
2969 << (OS != llvm::Triple::Win32);
2970 }
2971 return SemaBuiltinVAStartImpl(TheCall);
2972}
2973
2974/// Check the arguments to '__builtin_ms_va_start' for validity, and that
2975/// it was called from a Win64 ABI function.
2976/// Emit an error and return true on failure; return false on success.
2977bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) {
2978 // This only makes sense for x86-64.
2979 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
2980 Expr *Callee = TheCall->getCallee();
2981 if (TT.getArch() != llvm::Triple::x86_64)
2982 return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt);
2983 // Don't allow this in System V ABI functions.
2984 clang::CallingConv CC = CC_C;
2985 if (const FunctionDecl *FD = getCurFunctionDecl())
2986 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
2987 if (CC == CC_X86_64SysV ||
2988 (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64))
2989 return Diag(Callee->getLocStart(),
2990 diag::err_ms_va_start_used_in_sysv_function);
2991 return SemaBuiltinVAStartImpl(TheCall);
2992}
2993
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002994bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
2995 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
2996 // const char *named_addr);
2997
2998 Expr *Func = Call->getCallee();
2999
3000 if (Call->getNumArgs() < 3)
3001 return Diag(Call->getLocEnd(),
3002 diag::err_typecheck_call_too_few_args_at_least)
3003 << 0 /*function call*/ << 3 << Call->getNumArgs();
3004
3005 // Determine whether the current function is variadic or not.
3006 bool IsVariadic;
3007 if (BlockScopeInfo *CurBlock = getCurBlock())
3008 IsVariadic = CurBlock->TheDecl->isVariadic();
3009 else if (FunctionDecl *FD = getCurFunctionDecl())
3010 IsVariadic = FD->isVariadic();
3011 else if (ObjCMethodDecl *MD = getCurMethodDecl())
3012 IsVariadic = MD->isVariadic();
3013 else
3014 llvm_unreachable("unexpected statement type");
3015
3016 if (!IsVariadic) {
3017 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3018 return true;
3019 }
3020
3021 // Type-check the first argument normally.
3022 if (checkBuiltinArgument(*this, Call, 0))
3023 return true;
3024
Benjamin Kramere0ca6e12015-03-01 18:09:50 +00003025 const struct {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003026 unsigned ArgNo;
3027 QualType Type;
3028 } ArgumentTypes[] = {
3029 { 1, Context.getPointerType(Context.CharTy.withConst()) },
3030 { 2, Context.getSizeType() },
3031 };
3032
3033 for (const auto &AT : ArgumentTypes) {
3034 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
3035 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
3036 continue;
3037 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
3038 << Arg->getType() << AT.Type << 1 /* different class */
3039 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
3040 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
3041 }
3042
3043 return false;
3044}
3045
Chris Lattner2da14fb2007-12-20 00:26:33 +00003046/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
3047/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00003048bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
3049 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00003050 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00003051 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00003052 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00003053 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003054 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003055 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00003056 << SourceRange(TheCall->getArg(2)->getLocStart(),
3057 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003058
John Wiegley01296292011-04-08 18:41:53 +00003059 ExprResult OrigArg0 = TheCall->getArg(0);
3060 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00003061
Chris Lattner2da14fb2007-12-20 00:26:33 +00003062 // Do standard promotions between the two arguments, returning their common
3063 // type.
Chris Lattner08464942007-12-28 05:29:59 +00003064 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00003065 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
3066 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00003067
3068 // Make sure any conversions are pushed back into the call; this is
3069 // type safe since unordered compare builtins are declared as "_Bool
3070 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00003071 TheCall->setArg(0, OrigArg0.get());
3072 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00003073
John Wiegley01296292011-04-08 18:41:53 +00003074 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00003075 return false;
3076
Chris Lattner2da14fb2007-12-20 00:26:33 +00003077 // If the common type isn't a real floating type, then the arguments were
3078 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00003079 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00003080 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003081 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00003082 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
3083 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003084
Chris Lattner2da14fb2007-12-20 00:26:33 +00003085 return false;
3086}
3087
Benjamin Kramer634fc102010-02-15 22:42:31 +00003088/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
3089/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00003090/// to check everything. We expect the last argument to be a floating point
3091/// value.
3092bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
3093 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00003094 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00003095 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00003096 if (TheCall->getNumArgs() > NumArgs)
3097 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003098 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003099 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00003100 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003101 (*(TheCall->arg_end()-1))->getLocEnd());
3102
Benjamin Kramer64aae502010-02-16 10:07:31 +00003103 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00003104
Eli Friedman7e4faac2009-08-31 20:06:00 +00003105 if (OrigArg->isTypeDependent())
3106 return false;
3107
Chris Lattner68784ef2010-05-06 05:50:07 +00003108 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00003109 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00003110 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003111 diag::err_typecheck_call_invalid_unary_fp)
3112 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003113
Chris Lattner68784ef2010-05-06 05:50:07 +00003114 // If this is an implicit conversion from float -> double, remove it.
3115 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
3116 Expr *CastArg = Cast->getSubExpr();
3117 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
3118 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
3119 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00003120 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00003121 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00003122 }
3123 }
3124
Eli Friedman7e4faac2009-08-31 20:06:00 +00003125 return false;
3126}
3127
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003128/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
3129// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00003130ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00003131 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003132 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00003133 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00003134 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3135 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003136
Nate Begemana0110022010-06-08 00:16:34 +00003137 // Determine which of the following types of shufflevector we're checking:
3138 // 1) unary, vector mask: (lhs, mask)
Craig Topperb3174a82016-05-18 04:11:25 +00003139 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
Nate Begemana0110022010-06-08 00:16:34 +00003140 QualType resType = TheCall->getArg(0)->getType();
3141 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00003142
Douglas Gregorc25f7662009-05-19 22:10:17 +00003143 if (!TheCall->getArg(0)->isTypeDependent() &&
3144 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00003145 QualType LHSType = TheCall->getArg(0)->getType();
3146 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00003147
Craig Topperbaca3892013-07-29 06:47:04 +00003148 if (!LHSType->isVectorType() || !RHSType->isVectorType())
3149 return ExprError(Diag(TheCall->getLocStart(),
3150 diag::err_shufflevector_non_vector)
3151 << SourceRange(TheCall->getArg(0)->getLocStart(),
3152 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00003153
Nate Begemana0110022010-06-08 00:16:34 +00003154 numElements = LHSType->getAs<VectorType>()->getNumElements();
3155 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00003156
Nate Begemana0110022010-06-08 00:16:34 +00003157 // Check to see if we have a call with 2 vector arguments, the unary shuffle
3158 // with mask. If so, verify that RHS is an integer vector type with the
3159 // same number of elts as lhs.
3160 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00003161 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00003162 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00003163 return ExprError(Diag(TheCall->getLocStart(),
3164 diag::err_shufflevector_incompatible_vector)
3165 << SourceRange(TheCall->getArg(1)->getLocStart(),
3166 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00003167 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00003168 return ExprError(Diag(TheCall->getLocStart(),
3169 diag::err_shufflevector_incompatible_vector)
3170 << SourceRange(TheCall->getArg(0)->getLocStart(),
3171 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00003172 } else if (numElements != numResElements) {
3173 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00003174 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00003175 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00003176 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003177 }
3178
3179 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00003180 if (TheCall->getArg(i)->isTypeDependent() ||
3181 TheCall->getArg(i)->isValueDependent())
3182 continue;
3183
Nate Begemana0110022010-06-08 00:16:34 +00003184 llvm::APSInt Result(32);
3185 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
3186 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00003187 diag::err_shufflevector_nonconstant_argument)
3188 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003189
Craig Topper50ad5b72013-08-03 17:40:38 +00003190 // Allow -1 which will be translated to undef in the IR.
3191 if (Result.isSigned() && Result.isAllOnesValue())
3192 continue;
3193
Chris Lattner7ab824e2008-08-10 02:05:13 +00003194 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003195 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00003196 diag::err_shufflevector_argument_too_large)
3197 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003198 }
3199
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003200 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003201
Chris Lattner7ab824e2008-08-10 02:05:13 +00003202 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003203 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00003204 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003205 }
3206
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003207 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
3208 TheCall->getCallee()->getLocStart(),
3209 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003210}
Chris Lattner43be2e62007-12-19 23:59:04 +00003211
Hal Finkelc4d7c822013-09-18 03:29:45 +00003212/// SemaConvertVectorExpr - Handle __builtin_convertvector
3213ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
3214 SourceLocation BuiltinLoc,
3215 SourceLocation RParenLoc) {
3216 ExprValueKind VK = VK_RValue;
3217 ExprObjectKind OK = OK_Ordinary;
3218 QualType DstTy = TInfo->getType();
3219 QualType SrcTy = E->getType();
3220
3221 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
3222 return ExprError(Diag(BuiltinLoc,
3223 diag::err_convertvector_non_vector)
3224 << E->getSourceRange());
3225 if (!DstTy->isVectorType() && !DstTy->isDependentType())
3226 return ExprError(Diag(BuiltinLoc,
3227 diag::err_convertvector_non_vector_type));
3228
3229 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
3230 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
3231 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
3232 if (SrcElts != DstElts)
3233 return ExprError(Diag(BuiltinLoc,
3234 diag::err_convertvector_incompatible_vector)
3235 << E->getSourceRange());
3236 }
3237
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003238 return new (Context)
3239 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00003240}
3241
Daniel Dunbarb7257262008-07-21 22:59:13 +00003242/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
3243// This is declared to take (const void*, ...) and can take two
3244// optional constant int args.
3245bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00003246 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003247
Chris Lattner3b054132008-11-19 05:08:23 +00003248 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003249 return Diag(TheCall->getLocEnd(),
3250 diag::err_typecheck_call_too_many_args_at_most)
3251 << 0 /*function call*/ << 3 << NumArgs
3252 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003253
3254 // Argument 0 is checked for us and the remaining arguments must be
3255 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00003256 for (unsigned i = 1; i != NumArgs; ++i)
3257 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00003258 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003259
Warren Hunt20e4a5d2014-02-21 23:08:53 +00003260 return false;
3261}
3262
Hal Finkelf0417332014-07-17 14:25:55 +00003263/// SemaBuiltinAssume - Handle __assume (MS Extension).
3264// __assume does not evaluate its arguments, and should warn if its argument
3265// has side effects.
3266bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
3267 Expr *Arg = TheCall->getArg(0);
3268 if (Arg->isInstantiationDependent()) return false;
3269
3270 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00003271 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00003272 << Arg->getSourceRange()
3273 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
3274
3275 return false;
3276}
3277
3278/// Handle __builtin_assume_aligned. This is declared
3279/// as (const void*, size_t, ...) and can take one optional constant int arg.
3280bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
3281 unsigned NumArgs = TheCall->getNumArgs();
3282
3283 if (NumArgs > 3)
3284 return Diag(TheCall->getLocEnd(),
3285 diag::err_typecheck_call_too_many_args_at_most)
3286 << 0 /*function call*/ << 3 << NumArgs
3287 << TheCall->getSourceRange();
3288
3289 // The alignment must be a constant integer.
3290 Expr *Arg = TheCall->getArg(1);
3291
3292 // We can't check the value of a dependent argument.
3293 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
3294 llvm::APSInt Result;
3295 if (SemaBuiltinConstantArg(TheCall, 1, Result))
3296 return true;
3297
3298 if (!Result.isPowerOf2())
3299 return Diag(TheCall->getLocStart(),
3300 diag::err_alignment_not_power_of_two)
3301 << Arg->getSourceRange();
3302 }
3303
3304 if (NumArgs > 2) {
3305 ExprResult Arg(TheCall->getArg(2));
3306 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3307 Context.getSizeType(), false);
3308 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3309 if (Arg.isInvalid()) return true;
3310 TheCall->setArg(2, Arg.get());
3311 }
Hal Finkelf0417332014-07-17 14:25:55 +00003312
3313 return false;
3314}
3315
Eric Christopher8d0c6212010-04-17 02:26:23 +00003316/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
3317/// TheCall is a constant expression.
3318bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
3319 llvm::APSInt &Result) {
3320 Expr *Arg = TheCall->getArg(ArgNum);
3321 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3322 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3323
3324 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
3325
3326 if (!Arg->isIntegerConstantExpr(Result, Context))
3327 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00003328 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00003329
Chris Lattnerd545ad12009-09-23 06:06:36 +00003330 return false;
3331}
3332
Richard Sandiford28940af2014-04-16 08:47:51 +00003333/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
3334/// TheCall is a constant expression in the range [Low, High].
3335bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
3336 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00003337 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00003338
3339 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00003340 Expr *Arg = TheCall->getArg(ArgNum);
3341 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00003342 return false;
3343
Eric Christopher8d0c6212010-04-17 02:26:23 +00003344 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00003345 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00003346 return true;
3347
Richard Sandiford28940af2014-04-16 08:47:51 +00003348 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00003349 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00003350 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00003351
3352 return false;
3353}
3354
Luke Cheeseman59b2d832015-06-15 17:51:01 +00003355/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
3356/// TheCall is an ARM/AArch64 special register string literal.
3357bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
3358 int ArgNum, unsigned ExpectedFieldNum,
3359 bool AllowName) {
3360 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
3361 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
3362 BuiltinID == ARM::BI__builtin_arm_rsr ||
3363 BuiltinID == ARM::BI__builtin_arm_rsrp ||
3364 BuiltinID == ARM::BI__builtin_arm_wsr ||
3365 BuiltinID == ARM::BI__builtin_arm_wsrp;
3366 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
3367 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
3368 BuiltinID == AArch64::BI__builtin_arm_rsr ||
3369 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
3370 BuiltinID == AArch64::BI__builtin_arm_wsr ||
3371 BuiltinID == AArch64::BI__builtin_arm_wsrp;
3372 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
3373
3374 // We can't check the value of a dependent argument.
3375 Expr *Arg = TheCall->getArg(ArgNum);
3376 if (Arg->isTypeDependent() || Arg->isValueDependent())
3377 return false;
3378
3379 // Check if the argument is a string literal.
3380 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3381 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
3382 << Arg->getSourceRange();
3383
3384 // Check the type of special register given.
3385 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3386 SmallVector<StringRef, 6> Fields;
3387 Reg.split(Fields, ":");
3388
3389 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
3390 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
3391 << Arg->getSourceRange();
3392
3393 // If the string is the name of a register then we cannot check that it is
3394 // valid here but if the string is of one the forms described in ACLE then we
3395 // can check that the supplied fields are integers and within the valid
3396 // ranges.
3397 if (Fields.size() > 1) {
3398 bool FiveFields = Fields.size() == 5;
3399
3400 bool ValidString = true;
3401 if (IsARMBuiltin) {
3402 ValidString &= Fields[0].startswith_lower("cp") ||
3403 Fields[0].startswith_lower("p");
3404 if (ValidString)
3405 Fields[0] =
3406 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
3407
3408 ValidString &= Fields[2].startswith_lower("c");
3409 if (ValidString)
3410 Fields[2] = Fields[2].drop_front(1);
3411
3412 if (FiveFields) {
3413 ValidString &= Fields[3].startswith_lower("c");
3414 if (ValidString)
3415 Fields[3] = Fields[3].drop_front(1);
3416 }
3417 }
3418
3419 SmallVector<int, 5> Ranges;
3420 if (FiveFields)
3421 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15});
3422 else
3423 Ranges.append({15, 7, 15});
3424
3425 for (unsigned i=0; i<Fields.size(); ++i) {
3426 int IntField;
3427 ValidString &= !Fields[i].getAsInteger(10, IntField);
3428 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
3429 }
3430
3431 if (!ValidString)
3432 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
3433 << Arg->getSourceRange();
3434
3435 } else if (IsAArch64Builtin && Fields.size() == 1) {
3436 // If the register name is one of those that appear in the condition below
3437 // and the special register builtin being used is one of the write builtins,
3438 // then we require that the argument provided for writing to the register
3439 // is an integer constant expression. This is because it will be lowered to
3440 // an MSR (immediate) instruction, so we need to know the immediate at
3441 // compile time.
3442 if (TheCall->getNumArgs() != 2)
3443 return false;
3444
3445 std::string RegLower = Reg.lower();
3446 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
3447 RegLower != "pan" && RegLower != "uao")
3448 return false;
3449
3450 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
3451 }
3452
3453 return false;
3454}
3455
Eli Friedmanc97d0142009-05-03 06:04:26 +00003456/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003457/// This checks that the target supports __builtin_longjmp and
3458/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003459bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003460 if (!Context.getTargetInfo().hasSjLjLowering())
3461 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
3462 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
3463
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003464 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00003465 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00003466
Eric Christopher8d0c6212010-04-17 02:26:23 +00003467 // TODO: This is less than ideal. Overload this to take a value.
3468 if (SemaBuiltinConstantArg(TheCall, 1, Result))
3469 return true;
3470
3471 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003472 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
3473 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
3474
3475 return false;
3476}
3477
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003478/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
3479/// This checks that the target supports __builtin_setjmp.
3480bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
3481 if (!Context.getTargetInfo().hasSjLjLowering())
3482 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
3483 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
3484 return false;
3485}
3486
Richard Smithd7293d72013-08-05 18:49:43 +00003487namespace {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003488class UncoveredArgHandler {
3489 enum { Unknown = -1, AllCovered = -2 };
3490 signed FirstUncoveredArg;
3491 SmallVector<const Expr *, 4> DiagnosticExprs;
3492
3493public:
3494 UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
3495
3496 bool hasUncoveredArg() const {
3497 return (FirstUncoveredArg >= 0);
3498 }
3499
3500 unsigned getUncoveredArg() const {
3501 assert(hasUncoveredArg() && "no uncovered argument");
3502 return FirstUncoveredArg;
3503 }
3504
3505 void setAllCovered() {
3506 // A string has been found with all arguments covered, so clear out
3507 // the diagnostics.
3508 DiagnosticExprs.clear();
3509 FirstUncoveredArg = AllCovered;
3510 }
3511
3512 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
3513 assert(NewFirstUncoveredArg >= 0 && "Outside range");
3514
3515 // Don't update if a previous string covers all arguments.
3516 if (FirstUncoveredArg == AllCovered)
3517 return;
3518
3519 // UncoveredArgHandler tracks the highest uncovered argument index
3520 // and with it all the strings that match this index.
3521 if (NewFirstUncoveredArg == FirstUncoveredArg)
3522 DiagnosticExprs.push_back(StrExpr);
3523 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
3524 DiagnosticExprs.clear();
3525 DiagnosticExprs.push_back(StrExpr);
3526 FirstUncoveredArg = NewFirstUncoveredArg;
3527 }
3528 }
3529
3530 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
3531};
3532
Richard Smithd7293d72013-08-05 18:49:43 +00003533enum StringLiteralCheckType {
3534 SLCT_NotALiteral,
3535 SLCT_UncheckedLiteral,
3536 SLCT_CheckedLiteral
3537};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003538} // end anonymous namespace
Richard Smithd7293d72013-08-05 18:49:43 +00003539
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00003540static void CheckFormatString(Sema &S, const StringLiteral *FExpr,
3541 const Expr *OrigFormatExpr,
3542 ArrayRef<const Expr *> Args,
3543 bool HasVAListArg, unsigned format_idx,
3544 unsigned firstDataArg,
3545 Sema::FormatStringType Type,
3546 bool inFunctionCall,
3547 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003548 llvm::SmallBitVector &CheckedVarArgs,
3549 UncoveredArgHandler &UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00003550
Richard Smith55ce3522012-06-25 20:30:08 +00003551// Determine if an expression is a string literal or constant string.
3552// If this function returns false on the arguments to a function expecting a
3553// format string, we will usually need to emit a warning.
3554// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00003555static StringLiteralCheckType
3556checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
3557 bool HasVAListArg, unsigned format_idx,
3558 unsigned firstDataArg, Sema::FormatStringType Type,
3559 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003560 llvm::SmallBitVector &CheckedVarArgs,
3561 UncoveredArgHandler &UncoveredArg) {
Ted Kremenek808829352010-09-09 03:51:39 +00003562 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00003563 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00003564 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003565
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003566 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00003567
Richard Smithd7293d72013-08-05 18:49:43 +00003568 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00003569 // Technically -Wformat-nonliteral does not warn about this case.
3570 // The behavior of printf and friends in this case is implementation
3571 // dependent. Ideally if the format string cannot be null then
3572 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00003573 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00003574
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003575 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00003576 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003577 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00003578 // The expression is a literal if both sub-expressions were, and it was
3579 // completely checked only if both sub-expressions were checked.
3580 const AbstractConditionalOperator *C =
3581 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003582
3583 // Determine whether it is necessary to check both sub-expressions, for
3584 // example, because the condition expression is a constant that can be
3585 // evaluated at compile time.
3586 bool CheckLeft = true, CheckRight = true;
3587
3588 bool Cond;
3589 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
3590 if (Cond)
3591 CheckRight = false;
3592 else
3593 CheckLeft = false;
3594 }
3595
3596 StringLiteralCheckType Left;
3597 if (!CheckLeft)
3598 Left = SLCT_UncheckedLiteral;
3599 else {
3600 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
3601 HasVAListArg, format_idx, firstDataArg,
3602 Type, CallType, InFunctionCall,
3603 CheckedVarArgs, UncoveredArg);
3604 if (Left == SLCT_NotALiteral || !CheckRight)
3605 return Left;
3606 }
3607
Richard Smith55ce3522012-06-25 20:30:08 +00003608 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00003609 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003610 HasVAListArg, format_idx, firstDataArg,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003611 Type, CallType, InFunctionCall, CheckedVarArgs,
3612 UncoveredArg);
3613
3614 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003615 }
3616
3617 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00003618 E = cast<ImplicitCastExpr>(E)->getSubExpr();
3619 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003620 }
3621
John McCallc07a0c72011-02-17 10:25:35 +00003622 case Stmt::OpaqueValueExprClass:
3623 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
3624 E = src;
3625 goto tryAgain;
3626 }
Richard Smith55ce3522012-06-25 20:30:08 +00003627 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00003628
Ted Kremeneka8890832011-02-24 23:03:04 +00003629 case Stmt::PredefinedExprClass:
3630 // While __func__, etc., are technically not string literals, they
3631 // cannot contain format specifiers and thus are not a security
3632 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00003633 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00003634
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003635 case Stmt::DeclRefExprClass: {
3636 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00003637
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003638 // As an exception, do not flag errors for variables binding to
3639 // const string literals.
3640 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
3641 bool isConstant = false;
3642 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003643
Richard Smithd7293d72013-08-05 18:49:43 +00003644 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
3645 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00003646 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00003647 isConstant = T.isConstant(S.Context) &&
3648 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00003649 } else if (T->isObjCObjectPointerType()) {
3650 // In ObjC, there is usually no "const ObjectPointer" type,
3651 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00003652 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003653 }
Mike Stump11289f42009-09-09 15:08:12 +00003654
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003655 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00003656 if (const Expr *Init = VD->getAnyInitializer()) {
3657 // Look through initializers like const char c[] = { "foo" }
3658 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3659 if (InitList->isStringLiteralInit())
3660 Init = InitList->getInit(0)->IgnoreParenImpCasts();
3661 }
Richard Smithd7293d72013-08-05 18:49:43 +00003662 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003663 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003664 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003665 /*InFunctionCall*/false, CheckedVarArgs,
3666 UncoveredArg);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00003667 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003668 }
Mike Stump11289f42009-09-09 15:08:12 +00003669
Anders Carlssonb012ca92009-06-28 19:55:58 +00003670 // For vprintf* functions (i.e., HasVAListArg==true), we add a
3671 // special check to see if the format string is a function parameter
3672 // of the function calling the printf function. If the function
3673 // has an attribute indicating it is a printf-like function, then we
3674 // should suppress warnings concerning non-literals being used in a call
3675 // to a vprintf function. For example:
3676 //
3677 // void
3678 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
3679 // va_list ap;
3680 // va_start(ap, fmt);
3681 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
3682 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00003683 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003684 if (HasVAListArg) {
3685 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
3686 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
3687 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003688 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003689 // adjust for implicit parameter
3690 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
3691 if (MD->isInstance())
3692 ++PVIndex;
3693 // We also check if the formats are compatible.
3694 // We can't pass a 'scanf' string to a 'printf' function.
3695 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00003696 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00003697 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003698 }
3699 }
3700 }
3701 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003702 }
Mike Stump11289f42009-09-09 15:08:12 +00003703
Richard Smith55ce3522012-06-25 20:30:08 +00003704 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003705 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003706
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00003707 case Stmt::CallExprClass:
3708 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003709 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00003710 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
3711 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
3712 unsigned ArgIndex = FA->getFormatIdx();
3713 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
3714 if (MD->isInstance())
3715 --ArgIndex;
3716 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00003717
Richard Smithd7293d72013-08-05 18:49:43 +00003718 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003719 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00003720 Type, CallType, InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003721 CheckedVarArgs, UncoveredArg);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003722 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3723 unsigned BuiltinID = FD->getBuiltinID();
3724 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
3725 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
3726 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00003727 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003728 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003729 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003730 InFunctionCall, CheckedVarArgs,
3731 UncoveredArg);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003732 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003733 }
3734 }
Mike Stump11289f42009-09-09 15:08:12 +00003735
Richard Smith55ce3522012-06-25 20:30:08 +00003736 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003737 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003738 case Stmt::ObjCStringLiteralClass:
3739 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00003740 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003741
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003742 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003743 StrE = ObjCFExpr->getString();
3744 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003745 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00003746
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003747 if (StrE) {
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00003748 CheckFormatString(S, StrE, E, Args, HasVAListArg, format_idx,
3749 firstDataArg, Type, InFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003750 CheckedVarArgs, UncoveredArg);
Richard Smith55ce3522012-06-25 20:30:08 +00003751 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003752 }
Mike Stump11289f42009-09-09 15:08:12 +00003753
Richard Smith55ce3522012-06-25 20:30:08 +00003754 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003755 }
Mike Stump11289f42009-09-09 15:08:12 +00003756
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003757 default:
Richard Smith55ce3522012-06-25 20:30:08 +00003758 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003759 }
3760}
3761
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003762Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00003763 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003764 .Case("scanf", FST_Scanf)
3765 .Cases("printf", "printf0", FST_Printf)
3766 .Cases("NSString", "CFString", FST_NSString)
3767 .Case("strftime", FST_Strftime)
3768 .Case("strfmon", FST_Strfmon)
3769 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
Dimitry Andric6b5ed342015-02-19 22:32:33 +00003770 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00003771 .Case("os_trace", FST_OSTrace)
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003772 .Default(FST_Unknown);
3773}
3774
Jordan Rose3e0ec582012-07-19 18:10:23 +00003775/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00003776/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00003777/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003778bool Sema::CheckFormatArguments(const FormatAttr *Format,
3779 ArrayRef<const Expr *> Args,
3780 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003781 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003782 SourceLocation Loc, SourceRange Range,
3783 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00003784 FormatStringInfo FSI;
3785 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003786 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00003787 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00003788 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003789 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003790}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00003791
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003792bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003793 bool HasVAListArg, unsigned format_idx,
3794 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003795 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003796 SourceLocation Loc, SourceRange Range,
3797 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00003798 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003799 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003800 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00003801 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003802 }
Mike Stump11289f42009-09-09 15:08:12 +00003803
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003804 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00003805
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003806 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00003807 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003808 // Dynamically generated format strings are difficult to
3809 // automatically vet at compile time. Requiring that format strings
3810 // are string literals: (1) permits the checking of format strings by
3811 // the compiler and thereby (2) can practically remove the source of
3812 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00003813
Mike Stump11289f42009-09-09 15:08:12 +00003814 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00003815 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00003816 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00003817 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003818 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00003819 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00003820 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
3821 format_idx, firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003822 /*IsFunctionCall*/true, CheckedVarArgs,
3823 UncoveredArg);
3824
3825 // Generate a diagnostic where an uncovered argument is detected.
3826 if (UncoveredArg.hasUncoveredArg()) {
3827 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
3828 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
3829 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
3830 }
3831
Richard Smith55ce3522012-06-25 20:30:08 +00003832 if (CT != SLCT_NotALiteral)
3833 // Literal format string found, check done!
3834 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00003835
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00003836 // Strftime is particular as it always uses a single 'time' argument,
3837 // so it is safe to pass a non-literal string.
3838 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00003839 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00003840
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00003841 // Do not emit diag when the string param is a macro expansion and the
3842 // format is either NSString or CFString. This is a hack to prevent
3843 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
3844 // which are usually used in place of NS and CF string literals.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00003845 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
3846 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
Richard Smith55ce3522012-06-25 20:30:08 +00003847 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00003848
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003849 // If there are no arguments specified, warn with -Wformat-security, otherwise
3850 // warn only with -Wformat-nonliteral.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00003851 if (Args.size() == firstDataArg) {
Bob Wilson57819fc2016-03-15 20:56:38 +00003852 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
3853 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00003854 switch (Type) {
3855 default:
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00003856 break;
3857 case FST_Kprintf:
3858 case FST_FreeBSDKPrintf:
3859 case FST_Printf:
Bob Wilson57819fc2016-03-15 20:56:38 +00003860 Diag(FormatLoc, diag::note_format_security_fixit)
3861 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00003862 break;
3863 case FST_NSString:
Bob Wilson57819fc2016-03-15 20:56:38 +00003864 Diag(FormatLoc, diag::note_format_security_fixit)
3865 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00003866 break;
3867 }
3868 } else {
3869 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003870 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00003871 }
Richard Smith55ce3522012-06-25 20:30:08 +00003872 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003873}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003874
Ted Kremenekab278de2010-01-28 23:39:18 +00003875namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00003876class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
3877protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00003878 Sema &S;
3879 const StringLiteral *FExpr;
3880 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00003881 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00003882 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00003883 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00003884 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003885 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00003886 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00003887 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00003888 bool usesPositionalArgs;
3889 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00003890 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00003891 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00003892 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003893 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003894
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003895public:
Ted Kremenek02087932010-07-16 02:11:22 +00003896 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00003897 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003898 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003899 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003900 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003901 Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003902 llvm::SmallBitVector &CheckedVarArgs,
3903 UncoveredArgHandler &UncoveredArg)
Ted Kremenekab278de2010-01-28 23:39:18 +00003904 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003905 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
3906 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003907 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00003908 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00003909 inFunctionCall(inFunctionCall), CallType(callType),
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003910 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00003911 CoveredArgs.resize(numDataArgs);
3912 CoveredArgs.reset();
3913 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003914
Ted Kremenek019d2242010-01-29 01:50:07 +00003915 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003916
Ted Kremenek02087932010-07-16 02:11:22 +00003917 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003918 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003919
Jordan Rose92303592012-09-08 04:00:03 +00003920 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003921 const analyze_format_string::FormatSpecifier &FS,
3922 const analyze_format_string::ConversionSpecifier &CS,
3923 const char *startSpecifier, unsigned specifierLen,
3924 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00003925
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003926 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003927 const analyze_format_string::FormatSpecifier &FS,
3928 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003929
3930 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003931 const analyze_format_string::ConversionSpecifier &CS,
3932 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003933
Craig Toppere14c0f82014-03-12 04:55:44 +00003934 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00003935
Craig Toppere14c0f82014-03-12 04:55:44 +00003936 void HandleInvalidPosition(const char *startSpecifier,
3937 unsigned specifierLen,
3938 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00003939
Craig Toppere14c0f82014-03-12 04:55:44 +00003940 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00003941
Craig Toppere14c0f82014-03-12 04:55:44 +00003942 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003943
Richard Trieu03cf7b72011-10-28 00:41:25 +00003944 template <typename Range>
3945 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
3946 const Expr *ArgumentExpr,
3947 PartialDiagnostic PDiag,
3948 SourceLocation StringLoc,
3949 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00003950 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003951
Ted Kremenek02087932010-07-16 02:11:22 +00003952protected:
Ted Kremenekce815422010-07-19 21:25:57 +00003953 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
3954 const char *startSpec,
3955 unsigned specifierLen,
3956 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003957
3958 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
3959 const char *startSpec,
3960 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00003961
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003962 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00003963 CharSourceRange getSpecifierRange(const char *startSpecifier,
3964 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00003965 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003966
Ted Kremenek5739de72010-01-29 01:06:55 +00003967 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003968
3969 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
3970 const analyze_format_string::ConversionSpecifier &CS,
3971 const char *startSpecifier, unsigned specifierLen,
3972 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003973
3974 template <typename Range>
3975 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
3976 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00003977 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00003978};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003979} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00003980
Ted Kremenek02087932010-07-16 02:11:22 +00003981SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00003982 return OrigFormatExpr->getSourceRange();
3983}
3984
Ted Kremenek02087932010-07-16 02:11:22 +00003985CharSourceRange CheckFormatHandler::
3986getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00003987 SourceLocation Start = getLocationOfByte(startSpecifier);
3988 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
3989
3990 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003991 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00003992
3993 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003994}
3995
Ted Kremenek02087932010-07-16 02:11:22 +00003996SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003997 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00003998}
3999
Ted Kremenek02087932010-07-16 02:11:22 +00004000void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
4001 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00004002 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
4003 getLocationOfByte(startSpecifier),
4004 /*IsStringLocation*/true,
4005 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00004006}
4007
Jordan Rose92303592012-09-08 04:00:03 +00004008void CheckFormatHandler::HandleInvalidLengthModifier(
4009 const analyze_format_string::FormatSpecifier &FS,
4010 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00004011 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00004012 using namespace analyze_format_string;
4013
4014 const LengthModifier &LM = FS.getLengthModifier();
4015 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4016
4017 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00004018 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00004019 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004020 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00004021 getLocationOfByte(LM.getStart()),
4022 /*IsStringLocation*/true,
4023 getSpecifierRange(startSpecifier, specifierLen));
4024
4025 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4026 << FixedLM->toString()
4027 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
4028
4029 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004030 FixItHint Hint;
4031 if (DiagID == diag::warn_format_nonsensical_length)
4032 Hint = FixItHint::CreateRemoval(LMRange);
4033
4034 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00004035 getLocationOfByte(LM.getStart()),
4036 /*IsStringLocation*/true,
4037 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00004038 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00004039 }
4040}
4041
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004042void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00004043 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004044 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004045 using namespace analyze_format_string;
4046
4047 const LengthModifier &LM = FS.getLengthModifier();
4048 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4049
4050 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00004051 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00004052 if (FixedLM) {
4053 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4054 << LM.toString() << 0,
4055 getLocationOfByte(LM.getStart()),
4056 /*IsStringLocation*/true,
4057 getSpecifierRange(startSpecifier, specifierLen));
4058
4059 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4060 << FixedLM->toString()
4061 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
4062
4063 } else {
4064 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4065 << LM.toString() << 0,
4066 getLocationOfByte(LM.getStart()),
4067 /*IsStringLocation*/true,
4068 getSpecifierRange(startSpecifier, specifierLen));
4069 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004070}
4071
4072void CheckFormatHandler::HandleNonStandardConversionSpecifier(
4073 const analyze_format_string::ConversionSpecifier &CS,
4074 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00004075 using namespace analyze_format_string;
4076
4077 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00004078 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00004079 if (FixedCS) {
4080 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4081 << CS.toString() << /*conversion specifier*/1,
4082 getLocationOfByte(CS.getStart()),
4083 /*IsStringLocation*/true,
4084 getSpecifierRange(startSpecifier, specifierLen));
4085
4086 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
4087 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
4088 << FixedCS->toString()
4089 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
4090 } else {
4091 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4092 << CS.toString() << /*conversion specifier*/1,
4093 getLocationOfByte(CS.getStart()),
4094 /*IsStringLocation*/true,
4095 getSpecifierRange(startSpecifier, specifierLen));
4096 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004097}
4098
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00004099void CheckFormatHandler::HandlePosition(const char *startPos,
4100 unsigned posLen) {
4101 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
4102 getLocationOfByte(startPos),
4103 /*IsStringLocation*/true,
4104 getSpecifierRange(startPos, posLen));
4105}
4106
Ted Kremenekd1668192010-02-27 01:41:03 +00004107void
Ted Kremenek02087932010-07-16 02:11:22 +00004108CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
4109 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004110 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
4111 << (unsigned) p,
4112 getLocationOfByte(startPos), /*IsStringLocation*/true,
4113 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00004114}
4115
Ted Kremenek02087932010-07-16 02:11:22 +00004116void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00004117 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004118 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
4119 getLocationOfByte(startPos),
4120 /*IsStringLocation*/true,
4121 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00004122}
4123
Ted Kremenek02087932010-07-16 02:11:22 +00004124void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004125 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00004126 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00004127 EmitFormatDiagnostic(
4128 S.PDiag(diag::warn_printf_format_string_contains_null_char),
4129 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
4130 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00004131 }
Ted Kremenek02087932010-07-16 02:11:22 +00004132}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004133
Jordan Rose58bbe422012-07-19 18:10:08 +00004134// Note that this may return NULL if there was an error parsing or building
4135// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00004136const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004137 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00004138}
4139
4140void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004141 // Does the number of data arguments exceed the number of
4142 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00004143 if (!HasVAListArg) {
4144 // Find any arguments that weren't covered.
4145 CoveredArgs.flip();
4146 signed notCoveredArg = CoveredArgs.find_first();
4147 if (notCoveredArg >= 0) {
4148 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004149 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
4150 } else {
4151 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00004152 }
4153 }
4154}
4155
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004156void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
4157 const Expr *ArgExpr) {
4158 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
4159 "Invalid state");
4160
4161 if (!ArgExpr)
4162 return;
4163
4164 SourceLocation Loc = ArgExpr->getLocStart();
4165
4166 if (S.getSourceManager().isInSystemMacro(Loc))
4167 return;
4168
4169 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
4170 for (auto E : DiagnosticExprs)
4171 PDiag << E->getSourceRange();
4172
4173 CheckFormatHandler::EmitFormatDiagnostic(
4174 S, IsFunctionCall, DiagnosticExprs[0],
4175 PDiag, Loc, /*IsStringLocation*/false,
4176 DiagnosticExprs[0]->getSourceRange());
4177}
4178
Ted Kremenekce815422010-07-19 21:25:57 +00004179bool
4180CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
4181 SourceLocation Loc,
4182 const char *startSpec,
4183 unsigned specifierLen,
4184 const char *csStart,
4185 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00004186 bool keepGoing = true;
4187 if (argIndex < NumDataArgs) {
4188 // Consider the argument coverered, even though the specifier doesn't
4189 // make sense.
4190 CoveredArgs.set(argIndex);
4191 }
4192 else {
4193 // If argIndex exceeds the number of data arguments we
4194 // don't issue a warning because that is just a cascade of warnings (and
4195 // they may have intended '%%' anyway). We don't want to continue processing
4196 // the format string after this point, however, as we will like just get
4197 // gibberish when trying to match arguments.
4198 keepGoing = false;
4199 }
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00004200
4201 StringRef Specifier(csStart, csLen);
4202
4203 // If the specifier in non-printable, it could be the first byte of a UTF-8
4204 // sequence. In that case, print the UTF-8 code point. If not, print the byte
4205 // hex value.
4206 std::string CodePointStr;
4207 if (!llvm::sys::locale::isPrint(*csStart)) {
4208 UTF32 CodePoint;
4209 const UTF8 **B = reinterpret_cast<const UTF8 **>(&csStart);
4210 const UTF8 *E =
4211 reinterpret_cast<const UTF8 *>(csStart + csLen);
4212 ConversionResult Result =
4213 llvm::convertUTF8Sequence(B, E, &CodePoint, strictConversion);
4214
4215 if (Result != conversionOK) {
4216 unsigned char FirstChar = *csStart;
4217 CodePoint = (UTF32)FirstChar;
4218 }
4219
4220 llvm::raw_string_ostream OS(CodePointStr);
4221 if (CodePoint < 256)
4222 OS << "\\x" << llvm::format("%02x", CodePoint);
4223 else if (CodePoint <= 0xFFFF)
4224 OS << "\\u" << llvm::format("%04x", CodePoint);
4225 else
4226 OS << "\\U" << llvm::format("%08x", CodePoint);
4227 OS.flush();
4228 Specifier = CodePointStr;
4229 }
4230
4231 EmitFormatDiagnostic(
4232 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
4233 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
4234
Ted Kremenekce815422010-07-19 21:25:57 +00004235 return keepGoing;
4236}
4237
Richard Trieu03cf7b72011-10-28 00:41:25 +00004238void
4239CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
4240 const char *startSpec,
4241 unsigned specifierLen) {
4242 EmitFormatDiagnostic(
4243 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
4244 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
4245}
4246
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004247bool
4248CheckFormatHandler::CheckNumArgs(
4249 const analyze_format_string::FormatSpecifier &FS,
4250 const analyze_format_string::ConversionSpecifier &CS,
4251 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
4252
4253 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004254 PartialDiagnostic PDiag = FS.usesPositionalArg()
4255 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
4256 << (argIndex+1) << NumDataArgs)
4257 : S.PDiag(diag::warn_printf_insufficient_data_args);
4258 EmitFormatDiagnostic(
4259 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
4260 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004261
4262 // Since more arguments than conversion tokens are given, by extension
4263 // all arguments are covered, so mark this as so.
4264 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004265 return false;
4266 }
4267 return true;
4268}
4269
Richard Trieu03cf7b72011-10-28 00:41:25 +00004270template<typename Range>
4271void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
4272 SourceLocation Loc,
4273 bool IsStringLocation,
4274 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00004275 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004276 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00004277 Loc, IsStringLocation, StringRange, FixIt);
4278}
4279
4280/// \brief If the format string is not within the funcion call, emit a note
4281/// so that the function call and string are in diagnostic messages.
4282///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00004283/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00004284/// call and only one diagnostic message will be produced. Otherwise, an
4285/// extra note will be emitted pointing to location of the format string.
4286///
4287/// \param ArgumentExpr the expression that is passed as the format string
4288/// argument in the function call. Used for getting locations when two
4289/// diagnostics are emitted.
4290///
4291/// \param PDiag the callee should already have provided any strings for the
4292/// diagnostic message. This function only adds locations and fixits
4293/// to diagnostics.
4294///
4295/// \param Loc primary location for diagnostic. If two diagnostics are
4296/// required, one will be at Loc and a new SourceLocation will be created for
4297/// the other one.
4298///
4299/// \param IsStringLocation if true, Loc points to the format string should be
4300/// used for the note. Otherwise, Loc points to the argument list and will
4301/// be used with PDiag.
4302///
4303/// \param StringRange some or all of the string to highlight. This is
4304/// templated so it can accept either a CharSourceRange or a SourceRange.
4305///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00004306/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00004307template<typename Range>
4308void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
4309 const Expr *ArgumentExpr,
4310 PartialDiagnostic PDiag,
4311 SourceLocation Loc,
4312 bool IsStringLocation,
4313 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00004314 ArrayRef<FixItHint> FixIt) {
4315 if (InFunctionCall) {
4316 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
4317 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00004318 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00004319 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004320 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
4321 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00004322
4323 const Sema::SemaDiagnosticBuilder &Note =
4324 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
4325 diag::note_format_string_defined);
4326
4327 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00004328 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00004329 }
4330}
4331
Ted Kremenek02087932010-07-16 02:11:22 +00004332//===--- CHECK: Printf format string checking ------------------------------===//
4333
4334namespace {
4335class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004336 bool ObjCContext;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004337
Ted Kremenek02087932010-07-16 02:11:22 +00004338public:
4339 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
4340 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004341 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00004342 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004343 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004344 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00004345 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004346 llvm::SmallBitVector &CheckedVarArgs,
4347 UncoveredArgHandler &UncoveredArg)
Richard Smithd7293d72013-08-05 18:49:43 +00004348 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
4349 numDataArgs, beg, hasVAListArg, Args,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004350 formatIdx, inFunctionCall, CallType, CheckedVarArgs,
4351 UncoveredArg),
Richard Smithd7293d72013-08-05 18:49:43 +00004352 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00004353 {}
4354
Ted Kremenek02087932010-07-16 02:11:22 +00004355 bool HandleInvalidPrintfConversionSpecifier(
4356 const analyze_printf::PrintfSpecifier &FS,
4357 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004358 unsigned specifierLen) override;
4359
Ted Kremenek02087932010-07-16 02:11:22 +00004360 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
4361 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004362 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00004363 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
4364 const char *StartSpecifier,
4365 unsigned SpecifierLen,
4366 const Expr *E);
4367
Ted Kremenek02087932010-07-16 02:11:22 +00004368 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
4369 const char *startSpecifier, unsigned specifierLen);
4370 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
4371 const analyze_printf::OptionalAmount &Amt,
4372 unsigned type,
4373 const char *startSpecifier, unsigned specifierLen);
4374 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
4375 const analyze_printf::OptionalFlag &flag,
4376 const char *startSpecifier, unsigned specifierLen);
4377 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
4378 const analyze_printf::OptionalFlag &ignoredFlag,
4379 const analyze_printf::OptionalFlag &flag,
4380 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004381 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00004382 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00004383
4384 void HandleEmptyObjCModifierFlag(const char *startFlag,
4385 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00004386
Ted Kremenek2b417712015-07-02 05:39:16 +00004387 void HandleInvalidObjCModifierFlag(const char *startFlag,
4388 unsigned flagLen) override;
4389
4390 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
4391 const char *flagsEnd,
4392 const char *conversionPosition)
4393 override;
4394};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004395} // end anonymous namespace
Ted Kremenek02087932010-07-16 02:11:22 +00004396
4397bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
4398 const analyze_printf::PrintfSpecifier &FS,
4399 const char *startSpecifier,
4400 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004401 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00004402 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00004403
Ted Kremenekce815422010-07-19 21:25:57 +00004404 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
4405 getLocationOfByte(CS.getStart()),
4406 startSpecifier, specifierLen,
4407 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00004408}
4409
Ted Kremenek02087932010-07-16 02:11:22 +00004410bool CheckPrintfHandler::HandleAmount(
4411 const analyze_format_string::OptionalAmount &Amt,
4412 unsigned k, const char *startSpecifier,
4413 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004414 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004415 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00004416 unsigned argIndex = Amt.getArgIndex();
4417 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004418 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
4419 << k,
4420 getLocationOfByte(Amt.getStart()),
4421 /*IsStringLocation*/true,
4422 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00004423 // Don't do any more checking. We will just emit
4424 // spurious errors.
4425 return false;
4426 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004427
Ted Kremenek5739de72010-01-29 01:06:55 +00004428 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00004429 // Although not in conformance with C99, we also allow the argument to be
4430 // an 'unsigned int' as that is a reasonably safe case. GCC also
4431 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00004432 CoveredArgs.set(argIndex);
4433 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00004434 if (!Arg)
4435 return false;
4436
Ted Kremenek5739de72010-01-29 01:06:55 +00004437 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004438
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004439 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
4440 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004441
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004442 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004443 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004444 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00004445 << T << Arg->getSourceRange(),
4446 getLocationOfByte(Amt.getStart()),
4447 /*IsStringLocation*/true,
4448 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00004449 // Don't do any more checking. We will just emit
4450 // spurious errors.
4451 return false;
4452 }
4453 }
4454 }
4455 return true;
4456}
Ted Kremenek5739de72010-01-29 01:06:55 +00004457
Tom Careb49ec692010-06-17 19:00:27 +00004458void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00004459 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004460 const analyze_printf::OptionalAmount &Amt,
4461 unsigned type,
4462 const char *startSpecifier,
4463 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004464 const analyze_printf::PrintfConversionSpecifier &CS =
4465 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00004466
Richard Trieu03cf7b72011-10-28 00:41:25 +00004467 FixItHint fixit =
4468 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
4469 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
4470 Amt.getConstantLength()))
4471 : FixItHint();
4472
4473 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
4474 << type << CS.toString(),
4475 getLocationOfByte(Amt.getStart()),
4476 /*IsStringLocation*/true,
4477 getSpecifierRange(startSpecifier, specifierLen),
4478 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00004479}
4480
Ted Kremenek02087932010-07-16 02:11:22 +00004481void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004482 const analyze_printf::OptionalFlag &flag,
4483 const char *startSpecifier,
4484 unsigned specifierLen) {
4485 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004486 const analyze_printf::PrintfConversionSpecifier &CS =
4487 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00004488 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
4489 << flag.toString() << CS.toString(),
4490 getLocationOfByte(flag.getPosition()),
4491 /*IsStringLocation*/true,
4492 getSpecifierRange(startSpecifier, specifierLen),
4493 FixItHint::CreateRemoval(
4494 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00004495}
4496
4497void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00004498 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004499 const analyze_printf::OptionalFlag &ignoredFlag,
4500 const analyze_printf::OptionalFlag &flag,
4501 const char *startSpecifier,
4502 unsigned specifierLen) {
4503 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00004504 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
4505 << ignoredFlag.toString() << flag.toString(),
4506 getLocationOfByte(ignoredFlag.getPosition()),
4507 /*IsStringLocation*/true,
4508 getSpecifierRange(startSpecifier, specifierLen),
4509 FixItHint::CreateRemoval(
4510 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00004511}
4512
Ted Kremenek2b417712015-07-02 05:39:16 +00004513// void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
4514// bool IsStringLocation, Range StringRange,
4515// ArrayRef<FixItHint> Fixit = None);
4516
4517void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
4518 unsigned flagLen) {
4519 // Warn about an empty flag.
4520 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
4521 getLocationOfByte(startFlag),
4522 /*IsStringLocation*/true,
4523 getSpecifierRange(startFlag, flagLen));
4524}
4525
4526void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
4527 unsigned flagLen) {
4528 // Warn about an invalid flag.
4529 auto Range = getSpecifierRange(startFlag, flagLen);
4530 StringRef flag(startFlag, flagLen);
4531 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
4532 getLocationOfByte(startFlag),
4533 /*IsStringLocation*/true,
4534 Range, FixItHint::CreateRemoval(Range));
4535}
4536
4537void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
4538 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
4539 // Warn about using '[...]' without a '@' conversion.
4540 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
4541 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
4542 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
4543 getLocationOfByte(conversionPosition),
4544 /*IsStringLocation*/true,
4545 Range, FixItHint::CreateRemoval(Range));
4546}
4547
Richard Smith55ce3522012-06-25 20:30:08 +00004548// Determines if the specified is a C++ class or struct containing
4549// a member with the specified name and kind (e.g. a CXXMethodDecl named
4550// "c_str()").
4551template<typename MemberKind>
4552static llvm::SmallPtrSet<MemberKind*, 1>
4553CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
4554 const RecordType *RT = Ty->getAs<RecordType>();
4555 llvm::SmallPtrSet<MemberKind*, 1> Results;
4556
4557 if (!RT)
4558 return Results;
4559 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00004560 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00004561 return Results;
4562
Alp Tokerb6cc5922014-05-03 03:45:55 +00004563 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00004564 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00004565 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00004566
4567 // We just need to include all members of the right kind turned up by the
4568 // filter, at this point.
4569 if (S.LookupQualifiedName(R, RT->getDecl()))
4570 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
4571 NamedDecl *decl = (*I)->getUnderlyingDecl();
4572 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
4573 Results.insert(FK);
4574 }
4575 return Results;
4576}
4577
Richard Smith2868a732014-02-28 01:36:39 +00004578/// Check if we could call '.c_str()' on an object.
4579///
4580/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
4581/// allow the call, or if it would be ambiguous).
4582bool Sema::hasCStrMethod(const Expr *E) {
4583 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
4584 MethodSet Results =
4585 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
4586 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
4587 MI != ME; ++MI)
4588 if ((*MI)->getMinRequiredArguments() == 0)
4589 return true;
4590 return false;
4591}
4592
Richard Smith55ce3522012-06-25 20:30:08 +00004593// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004594// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00004595// Returns true when a c_str() conversion method is found.
4596bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00004597 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00004598 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
4599
4600 MethodSet Results =
4601 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
4602
4603 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
4604 MI != ME; ++MI) {
4605 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00004606 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00004607 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00004608 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00004609 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00004610 S.Diag(E->getLocStart(), diag::note_printf_c_str)
4611 << "c_str()"
4612 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
4613 return true;
4614 }
4615 }
4616
4617 return false;
4618}
4619
Ted Kremenekab278de2010-01-28 23:39:18 +00004620bool
Ted Kremenek02087932010-07-16 02:11:22 +00004621CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00004622 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00004623 const char *startSpecifier,
4624 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004625 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00004626 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004627 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00004628
Ted Kremenek6cd69422010-07-19 22:01:06 +00004629 if (FS.consumesDataArgument()) {
4630 if (atFirstArg) {
4631 atFirstArg = false;
4632 usesPositionalArgs = FS.usesPositionalArg();
4633 }
4634 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004635 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
4636 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00004637 return false;
4638 }
Ted Kremenek5739de72010-01-29 01:06:55 +00004639 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004640
Ted Kremenekd1668192010-02-27 01:41:03 +00004641 // First check if the field width, precision, and conversion specifier
4642 // have matching data arguments.
4643 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
4644 startSpecifier, specifierLen)) {
4645 return false;
4646 }
4647
4648 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
4649 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004650 return false;
4651 }
4652
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004653 if (!CS.consumesDataArgument()) {
4654 // FIXME: Technically specifying a precision or field width here
4655 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00004656 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004657 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004658
Ted Kremenek4a49d982010-02-26 19:18:41 +00004659 // Consume the argument.
4660 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00004661 if (argIndex < NumDataArgs) {
4662 // The check to see if the argIndex is valid will come later.
4663 // We set the bit here because we may exit early from this
4664 // function if we encounter some other error.
4665 CoveredArgs.set(argIndex);
4666 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00004667
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004668 // FreeBSD kernel extensions.
4669 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
4670 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
4671 // We need at least two arguments.
4672 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
4673 return false;
4674
4675 // Claim the second argument.
4676 CoveredArgs.set(argIndex + 1);
4677
4678 // Type check the first argument (int for %b, pointer for %D)
4679 const Expr *Ex = getDataArg(argIndex);
4680 const analyze_printf::ArgType &AT =
4681 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
4682 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
4683 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
4684 EmitFormatDiagnostic(
4685 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4686 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
4687 << false << Ex->getSourceRange(),
4688 Ex->getLocStart(), /*IsStringLocation*/false,
4689 getSpecifierRange(startSpecifier, specifierLen));
4690
4691 // Type check the second argument (char * for both %b and %D)
4692 Ex = getDataArg(argIndex + 1);
4693 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
4694 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
4695 EmitFormatDiagnostic(
4696 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4697 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
4698 << false << Ex->getSourceRange(),
4699 Ex->getLocStart(), /*IsStringLocation*/false,
4700 getSpecifierRange(startSpecifier, specifierLen));
4701
4702 return true;
4703 }
4704
Ted Kremenek4a49d982010-02-26 19:18:41 +00004705 // Check for using an Objective-C specific conversion specifier
4706 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004707 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00004708 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
4709 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00004710 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004711
Tom Careb49ec692010-06-17 19:00:27 +00004712 // Check for invalid use of field width
4713 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00004714 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00004715 startSpecifier, specifierLen);
4716 }
4717
4718 // Check for invalid use of precision
4719 if (!FS.hasValidPrecision()) {
4720 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
4721 startSpecifier, specifierLen);
4722 }
4723
4724 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00004725 if (!FS.hasValidThousandsGroupingPrefix())
4726 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004727 if (!FS.hasValidLeadingZeros())
4728 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
4729 if (!FS.hasValidPlusPrefix())
4730 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00004731 if (!FS.hasValidSpacePrefix())
4732 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004733 if (!FS.hasValidAlternativeForm())
4734 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
4735 if (!FS.hasValidLeftJustified())
4736 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
4737
4738 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00004739 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
4740 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
4741 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004742 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
4743 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
4744 startSpecifier, specifierLen);
4745
4746 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00004747 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00004748 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4749 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00004750 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004751 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00004752 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004753 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4754 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00004755
Jordan Rose92303592012-09-08 04:00:03 +00004756 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4757 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4758
Ted Kremenek9fcd8302010-01-29 01:43:31 +00004759 // The remaining checks depend on the data arguments.
4760 if (HasVAListArg)
4761 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004762
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004763 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00004764 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004765
Jordan Rose58bbe422012-07-19 18:10:08 +00004766 const Expr *Arg = getDataArg(argIndex);
4767 if (!Arg)
4768 return true;
4769
4770 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00004771}
4772
Jordan Roseaee34382012-09-05 22:56:26 +00004773static bool requiresParensToAddCast(const Expr *E) {
4774 // FIXME: We should have a general way to reason about operator
4775 // precedence and whether parens are actually needed here.
4776 // Take care of a few common cases where they aren't.
4777 const Expr *Inside = E->IgnoreImpCasts();
4778 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
4779 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
4780
4781 switch (Inside->getStmtClass()) {
4782 case Stmt::ArraySubscriptExprClass:
4783 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004784 case Stmt::CharacterLiteralClass:
4785 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004786 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004787 case Stmt::FloatingLiteralClass:
4788 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004789 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004790 case Stmt::ObjCArrayLiteralClass:
4791 case Stmt::ObjCBoolLiteralExprClass:
4792 case Stmt::ObjCBoxedExprClass:
4793 case Stmt::ObjCDictionaryLiteralClass:
4794 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004795 case Stmt::ObjCIvarRefExprClass:
4796 case Stmt::ObjCMessageExprClass:
4797 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004798 case Stmt::ObjCStringLiteralClass:
4799 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004800 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004801 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004802 case Stmt::UnaryOperatorClass:
4803 return false;
4804 default:
4805 return true;
4806 }
4807}
4808
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004809static std::pair<QualType, StringRef>
4810shouldNotPrintDirectly(const ASTContext &Context,
4811 QualType IntendedTy,
4812 const Expr *E) {
4813 // Use a 'while' to peel off layers of typedefs.
4814 QualType TyTy = IntendedTy;
4815 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
4816 StringRef Name = UserTy->getDecl()->getName();
4817 QualType CastTy = llvm::StringSwitch<QualType>(Name)
4818 .Case("NSInteger", Context.LongTy)
4819 .Case("NSUInteger", Context.UnsignedLongTy)
4820 .Case("SInt32", Context.IntTy)
4821 .Case("UInt32", Context.UnsignedIntTy)
4822 .Default(QualType());
4823
4824 if (!CastTy.isNull())
4825 return std::make_pair(CastTy, Name);
4826
4827 TyTy = UserTy->desugar();
4828 }
4829
4830 // Strip parens if necessary.
4831 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
4832 return shouldNotPrintDirectly(Context,
4833 PE->getSubExpr()->getType(),
4834 PE->getSubExpr());
4835
4836 // If this is a conditional expression, then its result type is constructed
4837 // via usual arithmetic conversions and thus there might be no necessary
4838 // typedef sugar there. Recurse to operands to check for NSInteger &
4839 // Co. usage condition.
4840 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4841 QualType TrueTy, FalseTy;
4842 StringRef TrueName, FalseName;
4843
4844 std::tie(TrueTy, TrueName) =
4845 shouldNotPrintDirectly(Context,
4846 CO->getTrueExpr()->getType(),
4847 CO->getTrueExpr());
4848 std::tie(FalseTy, FalseName) =
4849 shouldNotPrintDirectly(Context,
4850 CO->getFalseExpr()->getType(),
4851 CO->getFalseExpr());
4852
4853 if (TrueTy == FalseTy)
4854 return std::make_pair(TrueTy, TrueName);
4855 else if (TrueTy.isNull())
4856 return std::make_pair(FalseTy, FalseName);
4857 else if (FalseTy.isNull())
4858 return std::make_pair(TrueTy, TrueName);
4859 }
4860
4861 return std::make_pair(QualType(), StringRef());
4862}
4863
Richard Smith55ce3522012-06-25 20:30:08 +00004864bool
4865CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
4866 const char *StartSpecifier,
4867 unsigned SpecifierLen,
4868 const Expr *E) {
4869 using namespace analyze_format_string;
4870 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004871 // Now type check the data expression that matches the
4872 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004873 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
4874 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00004875 if (!AT.isValid())
4876 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00004877
Jordan Rose598ec092012-12-05 18:44:40 +00004878 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00004879 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
4880 ExprTy = TET->getUnderlyingExpr()->getType();
4881 }
4882
Seth Cantrellb4802962015-03-04 03:12:10 +00004883 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
4884
4885 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00004886 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00004887 }
Jordan Rose98709982012-06-04 22:48:57 +00004888
Jordan Rose22b74712012-09-05 22:56:19 +00004889 // Look through argument promotions for our error message's reported type.
4890 // This includes the integral and floating promotions, but excludes array
4891 // and function pointer decay; seeing that an argument intended to be a
4892 // string has type 'char [6]' is probably more confusing than 'char *'.
4893 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
4894 if (ICE->getCastKind() == CK_IntegralCast ||
4895 ICE->getCastKind() == CK_FloatingCast) {
4896 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00004897 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00004898
4899 // Check if we didn't match because of an implicit cast from a 'char'
4900 // or 'short' to an 'int'. This is done because printf is a varargs
4901 // function.
4902 if (ICE->getType() == S.Context.IntTy ||
4903 ICE->getType() == S.Context.UnsignedIntTy) {
4904 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00004905 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00004906 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00004907 }
Jordan Rose98709982012-06-04 22:48:57 +00004908 }
Jordan Rose598ec092012-12-05 18:44:40 +00004909 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
4910 // Special case for 'a', which has type 'int' in C.
4911 // Note, however, that we do /not/ want to treat multibyte constants like
4912 // 'MooV' as characters! This form is deprecated but still exists.
4913 if (ExprTy == S.Context.IntTy)
4914 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
4915 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00004916 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004917
Jordan Rosebc53ed12014-05-31 04:12:14 +00004918 // Look through enums to their underlying type.
4919 bool IsEnum = false;
4920 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
4921 ExprTy = EnumTy->getDecl()->getIntegerType();
4922 IsEnum = true;
4923 }
4924
Jordan Rose0e5badd2012-12-05 18:44:49 +00004925 // %C in an Objective-C context prints a unichar, not a wchar_t.
4926 // If the argument is an integer of some kind, believe the %C and suggest
4927 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00004928 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00004929 if (ObjCContext &&
4930 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
4931 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
4932 !ExprTy->isCharType()) {
4933 // 'unichar' is defined as a typedef of unsigned short, but we should
4934 // prefer using the typedef if it is visible.
4935 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00004936
4937 // While we are here, check if the value is an IntegerLiteral that happens
4938 // to be within the valid range.
4939 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
4940 const llvm::APInt &V = IL->getValue();
4941 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
4942 return true;
4943 }
4944
Jordan Rose0e5badd2012-12-05 18:44:49 +00004945 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
4946 Sema::LookupOrdinaryName);
4947 if (S.LookupName(Result, S.getCurScope())) {
4948 NamedDecl *ND = Result.getFoundDecl();
4949 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
4950 if (TD->getUnderlyingType() == IntendedTy)
4951 IntendedTy = S.Context.getTypedefType(TD);
4952 }
4953 }
4954 }
4955
4956 // Special-case some of Darwin's platform-independence types by suggesting
4957 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004958 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00004959 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004960 QualType CastTy;
4961 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
4962 if (!CastTy.isNull()) {
4963 IntendedTy = CastTy;
4964 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00004965 }
4966 }
4967
Jordan Rose22b74712012-09-05 22:56:19 +00004968 // We may be able to offer a FixItHint if it is a supported type.
4969 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00004970 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00004971 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004972
Jordan Rose22b74712012-09-05 22:56:19 +00004973 if (success) {
4974 // Get the fix string from the fixed format specifier
4975 SmallString<16> buf;
4976 llvm::raw_svector_ostream os(buf);
4977 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004978
Jordan Roseaee34382012-09-05 22:56:26 +00004979 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
4980
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004981 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00004982 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4983 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
4984 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4985 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00004986 // In this case, the specifier is wrong and should be changed to match
4987 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00004988 EmitFormatDiagnostic(S.PDiag(diag)
4989 << AT.getRepresentativeTypeName(S.Context)
4990 << IntendedTy << IsEnum << E->getSourceRange(),
4991 E->getLocStart(),
4992 /*IsStringLocation*/ false, SpecRange,
4993 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00004994 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00004995 // The canonical type for formatting this value is different from the
4996 // actual type of the expression. (This occurs, for example, with Darwin's
4997 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
4998 // should be printed as 'long' for 64-bit compatibility.)
4999 // Rather than emitting a normal format/argument mismatch, we want to
5000 // add a cast to the recommended type (and correct the format string
5001 // if necessary).
5002 SmallString<16> CastBuf;
5003 llvm::raw_svector_ostream CastFix(CastBuf);
5004 CastFix << "(";
5005 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
5006 CastFix << ")";
5007
5008 SmallVector<FixItHint,4> Hints;
5009 if (!AT.matchesType(S.Context, IntendedTy))
5010 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
5011
5012 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
5013 // If there's already a cast present, just replace it.
5014 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
5015 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
5016
5017 } else if (!requiresParensToAddCast(E)) {
5018 // If the expression has high enough precedence,
5019 // just write the C-style cast.
5020 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
5021 CastFix.str()));
5022 } else {
5023 // Otherwise, add parens around the expression as well as the cast.
5024 CastFix << "(";
5025 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
5026 CastFix.str()));
5027
Alp Tokerb6cc5922014-05-03 03:45:55 +00005028 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00005029 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
5030 }
5031
Jordan Rose0e5badd2012-12-05 18:44:49 +00005032 if (ShouldNotPrintDirectly) {
5033 // The expression has a type that should not be printed directly.
5034 // We extract the name from the typedef because we don't want to show
5035 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005036 StringRef Name;
5037 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
5038 Name = TypedefTy->getDecl()->getName();
5039 else
5040 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00005041 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00005042 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00005043 << E->getSourceRange(),
5044 E->getLocStart(), /*IsStringLocation=*/false,
5045 SpecRange, Hints);
5046 } else {
5047 // In this case, the expression could be printed using a different
5048 // specifier, but we've decided that the specifier is probably correct
5049 // and we should cast instead. Just use the normal warning message.
5050 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00005051 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5052 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00005053 << E->getSourceRange(),
5054 E->getLocStart(), /*IsStringLocation*/false,
5055 SpecRange, Hints);
5056 }
Jordan Roseaee34382012-09-05 22:56:26 +00005057 }
Jordan Rose22b74712012-09-05 22:56:19 +00005058 } else {
5059 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
5060 SpecifierLen);
5061 // Since the warning for passing non-POD types to variadic functions
5062 // was deferred until now, we emit a warning for non-POD
5063 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00005064 switch (S.isValidVarArgType(ExprTy)) {
5065 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00005066 case Sema::VAK_ValidInCXX11: {
5067 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5068 if (match == analyze_printf::ArgType::NoMatchPedantic) {
5069 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5070 }
Richard Smithd7293d72013-08-05 18:49:43 +00005071
Seth Cantrellb4802962015-03-04 03:12:10 +00005072 EmitFormatDiagnostic(
5073 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
5074 << IsEnum << CSR << E->getSourceRange(),
5075 E->getLocStart(), /*IsStringLocation*/ false, CSR);
5076 break;
5077 }
Richard Smithd7293d72013-08-05 18:49:43 +00005078 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00005079 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00005080 EmitFormatDiagnostic(
5081 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005082 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00005083 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00005084 << CallType
5085 << AT.getRepresentativeTypeName(S.Context)
5086 << CSR
5087 << E->getSourceRange(),
5088 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00005089 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00005090 break;
5091
5092 case Sema::VAK_Invalid:
5093 if (ExprTy->isObjCObjectType())
5094 EmitFormatDiagnostic(
5095 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
5096 << S.getLangOpts().CPlusPlus11
5097 << ExprTy
5098 << CallType
5099 << AT.getRepresentativeTypeName(S.Context)
5100 << CSR
5101 << E->getSourceRange(),
5102 E->getLocStart(), /*IsStringLocation*/false, CSR);
5103 else
5104 // FIXME: If this is an initializer list, suggest removing the braces
5105 // or inserting a cast to the target type.
5106 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
5107 << isa<InitListExpr>(E) << ExprTy << CallType
5108 << AT.getRepresentativeTypeName(S.Context)
5109 << E->getSourceRange();
5110 break;
5111 }
5112
5113 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
5114 "format string specifier index out of range");
5115 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005116 }
5117
Ted Kremenekab278de2010-01-28 23:39:18 +00005118 return true;
5119}
5120
Ted Kremenek02087932010-07-16 02:11:22 +00005121//===--- CHECK: Scanf format string checking ------------------------------===//
5122
5123namespace {
5124class CheckScanfHandler : public CheckFormatHandler {
5125public:
5126 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
5127 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005128 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005129 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005130 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00005131 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005132 llvm::SmallBitVector &CheckedVarArgs,
5133 UncoveredArgHandler &UncoveredArg)
Richard Smithd7293d72013-08-05 18:49:43 +00005134 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
5135 numDataArgs, beg, hasVAListArg,
5136 Args, formatIdx, inFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005137 CheckedVarArgs, UncoveredArg)
Jordan Rose3e0ec582012-07-19 18:10:23 +00005138 {}
Ted Kremenek02087932010-07-16 02:11:22 +00005139
5140 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
5141 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005142 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00005143
5144 bool HandleInvalidScanfConversionSpecifier(
5145 const analyze_scanf::ScanfSpecifier &FS,
5146 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005147 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00005148
Craig Toppere14c0f82014-03-12 04:55:44 +00005149 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00005150};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005151} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00005152
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00005153void CheckScanfHandler::HandleIncompleteScanList(const char *start,
5154 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005155 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
5156 getLocationOfByte(end), /*IsStringLocation*/true,
5157 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00005158}
5159
Ted Kremenekce815422010-07-19 21:25:57 +00005160bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
5161 const analyze_scanf::ScanfSpecifier &FS,
5162 const char *startSpecifier,
5163 unsigned specifierLen) {
5164
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005165 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00005166 FS.getConversionSpecifier();
5167
5168 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5169 getLocationOfByte(CS.getStart()),
5170 startSpecifier, specifierLen,
5171 CS.getStart(), CS.getLength());
5172}
5173
Ted Kremenek02087932010-07-16 02:11:22 +00005174bool CheckScanfHandler::HandleScanfSpecifier(
5175 const analyze_scanf::ScanfSpecifier &FS,
5176 const char *startSpecifier,
5177 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00005178 using namespace analyze_scanf;
5179 using namespace analyze_format_string;
5180
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005181 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00005182
Ted Kremenek6cd69422010-07-19 22:01:06 +00005183 // Handle case where '%' and '*' don't consume an argument. These shouldn't
5184 // be used to decide if we are using positional arguments consistently.
5185 if (FS.consumesDataArgument()) {
5186 if (atFirstArg) {
5187 atFirstArg = false;
5188 usesPositionalArgs = FS.usesPositionalArg();
5189 }
5190 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005191 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5192 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00005193 return false;
5194 }
Ted Kremenek02087932010-07-16 02:11:22 +00005195 }
5196
5197 // Check if the field with is non-zero.
5198 const OptionalAmount &Amt = FS.getFieldWidth();
5199 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
5200 if (Amt.getConstantAmount() == 0) {
5201 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
5202 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00005203 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
5204 getLocationOfByte(Amt.getStart()),
5205 /*IsStringLocation*/true, R,
5206 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00005207 }
5208 }
Seth Cantrellb4802962015-03-04 03:12:10 +00005209
Ted Kremenek02087932010-07-16 02:11:22 +00005210 if (!FS.consumesDataArgument()) {
5211 // FIXME: Technically specifying a precision or field width here
5212 // makes no sense. Worth issuing a warning at some point.
5213 return true;
5214 }
Seth Cantrellb4802962015-03-04 03:12:10 +00005215
Ted Kremenek02087932010-07-16 02:11:22 +00005216 // Consume the argument.
5217 unsigned argIndex = FS.getArgIndex();
5218 if (argIndex < NumDataArgs) {
5219 // The check to see if the argIndex is valid will come later.
5220 // We set the bit here because we may exit early from this
5221 // function if we encounter some other error.
5222 CoveredArgs.set(argIndex);
5223 }
Seth Cantrellb4802962015-03-04 03:12:10 +00005224
Ted Kremenek4407ea42010-07-20 20:04:47 +00005225 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00005226 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00005227 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5228 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00005229 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005230 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00005231 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005232 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5233 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005234
Jordan Rose92303592012-09-08 04:00:03 +00005235 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
5236 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5237
Ted Kremenek02087932010-07-16 02:11:22 +00005238 // The remaining checks depend on the data arguments.
5239 if (HasVAListArg)
5240 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00005241
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005242 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00005243 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00005244
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005245 // Check that the argument type matches the format specifier.
5246 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00005247 if (!Ex)
5248 return true;
5249
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00005250 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00005251
5252 if (!AT.isValid()) {
5253 return true;
5254 }
5255
Seth Cantrellb4802962015-03-04 03:12:10 +00005256 analyze_format_string::ArgType::MatchKind match =
5257 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00005258 if (match == analyze_format_string::ArgType::Match) {
5259 return true;
5260 }
Seth Cantrellb4802962015-03-04 03:12:10 +00005261
Seth Cantrell79340072015-03-04 05:58:08 +00005262 ScanfSpecifier fixedFS = FS;
5263 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
5264 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005265
Seth Cantrell79340072015-03-04 05:58:08 +00005266 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5267 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
5268 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5269 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005270
Seth Cantrell79340072015-03-04 05:58:08 +00005271 if (success) {
5272 // Get the fix string from the fixed format specifier.
5273 SmallString<128> buf;
5274 llvm::raw_svector_ostream os(buf);
5275 fixedFS.toString(os);
5276
5277 EmitFormatDiagnostic(
5278 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
5279 << Ex->getType() << false << Ex->getSourceRange(),
5280 Ex->getLocStart(),
5281 /*IsStringLocation*/ false,
5282 getSpecifierRange(startSpecifier, specifierLen),
5283 FixItHint::CreateReplacement(
5284 getSpecifierRange(startSpecifier, specifierLen), os.str()));
5285 } else {
5286 EmitFormatDiagnostic(S.PDiag(diag)
5287 << AT.getRepresentativeTypeName(S.Context)
5288 << Ex->getType() << false << Ex->getSourceRange(),
5289 Ex->getLocStart(),
5290 /*IsStringLocation*/ false,
5291 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005292 }
5293
Ted Kremenek02087932010-07-16 02:11:22 +00005294 return true;
5295}
5296
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005297static void CheckFormatString(Sema &S, const StringLiteral *FExpr,
5298 const Expr *OrigFormatExpr,
5299 ArrayRef<const Expr *> Args,
5300 bool HasVAListArg, unsigned format_idx,
5301 unsigned firstDataArg,
5302 Sema::FormatStringType Type,
5303 bool inFunctionCall,
5304 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005305 llvm::SmallBitVector &CheckedVarArgs,
5306 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00005307 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00005308 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005309 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005310 S, inFunctionCall, Args[format_idx],
5311 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00005312 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00005313 return;
5314 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005315
Ted Kremenekab278de2010-01-28 23:39:18 +00005316 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005317 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00005318 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005319 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005320 const ConstantArrayType *T =
5321 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005322 assert(T && "String literal not of constant array type!");
5323 size_t TypeSize = T->getSize().getZExtValue();
5324 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005325 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005326
5327 // Emit a warning if the string literal is truncated and does not contain an
5328 // embedded null character.
5329 if (TypeSize <= StrRef.size() &&
5330 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
5331 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005332 S, inFunctionCall, Args[format_idx],
5333 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005334 FExpr->getLocStart(),
5335 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
5336 return;
5337 }
5338
Ted Kremenekab278de2010-01-28 23:39:18 +00005339 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00005340 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005341 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005342 S, inFunctionCall, Args[format_idx],
5343 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00005344 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00005345 return;
5346 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005347
5348 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
5349 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSTrace) {
5350 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, firstDataArg,
5351 numDataArgs, (Type == Sema::FST_NSString ||
5352 Type == Sema::FST_OSTrace),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005353 Str, HasVAListArg, Args, format_idx,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005354 inFunctionCall, CallType, CheckedVarArgs,
5355 UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005356
Hans Wennborg23926bd2011-12-15 10:25:47 +00005357 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005358 S.getLangOpts(),
5359 S.Context.getTargetInfo(),
5360 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00005361 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005362 } else if (Type == Sema::FST_Scanf) {
5363 CheckScanfHandler H(S, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005364 Str, HasVAListArg, Args, format_idx,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005365 inFunctionCall, CallType, CheckedVarArgs,
5366 UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005367
Hans Wennborg23926bd2011-12-15 10:25:47 +00005368 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005369 S.getLangOpts(),
5370 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00005371 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005372 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00005373}
5374
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00005375bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
5376 // Str - The format string. NOTE: this is NOT null-terminated!
5377 StringRef StrRef = FExpr->getString();
5378 const char *Str = StrRef.data();
5379 // Account for cases where the string literal is truncated in a declaration.
5380 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
5381 assert(T && "String literal not of constant array type!");
5382 size_t TypeSize = T->getSize().getZExtValue();
5383 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
5384 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
5385 getLangOpts(),
5386 Context.getTargetInfo());
5387}
5388
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005389//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
5390
5391// Returns the related absolute value function that is larger, of 0 if one
5392// does not exist.
5393static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
5394 switch (AbsFunction) {
5395 default:
5396 return 0;
5397
5398 case Builtin::BI__builtin_abs:
5399 return Builtin::BI__builtin_labs;
5400 case Builtin::BI__builtin_labs:
5401 return Builtin::BI__builtin_llabs;
5402 case Builtin::BI__builtin_llabs:
5403 return 0;
5404
5405 case Builtin::BI__builtin_fabsf:
5406 return Builtin::BI__builtin_fabs;
5407 case Builtin::BI__builtin_fabs:
5408 return Builtin::BI__builtin_fabsl;
5409 case Builtin::BI__builtin_fabsl:
5410 return 0;
5411
5412 case Builtin::BI__builtin_cabsf:
5413 return Builtin::BI__builtin_cabs;
5414 case Builtin::BI__builtin_cabs:
5415 return Builtin::BI__builtin_cabsl;
5416 case Builtin::BI__builtin_cabsl:
5417 return 0;
5418
5419 case Builtin::BIabs:
5420 return Builtin::BIlabs;
5421 case Builtin::BIlabs:
5422 return Builtin::BIllabs;
5423 case Builtin::BIllabs:
5424 return 0;
5425
5426 case Builtin::BIfabsf:
5427 return Builtin::BIfabs;
5428 case Builtin::BIfabs:
5429 return Builtin::BIfabsl;
5430 case Builtin::BIfabsl:
5431 return 0;
5432
5433 case Builtin::BIcabsf:
5434 return Builtin::BIcabs;
5435 case Builtin::BIcabs:
5436 return Builtin::BIcabsl;
5437 case Builtin::BIcabsl:
5438 return 0;
5439 }
5440}
5441
5442// Returns the argument type of the absolute value function.
5443static QualType getAbsoluteValueArgumentType(ASTContext &Context,
5444 unsigned AbsType) {
5445 if (AbsType == 0)
5446 return QualType();
5447
5448 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
5449 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
5450 if (Error != ASTContext::GE_None)
5451 return QualType();
5452
5453 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
5454 if (!FT)
5455 return QualType();
5456
5457 if (FT->getNumParams() != 1)
5458 return QualType();
5459
5460 return FT->getParamType(0);
5461}
5462
5463// Returns the best absolute value function, or zero, based on type and
5464// current absolute value function.
5465static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
5466 unsigned AbsFunctionKind) {
5467 unsigned BestKind = 0;
5468 uint64_t ArgSize = Context.getTypeSize(ArgType);
5469 for (unsigned Kind = AbsFunctionKind; Kind != 0;
5470 Kind = getLargerAbsoluteValueFunction(Kind)) {
5471 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
5472 if (Context.getTypeSize(ParamType) >= ArgSize) {
5473 if (BestKind == 0)
5474 BestKind = Kind;
5475 else if (Context.hasSameType(ParamType, ArgType)) {
5476 BestKind = Kind;
5477 break;
5478 }
5479 }
5480 }
5481 return BestKind;
5482}
5483
5484enum AbsoluteValueKind {
5485 AVK_Integer,
5486 AVK_Floating,
5487 AVK_Complex
5488};
5489
5490static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
5491 if (T->isIntegralOrEnumerationType())
5492 return AVK_Integer;
5493 if (T->isRealFloatingType())
5494 return AVK_Floating;
5495 if (T->isAnyComplexType())
5496 return AVK_Complex;
5497
5498 llvm_unreachable("Type not integer, floating, or complex");
5499}
5500
5501// Changes the absolute value function to a different type. Preserves whether
5502// the function is a builtin.
5503static unsigned changeAbsFunction(unsigned AbsKind,
5504 AbsoluteValueKind ValueKind) {
5505 switch (ValueKind) {
5506 case AVK_Integer:
5507 switch (AbsKind) {
5508 default:
5509 return 0;
5510 case Builtin::BI__builtin_fabsf:
5511 case Builtin::BI__builtin_fabs:
5512 case Builtin::BI__builtin_fabsl:
5513 case Builtin::BI__builtin_cabsf:
5514 case Builtin::BI__builtin_cabs:
5515 case Builtin::BI__builtin_cabsl:
5516 return Builtin::BI__builtin_abs;
5517 case Builtin::BIfabsf:
5518 case Builtin::BIfabs:
5519 case Builtin::BIfabsl:
5520 case Builtin::BIcabsf:
5521 case Builtin::BIcabs:
5522 case Builtin::BIcabsl:
5523 return Builtin::BIabs;
5524 }
5525 case AVK_Floating:
5526 switch (AbsKind) {
5527 default:
5528 return 0;
5529 case Builtin::BI__builtin_abs:
5530 case Builtin::BI__builtin_labs:
5531 case Builtin::BI__builtin_llabs:
5532 case Builtin::BI__builtin_cabsf:
5533 case Builtin::BI__builtin_cabs:
5534 case Builtin::BI__builtin_cabsl:
5535 return Builtin::BI__builtin_fabsf;
5536 case Builtin::BIabs:
5537 case Builtin::BIlabs:
5538 case Builtin::BIllabs:
5539 case Builtin::BIcabsf:
5540 case Builtin::BIcabs:
5541 case Builtin::BIcabsl:
5542 return Builtin::BIfabsf;
5543 }
5544 case AVK_Complex:
5545 switch (AbsKind) {
5546 default:
5547 return 0;
5548 case Builtin::BI__builtin_abs:
5549 case Builtin::BI__builtin_labs:
5550 case Builtin::BI__builtin_llabs:
5551 case Builtin::BI__builtin_fabsf:
5552 case Builtin::BI__builtin_fabs:
5553 case Builtin::BI__builtin_fabsl:
5554 return Builtin::BI__builtin_cabsf;
5555 case Builtin::BIabs:
5556 case Builtin::BIlabs:
5557 case Builtin::BIllabs:
5558 case Builtin::BIfabsf:
5559 case Builtin::BIfabs:
5560 case Builtin::BIfabsl:
5561 return Builtin::BIcabsf;
5562 }
5563 }
5564 llvm_unreachable("Unable to convert function");
5565}
5566
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00005567static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005568 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
5569 if (!FnInfo)
5570 return 0;
5571
5572 switch (FDecl->getBuiltinID()) {
5573 default:
5574 return 0;
5575 case Builtin::BI__builtin_abs:
5576 case Builtin::BI__builtin_fabs:
5577 case Builtin::BI__builtin_fabsf:
5578 case Builtin::BI__builtin_fabsl:
5579 case Builtin::BI__builtin_labs:
5580 case Builtin::BI__builtin_llabs:
5581 case Builtin::BI__builtin_cabs:
5582 case Builtin::BI__builtin_cabsf:
5583 case Builtin::BI__builtin_cabsl:
5584 case Builtin::BIabs:
5585 case Builtin::BIlabs:
5586 case Builtin::BIllabs:
5587 case Builtin::BIfabs:
5588 case Builtin::BIfabsf:
5589 case Builtin::BIfabsl:
5590 case Builtin::BIcabs:
5591 case Builtin::BIcabsf:
5592 case Builtin::BIcabsl:
5593 return FDecl->getBuiltinID();
5594 }
5595 llvm_unreachable("Unknown Builtin type");
5596}
5597
5598// If the replacement is valid, emit a note with replacement function.
5599// Additionally, suggest including the proper header if not already included.
5600static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00005601 unsigned AbsKind, QualType ArgType) {
5602 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00005603 const char *HeaderName = nullptr;
5604 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00005605 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
5606 FunctionName = "std::abs";
5607 if (ArgType->isIntegralOrEnumerationType()) {
5608 HeaderName = "cstdlib";
5609 } else if (ArgType->isRealFloatingType()) {
5610 HeaderName = "cmath";
5611 } else {
5612 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005613 }
Richard Trieubeffb832014-04-15 23:47:53 +00005614
5615 // Lookup all std::abs
5616 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00005617 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00005618 R.suppressDiagnostics();
5619 S.LookupQualifiedName(R, Std);
5620
5621 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005622 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00005623 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
5624 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
5625 } else {
5626 FDecl = dyn_cast<FunctionDecl>(I);
5627 }
5628 if (!FDecl)
5629 continue;
5630
5631 // Found std::abs(), check that they are the right ones.
5632 if (FDecl->getNumParams() != 1)
5633 continue;
5634
5635 // Check that the parameter type can handle the argument.
5636 QualType ParamType = FDecl->getParamDecl(0)->getType();
5637 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
5638 S.Context.getTypeSize(ArgType) <=
5639 S.Context.getTypeSize(ParamType)) {
5640 // Found a function, don't need the header hint.
5641 EmitHeaderHint = false;
5642 break;
5643 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005644 }
Richard Trieubeffb832014-04-15 23:47:53 +00005645 }
5646 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00005647 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00005648 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
5649
5650 if (HeaderName) {
5651 DeclarationName DN(&S.Context.Idents.get(FunctionName));
5652 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
5653 R.suppressDiagnostics();
5654 S.LookupName(R, S.getCurScope());
5655
5656 if (R.isSingleResult()) {
5657 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
5658 if (FD && FD->getBuiltinID() == AbsKind) {
5659 EmitHeaderHint = false;
5660 } else {
5661 return;
5662 }
5663 } else if (!R.empty()) {
5664 return;
5665 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005666 }
5667 }
5668
5669 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00005670 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005671
Richard Trieubeffb832014-04-15 23:47:53 +00005672 if (!HeaderName)
5673 return;
5674
5675 if (!EmitHeaderHint)
5676 return;
5677
Alp Toker5d96e0a2014-07-11 20:53:51 +00005678 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
5679 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00005680}
5681
5682static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
5683 if (!FDecl)
5684 return false;
5685
5686 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
5687 return false;
5688
5689 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
5690
5691 while (ND && ND->isInlineNamespace()) {
5692 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005693 }
Richard Trieubeffb832014-04-15 23:47:53 +00005694
5695 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
5696 return false;
5697
5698 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
5699 return false;
5700
5701 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005702}
5703
5704// Warn when using the wrong abs() function.
5705void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
5706 const FunctionDecl *FDecl,
5707 IdentifierInfo *FnInfo) {
5708 if (Call->getNumArgs() != 1)
5709 return;
5710
5711 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00005712 bool IsStdAbs = IsFunctionStdAbs(FDecl);
5713 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005714 return;
5715
5716 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
5717 QualType ParamType = Call->getArg(0)->getType();
5718
Alp Toker5d96e0a2014-07-11 20:53:51 +00005719 // Unsigned types cannot be negative. Suggest removing the absolute value
5720 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005721 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00005722 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00005723 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005724 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
5725 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00005726 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005727 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
5728 return;
5729 }
5730
David Majnemer7f77eb92015-11-15 03:04:34 +00005731 // Taking the absolute value of a pointer is very suspicious, they probably
5732 // wanted to index into an array, dereference a pointer, call a function, etc.
5733 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
5734 unsigned DiagType = 0;
5735 if (ArgType->isFunctionType())
5736 DiagType = 1;
5737 else if (ArgType->isArrayType())
5738 DiagType = 2;
5739
5740 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
5741 return;
5742 }
5743
Richard Trieubeffb832014-04-15 23:47:53 +00005744 // std::abs has overloads which prevent most of the absolute value problems
5745 // from occurring.
5746 if (IsStdAbs)
5747 return;
5748
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005749 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
5750 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
5751
5752 // The argument and parameter are the same kind. Check if they are the right
5753 // size.
5754 if (ArgValueKind == ParamValueKind) {
5755 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
5756 return;
5757
5758 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
5759 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
5760 << FDecl << ArgType << ParamType;
5761
5762 if (NewAbsKind == 0)
5763 return;
5764
5765 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00005766 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005767 return;
5768 }
5769
5770 // ArgValueKind != ParamValueKind
5771 // The wrong type of absolute value function was used. Attempt to find the
5772 // proper one.
5773 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
5774 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
5775 if (NewAbsKind == 0)
5776 return;
5777
5778 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
5779 << FDecl << ParamValueKind << ArgValueKind;
5780
5781 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00005782 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005783}
5784
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005785//===--- CHECK: Standard memory functions ---------------------------------===//
5786
Nico Weber0e6daef2013-12-26 23:38:39 +00005787/// \brief Takes the expression passed to the size_t parameter of functions
5788/// such as memcmp, strncat, etc and warns if it's a comparison.
5789///
5790/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
5791static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
5792 IdentifierInfo *FnName,
5793 SourceLocation FnLoc,
5794 SourceLocation RParenLoc) {
5795 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
5796 if (!Size)
5797 return false;
5798
5799 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
5800 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
5801 return false;
5802
Nico Weber0e6daef2013-12-26 23:38:39 +00005803 SourceRange SizeRange = Size->getSourceRange();
5804 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
5805 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00005806 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00005807 << FnName << FixItHint::CreateInsertion(
5808 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00005809 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00005810 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00005811 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00005812 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
5813 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00005814
5815 return true;
5816}
5817
Reid Kleckner5fb5b122014-06-27 23:58:21 +00005818/// \brief Determine whether the given type is or contains a dynamic class type
5819/// (e.g., whether it has a vtable).
5820static const CXXRecordDecl *getContainedDynamicClass(QualType T,
5821 bool &IsContained) {
5822 // Look through array types while ignoring qualifiers.
5823 const Type *Ty = T->getBaseElementTypeUnsafe();
5824 IsContained = false;
5825
5826 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
5827 RD = RD ? RD->getDefinition() : nullptr;
Richard Trieu1c7237a2016-03-31 04:18:07 +00005828 if (!RD || RD->isInvalidDecl())
Reid Kleckner5fb5b122014-06-27 23:58:21 +00005829 return nullptr;
5830
5831 if (RD->isDynamicClass())
5832 return RD;
5833
5834 // Check all the fields. If any bases were dynamic, the class is dynamic.
5835 // It's impossible for a class to transitively contain itself by value, so
5836 // infinite recursion is impossible.
5837 for (auto *FD : RD->fields()) {
5838 bool SubContained;
5839 if (const CXXRecordDecl *ContainedRD =
5840 getContainedDynamicClass(FD->getType(), SubContained)) {
5841 IsContained = true;
5842 return ContainedRD;
5843 }
5844 }
5845
5846 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00005847}
5848
Chandler Carruth889ed862011-06-21 23:04:20 +00005849/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005850/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00005851static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00005852 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005853 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
5854 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
5855 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00005856
Craig Topperc3ec1492014-05-26 06:22:03 +00005857 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005858}
5859
Chandler Carruth889ed862011-06-21 23:04:20 +00005860/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00005861static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005862 if (const UnaryExprOrTypeTraitExpr *SizeOf =
5863 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
5864 if (SizeOf->getKind() == clang::UETT_SizeOf)
5865 return SizeOf->getTypeOfArgument();
5866
5867 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00005868}
5869
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005870/// \brief Check for dangerous or invalid arguments to memset().
5871///
Chandler Carruthac687262011-06-03 06:23:57 +00005872/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005873/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
5874/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005875///
5876/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005877void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00005878 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005879 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00005880 assert(BId != 0);
5881
Ted Kremenekb5fabb22011-04-28 01:38:02 +00005882 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00005883 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00005884 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00005885 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00005886 return;
5887
Anna Zaks22122702012-01-17 00:37:07 +00005888 unsigned LastArg = (BId == Builtin::BImemset ||
5889 BId == Builtin::BIstrndup ? 1 : 2);
5890 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00005891 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005892
Nico Weber0e6daef2013-12-26 23:38:39 +00005893 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
5894 Call->getLocStart(), Call->getRParenLoc()))
5895 return;
5896
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005897 // We have special checking when the length is a sizeof expression.
5898 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
5899 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
5900 llvm::FoldingSetNodeID SizeOfArgID;
5901
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005902 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
5903 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00005904 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005905
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005906 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00005907 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005908 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00005909 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00005910
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005911 // Never warn about void type pointers. This can be used to suppress
5912 // false positives.
5913 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005914 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005915
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005916 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
5917 // actually comparing the expressions for equality. Because computing the
5918 // expression IDs can be expensive, we only do this if the diagnostic is
5919 // enabled.
5920 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00005921 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
5922 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005923 // We only compute IDs for expressions if the warning is enabled, and
5924 // cache the sizeof arg's ID.
5925 if (SizeOfArgID == llvm::FoldingSetNodeID())
5926 SizeOfArg->Profile(SizeOfArgID, Context, true);
5927 llvm::FoldingSetNodeID DestID;
5928 Dest->Profile(DestID, Context, true);
5929 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00005930 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
5931 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005932 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00005933 StringRef ReadableName = FnName->getName();
5934
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005935 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00005936 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005937 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00005938 if (!PointeeTy->isIncompleteType() &&
5939 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005940 ActionIdx = 2; // If the pointee's size is sizeof(char),
5941 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00005942
5943 // If the function is defined as a builtin macro, do not show macro
5944 // expansion.
5945 SourceLocation SL = SizeOfArg->getExprLoc();
5946 SourceRange DSR = Dest->getSourceRange();
5947 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00005948 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00005949
5950 if (SM.isMacroArgExpansion(SL)) {
5951 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
5952 SL = SM.getSpellingLoc(SL);
5953 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
5954 SM.getSpellingLoc(DSR.getEnd()));
5955 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
5956 SM.getSpellingLoc(SSR.getEnd()));
5957 }
5958
Anna Zaksd08d9152012-05-30 23:14:52 +00005959 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005960 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00005961 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00005962 << PointeeTy
5963 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00005964 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00005965 << SSR);
5966 DiagRuntimeBehavior(SL, SizeOfArg,
5967 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
5968 << ActionIdx
5969 << SSR);
5970
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005971 break;
5972 }
5973 }
5974
5975 // Also check for cases where the sizeof argument is the exact same
5976 // type as the memory argument, and where it points to a user-defined
5977 // record type.
5978 if (SizeOfArgTy != QualType()) {
5979 if (PointeeTy->isRecordType() &&
5980 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
5981 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
5982 PDiag(diag::warn_sizeof_pointer_type_memaccess)
5983 << FnName << SizeOfArgTy << ArgIdx
5984 << PointeeTy << Dest->getSourceRange()
5985 << LenExpr->getSourceRange());
5986 break;
5987 }
Nico Weberc5e73862011-06-14 16:14:58 +00005988 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00005989 } else if (DestTy->isArrayType()) {
5990 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00005991 }
Nico Weberc5e73862011-06-14 16:14:58 +00005992
Nico Weberc44b35e2015-03-21 17:37:46 +00005993 if (PointeeTy == QualType())
5994 continue;
Anna Zaks22122702012-01-17 00:37:07 +00005995
Nico Weberc44b35e2015-03-21 17:37:46 +00005996 // Always complain about dynamic classes.
5997 bool IsContained;
5998 if (const CXXRecordDecl *ContainedRD =
5999 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00006000
Nico Weberc44b35e2015-03-21 17:37:46 +00006001 unsigned OperationType = 0;
6002 // "overwritten" if we're warning about the destination for any call
6003 // but memcmp; otherwise a verb appropriate to the call.
6004 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
6005 if (BId == Builtin::BImemcpy)
6006 OperationType = 1;
6007 else if(BId == Builtin::BImemmove)
6008 OperationType = 2;
6009 else if (BId == Builtin::BImemcmp)
6010 OperationType = 3;
6011 }
6012
John McCall31168b02011-06-15 23:02:42 +00006013 DiagRuntimeBehavior(
6014 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00006015 PDiag(diag::warn_dyn_class_memaccess)
6016 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
6017 << FnName << IsContained << ContainedRD << OperationType
6018 << Call->getCallee()->getSourceRange());
6019 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
6020 BId != Builtin::BImemset)
6021 DiagRuntimeBehavior(
6022 Dest->getExprLoc(), Dest,
6023 PDiag(diag::warn_arc_object_memaccess)
6024 << ArgIdx << FnName << PointeeTy
6025 << Call->getCallee()->getSourceRange());
6026 else
6027 continue;
6028
6029 DiagRuntimeBehavior(
6030 Dest->getExprLoc(), Dest,
6031 PDiag(diag::note_bad_memaccess_silence)
6032 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
6033 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006034 }
6035}
6036
Ted Kremenek6865f772011-08-18 20:55:45 +00006037// A little helper routine: ignore addition and subtraction of integer literals.
6038// This intentionally does not ignore all integer constant expressions because
6039// we don't want to remove sizeof().
6040static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
6041 Ex = Ex->IgnoreParenCasts();
6042
6043 for (;;) {
6044 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
6045 if (!BO || !BO->isAdditiveOp())
6046 break;
6047
6048 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
6049 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
6050
6051 if (isa<IntegerLiteral>(RHS))
6052 Ex = LHS;
6053 else if (isa<IntegerLiteral>(LHS))
6054 Ex = RHS;
6055 else
6056 break;
6057 }
6058
6059 return Ex;
6060}
6061
Anna Zaks13b08572012-08-08 21:42:23 +00006062static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
6063 ASTContext &Context) {
6064 // Only handle constant-sized or VLAs, but not flexible members.
6065 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
6066 // Only issue the FIXIT for arrays of size > 1.
6067 if (CAT->getSize().getSExtValue() <= 1)
6068 return false;
6069 } else if (!Ty->isVariableArrayType()) {
6070 return false;
6071 }
6072 return true;
6073}
6074
Ted Kremenek6865f772011-08-18 20:55:45 +00006075// Warn if the user has made the 'size' argument to strlcpy or strlcat
6076// be the size of the source, instead of the destination.
6077void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
6078 IdentifierInfo *FnName) {
6079
6080 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00006081 unsigned NumArgs = Call->getNumArgs();
6082 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00006083 return;
6084
6085 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
6086 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00006087 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00006088
6089 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
6090 Call->getLocStart(), Call->getRParenLoc()))
6091 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00006092
6093 // Look for 'strlcpy(dst, x, sizeof(x))'
6094 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
6095 CompareWithSrc = Ex;
6096 else {
6097 // Look for 'strlcpy(dst, x, strlen(x))'
6098 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00006099 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
6100 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00006101 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
6102 }
6103 }
6104
6105 if (!CompareWithSrc)
6106 return;
6107
6108 // Determine if the argument to sizeof/strlen is equal to the source
6109 // argument. In principle there's all kinds of things you could do
6110 // here, for instance creating an == expression and evaluating it with
6111 // EvaluateAsBooleanCondition, but this uses a more direct technique:
6112 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
6113 if (!SrcArgDRE)
6114 return;
6115
6116 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
6117 if (!CompareWithSrcDRE ||
6118 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
6119 return;
6120
6121 const Expr *OriginalSizeArg = Call->getArg(2);
6122 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
6123 << OriginalSizeArg->getSourceRange() << FnName;
6124
6125 // Output a FIXIT hint if the destination is an array (rather than a
6126 // pointer to an array). This could be enhanced to handle some
6127 // pointers if we know the actual size, like if DstArg is 'array+2'
6128 // we could say 'sizeof(array)-2'.
6129 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00006130 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00006131 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00006132
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00006133 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00006134 llvm::raw_svector_ostream OS(sizeString);
6135 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00006136 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00006137 OS << ")";
6138
6139 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
6140 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
6141 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00006142}
6143
Anna Zaks314cd092012-02-01 19:08:57 +00006144/// Check if two expressions refer to the same declaration.
6145static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
6146 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
6147 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
6148 return D1->getDecl() == D2->getDecl();
6149 return false;
6150}
6151
6152static const Expr *getStrlenExprArg(const Expr *E) {
6153 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6154 const FunctionDecl *FD = CE->getDirectCallee();
6155 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00006156 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00006157 return CE->getArg(0)->IgnoreParenCasts();
6158 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006159 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00006160}
6161
6162// Warn on anti-patterns as the 'size' argument to strncat.
6163// The correct size argument should look like following:
6164// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
6165void Sema::CheckStrncatArguments(const CallExpr *CE,
6166 IdentifierInfo *FnName) {
6167 // Don't crash if the user has the wrong number of arguments.
6168 if (CE->getNumArgs() < 3)
6169 return;
6170 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
6171 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
6172 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
6173
Nico Weber0e6daef2013-12-26 23:38:39 +00006174 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
6175 CE->getRParenLoc()))
6176 return;
6177
Anna Zaks314cd092012-02-01 19:08:57 +00006178 // Identify common expressions, which are wrongly used as the size argument
6179 // to strncat and may lead to buffer overflows.
6180 unsigned PatternType = 0;
6181 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
6182 // - sizeof(dst)
6183 if (referToTheSameDecl(SizeOfArg, DstArg))
6184 PatternType = 1;
6185 // - sizeof(src)
6186 else if (referToTheSameDecl(SizeOfArg, SrcArg))
6187 PatternType = 2;
6188 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
6189 if (BE->getOpcode() == BO_Sub) {
6190 const Expr *L = BE->getLHS()->IgnoreParenCasts();
6191 const Expr *R = BE->getRHS()->IgnoreParenCasts();
6192 // - sizeof(dst) - strlen(dst)
6193 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
6194 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
6195 PatternType = 1;
6196 // - sizeof(src) - (anything)
6197 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
6198 PatternType = 2;
6199 }
6200 }
6201
6202 if (PatternType == 0)
6203 return;
6204
Anna Zaks5069aa32012-02-03 01:27:37 +00006205 // Generate the diagnostic.
6206 SourceLocation SL = LenArg->getLocStart();
6207 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00006208 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00006209
6210 // If the function is defined as a builtin macro, do not show macro expansion.
6211 if (SM.isMacroArgExpansion(SL)) {
6212 SL = SM.getSpellingLoc(SL);
6213 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
6214 SM.getSpellingLoc(SR.getEnd()));
6215 }
6216
Anna Zaks13b08572012-08-08 21:42:23 +00006217 // Check if the destination is an array (rather than a pointer to an array).
6218 QualType DstTy = DstArg->getType();
6219 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
6220 Context);
6221 if (!isKnownSizeArray) {
6222 if (PatternType == 1)
6223 Diag(SL, diag::warn_strncat_wrong_size) << SR;
6224 else
6225 Diag(SL, diag::warn_strncat_src_size) << SR;
6226 return;
6227 }
6228
Anna Zaks314cd092012-02-01 19:08:57 +00006229 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00006230 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00006231 else
Anna Zaks5069aa32012-02-03 01:27:37 +00006232 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00006233
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00006234 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00006235 llvm::raw_svector_ostream OS(sizeString);
6236 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00006237 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00006238 OS << ") - ";
6239 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00006240 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00006241 OS << ") - 1";
6242
Anna Zaks5069aa32012-02-03 01:27:37 +00006243 Diag(SL, diag::note_strncat_wrong_size)
6244 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00006245}
6246
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006247//===--- CHECK: Return Address of Stack Variable --------------------------===//
6248
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006249static const Expr *EvalVal(const Expr *E,
6250 SmallVectorImpl<const DeclRefExpr *> &refVars,
6251 const Decl *ParentDecl);
6252static const Expr *EvalAddr(const Expr *E,
6253 SmallVectorImpl<const DeclRefExpr *> &refVars,
6254 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006255
6256/// CheckReturnStackAddr - Check if a return statement returns the address
6257/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006258static void
6259CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
6260 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00006261
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006262 const Expr *stackE = nullptr;
6263 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006264
6265 // Perform checking for returned stack addresses, local blocks,
6266 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00006267 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006268 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006269 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00006270 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006271 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006272 }
6273
Craig Topperc3ec1492014-05-26 06:22:03 +00006274 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006275 return; // Nothing suspicious was found.
6276
6277 SourceLocation diagLoc;
6278 SourceRange diagRange;
6279 if (refVars.empty()) {
6280 diagLoc = stackE->getLocStart();
6281 diagRange = stackE->getSourceRange();
6282 } else {
6283 // We followed through a reference variable. 'stackE' contains the
6284 // problematic expression but we will warn at the return statement pointing
6285 // at the reference variable. We will later display the "trail" of
6286 // reference variables using notes.
6287 diagLoc = refVars[0]->getLocStart();
6288 diagRange = refVars[0]->getSourceRange();
6289 }
6290
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006291 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
6292 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00006293 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006294 << DR->getDecl()->getDeclName() << diagRange;
6295 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006296 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006297 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006298 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006299 } else { // local temporary.
Craig Topperda7b27f2015-11-17 05:40:09 +00006300 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
6301 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006302 }
6303
6304 // Display the "trail" of reference variables that we followed until we
6305 // found the problematic expression using notes.
6306 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006307 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006308 // If this var binds to another reference var, show the range of the next
6309 // var, otherwise the var binds to the problematic expression, in which case
6310 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006311 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
6312 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006313 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
6314 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006315 }
6316}
6317
6318/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
6319/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006320/// to a location on the stack, a local block, an address of a label, or a
6321/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006322/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006323/// encounter a subexpression that (1) clearly does not lead to one of the
6324/// above problematic expressions (2) is something we cannot determine leads to
6325/// a problematic expression based on such local checking.
6326///
6327/// Both EvalAddr and EvalVal follow through reference variables to evaluate
6328/// the expression that they point to. Such variables are added to the
6329/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006330///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00006331/// EvalAddr processes expressions that are pointers that are used as
6332/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006333/// At the base case of the recursion is a check for the above problematic
6334/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006335///
6336/// This implementation handles:
6337///
6338/// * pointer-to-pointer casts
6339/// * implicit conversions from array references to pointers
6340/// * taking the address of fields
6341/// * arbitrary interplay between "&" and "*" operators
6342/// * pointer arithmetic from an address of a stack variable
6343/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006344static const Expr *EvalAddr(const Expr *E,
6345 SmallVectorImpl<const DeclRefExpr *> &refVars,
6346 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006347 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00006348 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006349
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006350 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00006351 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00006352 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006353 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00006354 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00006355
Peter Collingbourne91147592011-04-15 00:35:48 +00006356 E = E->IgnoreParens();
6357
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006358 // Our "symbolic interpreter" is just a dispatch off the currently
6359 // viewed AST node. We then recursively traverse the AST by calling
6360 // EvalAddr and EvalVal appropriately.
6361 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006362 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006363 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006364
Richard Smith40f08eb2014-01-30 22:05:38 +00006365 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00006366 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00006367 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00006368
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006369 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006370 // If this is a reference variable, follow through to the expression that
6371 // it points to.
6372 if (V->hasLocalStorage() &&
6373 V->getType()->isReferenceType() && V->hasInit()) {
6374 // Add the reference variable to the "trail".
6375 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006376 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006377 }
6378
Craig Topperc3ec1492014-05-26 06:22:03 +00006379 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006380 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006381
Chris Lattner934edb22007-12-28 05:31:15 +00006382 case Stmt::UnaryOperatorClass: {
6383 // The only unary operator that make sense to handle here
6384 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006385 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006386
John McCalle3027922010-08-25 11:45:40 +00006387 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006388 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006389 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006390 }
Mike Stump11289f42009-09-09 15:08:12 +00006391
Chris Lattner934edb22007-12-28 05:31:15 +00006392 case Stmt::BinaryOperatorClass: {
6393 // Handle pointer arithmetic. All other binary operators are not valid
6394 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006395 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00006396 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00006397
John McCalle3027922010-08-25 11:45:40 +00006398 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00006399 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006400
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006401 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00006402
6403 // Determine which argument is the real pointer base. It could be
6404 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006405 if (!Base->getType()->isPointerType())
6406 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00006407
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006408 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006409 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00006410 }
Steve Naroff2752a172008-09-10 19:17:48 +00006411
Chris Lattner934edb22007-12-28 05:31:15 +00006412 // For conditional operators we need to see if either the LHS or RHS are
6413 // valid DeclRefExpr*s. If one of them is valid, we return it.
6414 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006415 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006416
Chris Lattner934edb22007-12-28 05:31:15 +00006417 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006418 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006419 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006420 // In C++, we can have a throw-expression, which has 'void' type.
6421 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006422 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006423 return LHS;
6424 }
Chris Lattner934edb22007-12-28 05:31:15 +00006425
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006426 // In C++, we can have a throw-expression, which has 'void' type.
6427 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00006428 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006429
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006430 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00006431 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006432
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006433 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00006434 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006435 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00006436 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006437
6438 case Stmt::AddrLabelExprClass:
6439 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00006440
John McCall28fc7092011-11-10 05:35:25 +00006441 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006442 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
6443 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00006444
Ted Kremenekc3b4c522008-08-07 00:49:01 +00006445 // For casts, we need to handle conversions from arrays to
6446 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00006447 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00006448 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00006449 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00006450 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00006451 case Stmt::CXXStaticCastExprClass:
6452 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00006453 case Stmt::CXXConstCastExprClass:
6454 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006455 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00006456 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00006457 case CK_LValueToRValue:
6458 case CK_NoOp:
6459 case CK_BaseToDerived:
6460 case CK_DerivedToBase:
6461 case CK_UncheckedDerivedToBase:
6462 case CK_Dynamic:
6463 case CK_CPointerToObjCPointerCast:
6464 case CK_BlockPointerToObjCPointerCast:
6465 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006466 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00006467
6468 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006469 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00006470
Richard Trieudadefde2014-07-02 04:39:38 +00006471 case CK_BitCast:
6472 if (SubExpr->getType()->isAnyPointerType() ||
6473 SubExpr->getType()->isBlockPointerType() ||
6474 SubExpr->getType()->isObjCQualifiedIdType())
6475 return EvalAddr(SubExpr, refVars, ParentDecl);
6476 else
6477 return nullptr;
6478
Eli Friedman8195ad72012-02-23 23:04:32 +00006479 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00006480 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00006481 }
Chris Lattner934edb22007-12-28 05:31:15 +00006482 }
Mike Stump11289f42009-09-09 15:08:12 +00006483
Douglas Gregorfe314812011-06-21 17:03:29 +00006484 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006485 if (const Expr *Result =
6486 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
6487 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00006488 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00006489 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006490
Chris Lattner934edb22007-12-28 05:31:15 +00006491 // Everything else: we simply don't reason about them.
6492 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00006493 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00006494 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006495}
Mike Stump11289f42009-09-09 15:08:12 +00006496
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006497/// EvalVal - This function is complements EvalAddr in the mutual recursion.
6498/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006499static const Expr *EvalVal(const Expr *E,
6500 SmallVectorImpl<const DeclRefExpr *> &refVars,
6501 const Decl *ParentDecl) {
6502 do {
6503 // We should only be called for evaluating non-pointer expressions, or
6504 // expressions with a pointer type that are not used as references but
6505 // instead
6506 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00006507
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006508 // Our "symbolic interpreter" is just a dispatch off the currently
6509 // viewed AST node. We then recursively traverse the AST by calling
6510 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00006511
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006512 E = E->IgnoreParens();
6513 switch (E->getStmtClass()) {
6514 case Stmt::ImplicitCastExprClass: {
6515 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
6516 if (IE->getValueKind() == VK_LValue) {
6517 E = IE->getSubExpr();
6518 continue;
6519 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006520 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006521 }
Richard Smith40f08eb2014-01-30 22:05:38 +00006522
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006523 case Stmt::ExprWithCleanupsClass:
6524 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
6525 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006526
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006527 case Stmt::DeclRefExprClass: {
6528 // When we hit a DeclRefExpr we are looking at code that refers to a
6529 // variable's name. If it's not a reference variable we check if it has
6530 // local storage within the function, and if so, return the expression.
6531 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6532
6533 // If we leave the immediate function, the lifetime isn't about to end.
6534 if (DR->refersToEnclosingVariableOrCapture())
6535 return nullptr;
6536
6537 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
6538 // Check if it refers to itself, e.g. "int& i = i;".
6539 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006540 return DR;
6541
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006542 if (V->hasLocalStorage()) {
6543 if (!V->getType()->isReferenceType())
6544 return DR;
6545
6546 // Reference variable, follow through to the expression that
6547 // it points to.
6548 if (V->hasInit()) {
6549 // Add the reference variable to the "trail".
6550 refVars.push_back(DR);
6551 return EvalVal(V->getInit(), refVars, V);
6552 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006553 }
6554 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006555
6556 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006557 }
Mike Stump11289f42009-09-09 15:08:12 +00006558
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006559 case Stmt::UnaryOperatorClass: {
6560 // The only unary operator that make sense to handle here
6561 // is Deref. All others don't resolve to a "name." This includes
6562 // handling all sorts of rvalues passed to a unary operator.
6563 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006564
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006565 if (U->getOpcode() == UO_Deref)
6566 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00006567
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006568 return nullptr;
6569 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006570
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006571 case Stmt::ArraySubscriptExprClass: {
6572 // Array subscripts are potential references to data on the stack. We
6573 // retrieve the DeclRefExpr* for the array variable if it indeed
6574 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00006575 const auto *ASE = cast<ArraySubscriptExpr>(E);
6576 if (ASE->isTypeDependent())
6577 return nullptr;
6578 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006579 }
Mike Stump11289f42009-09-09 15:08:12 +00006580
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006581 case Stmt::OMPArraySectionExprClass: {
6582 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
6583 ParentDecl);
6584 }
Mike Stump11289f42009-09-09 15:08:12 +00006585
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006586 case Stmt::ConditionalOperatorClass: {
6587 // For conditional operators we need to see if either the LHS or RHS are
6588 // non-NULL Expr's. If one is non-NULL, we return it.
6589 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00006590
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006591 // Handle the GNU extension for missing LHS.
6592 if (const Expr *LHSExpr = C->getLHS()) {
6593 // In C++, we can have a throw-expression, which has 'void' type.
6594 if (!LHSExpr->getType()->isVoidType())
6595 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
6596 return LHS;
6597 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006598
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006599 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006600 if (C->getRHS()->getType()->isVoidType())
6601 return nullptr;
6602
6603 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006604 }
6605
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006606 // Accesses to members are potential references to data on the stack.
6607 case Stmt::MemberExprClass: {
6608 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00006609
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006610 // Check for indirect access. We only want direct field accesses.
6611 if (M->isArrow())
6612 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006613
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006614 // Check whether the member type is itself a reference, in which case
6615 // we're not going to refer to the member, but to what the member refers
6616 // to.
6617 if (M->getMemberDecl()->getType()->isReferenceType())
6618 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006619
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006620 return EvalVal(M->getBase(), refVars, ParentDecl);
6621 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00006622
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006623 case Stmt::MaterializeTemporaryExprClass:
6624 if (const Expr *Result =
6625 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
6626 refVars, ParentDecl))
6627 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006628 return E;
6629
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006630 default:
6631 // Check that we don't return or take the address of a reference to a
6632 // temporary. This is only useful in C++.
6633 if (!E->isTypeDependent() && E->isRValue())
6634 return E;
6635
6636 // Everything else: we simply don't reason about them.
6637 return nullptr;
6638 }
6639 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006640}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006641
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006642void
6643Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
6644 SourceLocation ReturnLoc,
6645 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00006646 const AttrVec *Attrs,
6647 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006648 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
6649
6650 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00006651 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
6652 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00006653 CheckNonNullExpr(*this, RetValExp))
6654 Diag(ReturnLoc, diag::warn_null_ret)
6655 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00006656
6657 // C++11 [basic.stc.dynamic.allocation]p4:
6658 // If an allocation function declared with a non-throwing
6659 // exception-specification fails to allocate storage, it shall return
6660 // a null pointer. Any other allocation function that fails to allocate
6661 // storage shall indicate failure only by throwing an exception [...]
6662 if (FD) {
6663 OverloadedOperatorKind Op = FD->getOverloadedOperator();
6664 if (Op == OO_New || Op == OO_Array_New) {
6665 const FunctionProtoType *Proto
6666 = FD->getType()->castAs<FunctionProtoType>();
6667 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
6668 CheckNonNullExpr(*this, RetValExp))
6669 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
6670 << FD << getLangOpts().CPlusPlus11;
6671 }
6672 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006673}
6674
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006675//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
6676
6677/// Check for comparisons of floating point operands using != and ==.
6678/// Issue a warning if these are no self-comparisons, as they are not likely
6679/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00006680void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00006681 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
6682 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006683
6684 // Special case: check for x == x (which is OK).
6685 // Do not emit warnings for such cases.
6686 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
6687 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
6688 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00006689 return;
Mike Stump11289f42009-09-09 15:08:12 +00006690
Ted Kremenekeda40e22007-11-29 00:59:04 +00006691 // Special case: check for comparisons against literals that can be exactly
6692 // represented by APFloat. In such cases, do not emit a warning. This
6693 // is a heuristic: often comparison against such literals are used to
6694 // detect if a value in a variable has not changed. This clearly can
6695 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00006696 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
6697 if (FLL->isExact())
6698 return;
6699 } else
6700 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
6701 if (FLR->isExact())
6702 return;
Mike Stump11289f42009-09-09 15:08:12 +00006703
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006704 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00006705 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00006706 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00006707 return;
Mike Stump11289f42009-09-09 15:08:12 +00006708
David Blaikie1f4ff152012-07-16 20:47:22 +00006709 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00006710 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00006711 return;
Mike Stump11289f42009-09-09 15:08:12 +00006712
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006713 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00006714 Diag(Loc, diag::warn_floatingpoint_eq)
6715 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006716}
John McCallca01b222010-01-04 23:21:16 +00006717
John McCall70aa5392010-01-06 05:24:50 +00006718//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
6719//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00006720
John McCall70aa5392010-01-06 05:24:50 +00006721namespace {
John McCallca01b222010-01-04 23:21:16 +00006722
John McCall70aa5392010-01-06 05:24:50 +00006723/// Structure recording the 'active' range of an integer-valued
6724/// expression.
6725struct IntRange {
6726 /// The number of bits active in the int.
6727 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00006728
John McCall70aa5392010-01-06 05:24:50 +00006729 /// True if the int is known not to have negative values.
6730 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00006731
John McCall70aa5392010-01-06 05:24:50 +00006732 IntRange(unsigned Width, bool NonNegative)
6733 : Width(Width), NonNegative(NonNegative)
6734 {}
John McCallca01b222010-01-04 23:21:16 +00006735
John McCall817d4af2010-11-10 23:38:19 +00006736 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00006737 static IntRange forBoolType() {
6738 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00006739 }
6740
John McCall817d4af2010-11-10 23:38:19 +00006741 /// Returns the range of an opaque value of the given integral type.
6742 static IntRange forValueOfType(ASTContext &C, QualType T) {
6743 return forValueOfCanonicalType(C,
6744 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00006745 }
6746
John McCall817d4af2010-11-10 23:38:19 +00006747 /// Returns the range of an opaque value of a canonical integral type.
6748 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00006749 assert(T->isCanonicalUnqualified());
6750
6751 if (const VectorType *VT = dyn_cast<VectorType>(T))
6752 T = VT->getElementType().getTypePtr();
6753 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
6754 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00006755 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
6756 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00006757
David Majnemer6a426652013-06-07 22:07:20 +00006758 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00006759 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00006760 EnumDecl *Enum = ET->getDecl();
6761 if (!Enum->isCompleteDefinition())
6762 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00006763
David Majnemer6a426652013-06-07 22:07:20 +00006764 unsigned NumPositive = Enum->getNumPositiveBits();
6765 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00006766
David Majnemer6a426652013-06-07 22:07:20 +00006767 if (NumNegative == 0)
6768 return IntRange(NumPositive, true/*NonNegative*/);
6769 else
6770 return IntRange(std::max(NumPositive + 1, NumNegative),
6771 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00006772 }
John McCall70aa5392010-01-06 05:24:50 +00006773
6774 const BuiltinType *BT = cast<BuiltinType>(T);
6775 assert(BT->isInteger());
6776
6777 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
6778 }
6779
John McCall817d4af2010-11-10 23:38:19 +00006780 /// Returns the "target" range of a canonical integral type, i.e.
6781 /// the range of values expressible in the type.
6782 ///
6783 /// This matches forValueOfCanonicalType except that enums have the
6784 /// full range of their type, not the range of their enumerators.
6785 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
6786 assert(T->isCanonicalUnqualified());
6787
6788 if (const VectorType *VT = dyn_cast<VectorType>(T))
6789 T = VT->getElementType().getTypePtr();
6790 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
6791 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00006792 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
6793 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00006794 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00006795 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00006796
6797 const BuiltinType *BT = cast<BuiltinType>(T);
6798 assert(BT->isInteger());
6799
6800 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
6801 }
6802
6803 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00006804 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00006805 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00006806 L.NonNegative && R.NonNegative);
6807 }
6808
John McCall817d4af2010-11-10 23:38:19 +00006809 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00006810 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00006811 return IntRange(std::min(L.Width, R.Width),
6812 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00006813 }
6814};
6815
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006816IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006817 if (value.isSigned() && value.isNegative())
6818 return IntRange(value.getMinSignedBits(), false);
6819
6820 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00006821 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00006822
6823 // isNonNegative() just checks the sign bit without considering
6824 // signedness.
6825 return IntRange(value.getActiveBits(), true);
6826}
6827
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006828IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
6829 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006830 if (result.isInt())
6831 return GetValueRange(C, result.getInt(), MaxWidth);
6832
6833 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00006834 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
6835 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
6836 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
6837 R = IntRange::join(R, El);
6838 }
John McCall70aa5392010-01-06 05:24:50 +00006839 return R;
6840 }
6841
6842 if (result.isComplexInt()) {
6843 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
6844 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
6845 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00006846 }
6847
6848 // This can happen with lossless casts to intptr_t of "based" lvalues.
6849 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00006850 // FIXME: The only reason we need to pass the type in here is to get
6851 // the sign right on this one case. It would be nice if APValue
6852 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006853 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00006854 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00006855}
John McCall70aa5392010-01-06 05:24:50 +00006856
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006857QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00006858 QualType Ty = E->getType();
6859 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
6860 Ty = AtomicRHS->getValueType();
6861 return Ty;
6862}
6863
John McCall70aa5392010-01-06 05:24:50 +00006864/// Pseudo-evaluate the given integer expression, estimating the
6865/// range of values it might take.
6866///
6867/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006868IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006869 E = E->IgnoreParens();
6870
6871 // Try a full evaluation first.
6872 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00006873 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00006874 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00006875
6876 // I think we only want to look through implicit casts here; if the
6877 // user has an explicit widening cast, we should treat the value as
6878 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006879 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00006880 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00006881 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
6882
Eli Friedmane6d33952013-07-08 20:20:06 +00006883 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00006884
George Burgess IVdf1ed002016-01-13 01:52:39 +00006885 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
6886 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00006887
John McCall70aa5392010-01-06 05:24:50 +00006888 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00006889 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00006890 return OutputTypeRange;
6891
6892 IntRange SubRange
6893 = GetExprRange(C, CE->getSubExpr(),
6894 std::min(MaxWidth, OutputTypeRange.Width));
6895
6896 // Bail out if the subexpr's range is as wide as the cast type.
6897 if (SubRange.Width >= OutputTypeRange.Width)
6898 return OutputTypeRange;
6899
6900 // Otherwise, we take the smaller width, and we're non-negative if
6901 // either the output type or the subexpr is.
6902 return IntRange(SubRange.Width,
6903 SubRange.NonNegative || OutputTypeRange.NonNegative);
6904 }
6905
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006906 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00006907 // If we can fold the condition, just take that operand.
6908 bool CondResult;
6909 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
6910 return GetExprRange(C, CondResult ? CO->getTrueExpr()
6911 : CO->getFalseExpr(),
6912 MaxWidth);
6913
6914 // Otherwise, conservatively merge.
6915 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
6916 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
6917 return IntRange::join(L, R);
6918 }
6919
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006920 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00006921 switch (BO->getOpcode()) {
6922
6923 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00006924 case BO_LAnd:
6925 case BO_LOr:
6926 case BO_LT:
6927 case BO_GT:
6928 case BO_LE:
6929 case BO_GE:
6930 case BO_EQ:
6931 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00006932 return IntRange::forBoolType();
6933
John McCallc3688382011-07-13 06:35:24 +00006934 // The type of the assignments is the type of the LHS, so the RHS
6935 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00006936 case BO_MulAssign:
6937 case BO_DivAssign:
6938 case BO_RemAssign:
6939 case BO_AddAssign:
6940 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00006941 case BO_XorAssign:
6942 case BO_OrAssign:
6943 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00006944 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00006945
John McCallc3688382011-07-13 06:35:24 +00006946 // Simple assignments just pass through the RHS, which will have
6947 // been coerced to the LHS type.
6948 case BO_Assign:
6949 // TODO: bitfields?
6950 return GetExprRange(C, BO->getRHS(), MaxWidth);
6951
John McCall70aa5392010-01-06 05:24:50 +00006952 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00006953 case BO_PtrMemD:
6954 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00006955 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006956
John McCall2ce81ad2010-01-06 22:07:33 +00006957 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00006958 case BO_And:
6959 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00006960 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
6961 GetExprRange(C, BO->getRHS(), MaxWidth));
6962
John McCall70aa5392010-01-06 05:24:50 +00006963 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00006964 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00006965 // ...except that we want to treat '1 << (blah)' as logically
6966 // positive. It's an important idiom.
6967 if (IntegerLiteral *I
6968 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
6969 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00006970 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00006971 return IntRange(R.Width, /*NonNegative*/ true);
6972 }
6973 }
6974 // fallthrough
6975
John McCalle3027922010-08-25 11:45:40 +00006976 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00006977 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006978
John McCall2ce81ad2010-01-06 22:07:33 +00006979 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00006980 case BO_Shr:
6981 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00006982 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
6983
6984 // If the shift amount is a positive constant, drop the width by
6985 // that much.
6986 llvm::APSInt shift;
6987 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
6988 shift.isNonNegative()) {
6989 unsigned zext = shift.getZExtValue();
6990 if (zext >= L.Width)
6991 L.Width = (L.NonNegative ? 0 : 1);
6992 else
6993 L.Width -= zext;
6994 }
6995
6996 return L;
6997 }
6998
6999 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00007000 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00007001 return GetExprRange(C, BO->getRHS(), MaxWidth);
7002
John McCall2ce81ad2010-01-06 22:07:33 +00007003 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00007004 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00007005 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00007006 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00007007 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007008
John McCall51431812011-07-14 22:39:48 +00007009 // The width of a division result is mostly determined by the size
7010 // of the LHS.
7011 case BO_Div: {
7012 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00007013 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00007014 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
7015
7016 // If the divisor is constant, use that.
7017 llvm::APSInt divisor;
7018 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
7019 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
7020 if (log2 >= L.Width)
7021 L.Width = (L.NonNegative ? 0 : 1);
7022 else
7023 L.Width = std::min(L.Width - log2, MaxWidth);
7024 return L;
7025 }
7026
7027 // Otherwise, just use the LHS's width.
7028 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
7029 return IntRange(L.Width, L.NonNegative && R.NonNegative);
7030 }
7031
7032 // The result of a remainder can't be larger than the result of
7033 // either side.
7034 case BO_Rem: {
7035 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00007036 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00007037 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
7038 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
7039
7040 IntRange meet = IntRange::meet(L, R);
7041 meet.Width = std::min(meet.Width, MaxWidth);
7042 return meet;
7043 }
7044
7045 // The default behavior is okay for these.
7046 case BO_Mul:
7047 case BO_Add:
7048 case BO_Xor:
7049 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00007050 break;
7051 }
7052
John McCall51431812011-07-14 22:39:48 +00007053 // The default case is to treat the operation as if it were closed
7054 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00007055 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
7056 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
7057 return IntRange::join(L, R);
7058 }
7059
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007060 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00007061 switch (UO->getOpcode()) {
7062 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00007063 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00007064 return IntRange::forBoolType();
7065
7066 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00007067 case UO_Deref:
7068 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00007069 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00007070
7071 default:
7072 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
7073 }
7074 }
7075
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007076 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00007077 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
7078
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007079 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00007080 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00007081 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00007082
Eli Friedmane6d33952013-07-08 20:20:06 +00007083 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00007084}
John McCall263a48b2010-01-04 23:31:57 +00007085
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007086IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00007087 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00007088}
7089
John McCall263a48b2010-01-04 23:31:57 +00007090/// Checks whether the given value, which currently has the given
7091/// source semantics, has the same value when coerced through the
7092/// target semantics.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007093bool IsSameFloatAfterCast(const llvm::APFloat &value,
7094 const llvm::fltSemantics &Src,
7095 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00007096 llvm::APFloat truncated = value;
7097
7098 bool ignored;
7099 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
7100 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
7101
7102 return truncated.bitwiseIsEqual(value);
7103}
7104
7105/// Checks whether the given value, which currently has the given
7106/// source semantics, has the same value when coerced through the
7107/// target semantics.
7108///
7109/// The value might be a vector of floats (or a complex number).
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007110bool IsSameFloatAfterCast(const APValue &value,
7111 const llvm::fltSemantics &Src,
7112 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00007113 if (value.isFloat())
7114 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
7115
7116 if (value.isVector()) {
7117 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
7118 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
7119 return false;
7120 return true;
7121 }
7122
7123 assert(value.isComplexFloat());
7124 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
7125 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
7126}
7127
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007128void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007129
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007130bool IsZero(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00007131 // Suppress cases where we are comparing against an enum constant.
7132 if (const DeclRefExpr *DR =
7133 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
7134 if (isa<EnumConstantDecl>(DR->getDecl()))
7135 return false;
7136
7137 // Suppress cases where the '0' value is expanded from a macro.
7138 if (E->getLocStart().isMacroID())
7139 return false;
7140
John McCallcc7e5bf2010-05-06 08:58:33 +00007141 llvm::APSInt Value;
7142 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
7143}
7144
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007145bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00007146 // Strip off implicit integral promotions.
7147 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00007148 if (ICE->getCastKind() != CK_IntegralCast &&
7149 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00007150 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00007151 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00007152 }
7153
7154 return E->getType()->isEnumeralType();
7155}
7156
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007157void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00007158 // Disable warning in template instantiations.
7159 if (!S.ActiveTemplateInstantiations.empty())
7160 return;
7161
John McCalle3027922010-08-25 11:45:40 +00007162 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00007163 if (E->isValueDependent())
7164 return;
7165
John McCalle3027922010-08-25 11:45:40 +00007166 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007167 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00007168 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00007169 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00007170 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007171 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00007172 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00007173 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00007174 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007175 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00007176 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00007177 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00007178 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007179 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00007180 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00007181 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
7182 }
7183}
7184
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007185void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
7186 Expr *Constant, Expr *Other,
7187 llvm::APSInt Value,
7188 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00007189 // Disable warning in template instantiations.
7190 if (!S.ActiveTemplateInstantiations.empty())
7191 return;
7192
Richard Trieu0f097742014-04-04 04:13:47 +00007193 // TODO: Investigate using GetExprRange() to get tighter bounds
7194 // on the bit ranges.
7195 QualType OtherT = Other->getType();
David Majnemer7800f1f2015-05-23 01:32:17 +00007196 if (const auto *AT = OtherT->getAs<AtomicType>())
Justin Bogner4f42fc42014-07-21 18:01:53 +00007197 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00007198 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
7199 unsigned OtherWidth = OtherRange.Width;
7200
7201 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
7202
Richard Trieu560910c2012-11-14 22:50:24 +00007203 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00007204 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00007205 return;
7206
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007207 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00007208 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00007209
Richard Trieu0f097742014-04-04 04:13:47 +00007210 // Used for diagnostic printout.
7211 enum {
7212 LiteralConstant = 0,
7213 CXXBoolLiteralTrue,
7214 CXXBoolLiteralFalse
7215 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00007216
Richard Trieu0f097742014-04-04 04:13:47 +00007217 if (!OtherIsBooleanType) {
7218 QualType ConstantT = Constant->getType();
7219 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00007220
Richard Trieu0f097742014-04-04 04:13:47 +00007221 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
7222 return;
7223 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
7224 "comparison with non-integer type");
7225
7226 bool ConstantSigned = ConstantT->isSignedIntegerType();
7227 bool CommonSigned = CommonT->isSignedIntegerType();
7228
7229 bool EqualityOnly = false;
7230
7231 if (CommonSigned) {
7232 // The common type is signed, therefore no signed to unsigned conversion.
7233 if (!OtherRange.NonNegative) {
7234 // Check that the constant is representable in type OtherT.
7235 if (ConstantSigned) {
7236 if (OtherWidth >= Value.getMinSignedBits())
7237 return;
7238 } else { // !ConstantSigned
7239 if (OtherWidth >= Value.getActiveBits() + 1)
7240 return;
7241 }
7242 } else { // !OtherSigned
7243 // Check that the constant is representable in type OtherT.
7244 // Negative values are out of range.
7245 if (ConstantSigned) {
7246 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
7247 return;
7248 } else { // !ConstantSigned
7249 if (OtherWidth >= Value.getActiveBits())
7250 return;
7251 }
Richard Trieu560910c2012-11-14 22:50:24 +00007252 }
Richard Trieu0f097742014-04-04 04:13:47 +00007253 } else { // !CommonSigned
7254 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00007255 if (OtherWidth >= Value.getActiveBits())
7256 return;
Craig Toppercf360162014-06-18 05:13:11 +00007257 } else { // OtherSigned
7258 assert(!ConstantSigned &&
7259 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00007260 // Check to see if the constant is representable in OtherT.
7261 if (OtherWidth > Value.getActiveBits())
7262 return;
7263 // Check to see if the constant is equivalent to a negative value
7264 // cast to CommonT.
7265 if (S.Context.getIntWidth(ConstantT) ==
7266 S.Context.getIntWidth(CommonT) &&
7267 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
7268 return;
7269 // The constant value rests between values that OtherT can represent
7270 // after conversion. Relational comparison still works, but equality
7271 // comparisons will be tautological.
7272 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00007273 }
7274 }
Richard Trieu0f097742014-04-04 04:13:47 +00007275
7276 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
7277
7278 if (op == BO_EQ || op == BO_NE) {
7279 IsTrue = op == BO_NE;
7280 } else if (EqualityOnly) {
7281 return;
7282 } else if (RhsConstant) {
7283 if (op == BO_GT || op == BO_GE)
7284 IsTrue = !PositiveConstant;
7285 else // op == BO_LT || op == BO_LE
7286 IsTrue = PositiveConstant;
7287 } else {
7288 if (op == BO_LT || op == BO_LE)
7289 IsTrue = !PositiveConstant;
7290 else // op == BO_GT || op == BO_GE
7291 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00007292 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007293 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00007294 // Other isKnownToHaveBooleanValue
7295 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
7296 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
7297 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
7298
7299 static const struct LinkedConditions {
7300 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
7301 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
7302 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
7303 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
7304 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
7305 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
7306
7307 } TruthTable = {
7308 // Constant on LHS. | Constant on RHS. |
7309 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
7310 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
7311 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
7312 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
7313 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
7314 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
7315 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
7316 };
7317
7318 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
7319
7320 enum ConstantValue ConstVal = Zero;
7321 if (Value.isUnsigned() || Value.isNonNegative()) {
7322 if (Value == 0) {
7323 LiteralOrBoolConstant =
7324 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
7325 ConstVal = Zero;
7326 } else if (Value == 1) {
7327 LiteralOrBoolConstant =
7328 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
7329 ConstVal = One;
7330 } else {
7331 LiteralOrBoolConstant = LiteralConstant;
7332 ConstVal = GT_One;
7333 }
7334 } else {
7335 ConstVal = LT_Zero;
7336 }
7337
7338 CompareBoolWithConstantResult CmpRes;
7339
7340 switch (op) {
7341 case BO_LT:
7342 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
7343 break;
7344 case BO_GT:
7345 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
7346 break;
7347 case BO_LE:
7348 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
7349 break;
7350 case BO_GE:
7351 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
7352 break;
7353 case BO_EQ:
7354 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
7355 break;
7356 case BO_NE:
7357 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
7358 break;
7359 default:
7360 CmpRes = Unkwn;
7361 break;
7362 }
7363
7364 if (CmpRes == AFals) {
7365 IsTrue = false;
7366 } else if (CmpRes == ATrue) {
7367 IsTrue = true;
7368 } else {
7369 return;
7370 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007371 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00007372
7373 // If this is a comparison to an enum constant, include that
7374 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00007375 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00007376 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
7377 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
7378
7379 SmallString<64> PrettySourceValue;
7380 llvm::raw_svector_ostream OS(PrettySourceValue);
7381 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00007382 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00007383 else
7384 OS << Value;
7385
Richard Trieu0f097742014-04-04 04:13:47 +00007386 S.DiagRuntimeBehavior(
7387 E->getOperatorLoc(), E,
7388 S.PDiag(diag::warn_out_of_range_compare)
7389 << OS.str() << LiteralOrBoolConstant
7390 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
7391 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007392}
7393
John McCallcc7e5bf2010-05-06 08:58:33 +00007394/// Analyze the operands of the given comparison. Implements the
7395/// fallback case from AnalyzeComparison.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007396void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00007397 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
7398 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00007399}
John McCall263a48b2010-01-04 23:31:57 +00007400
John McCallca01b222010-01-04 23:21:16 +00007401/// \brief Implements -Wsign-compare.
7402///
Richard Trieu82402a02011-09-15 21:56:47 +00007403/// \param E the binary operator to check for warnings
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007404void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007405 // The type the comparison is being performed in.
7406 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00007407
7408 // Only analyze comparison operators where both sides have been converted to
7409 // the same type.
7410 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
7411 return AnalyzeImpConvsInComparison(S, E);
7412
7413 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00007414 if (E->isValueDependent())
7415 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007416
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007417 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
7418 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007419
7420 bool IsComparisonConstant = false;
7421
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007422 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007423 // of 'true' or 'false'.
7424 if (T->isIntegralType(S.Context)) {
7425 llvm::APSInt RHSValue;
7426 bool IsRHSIntegralLiteral =
7427 RHS->isIntegerConstantExpr(RHSValue, S.Context);
7428 llvm::APSInt LHSValue;
7429 bool IsLHSIntegralLiteral =
7430 LHS->isIntegerConstantExpr(LHSValue, S.Context);
7431 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
7432 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
7433 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
7434 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
7435 else
7436 IsComparisonConstant =
7437 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007438 } else if (!T->hasUnsignedIntegerRepresentation())
7439 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007440
John McCallcc7e5bf2010-05-06 08:58:33 +00007441 // We don't do anything special if this isn't an unsigned integral
7442 // comparison: we're only interested in integral comparisons, and
7443 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00007444 //
7445 // We also don't care about value-dependent expressions or expressions
7446 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007447 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00007448 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007449
John McCallcc7e5bf2010-05-06 08:58:33 +00007450 // Check to see if one of the (unmodified) operands is of different
7451 // signedness.
7452 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00007453 if (LHS->getType()->hasSignedIntegerRepresentation()) {
7454 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00007455 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00007456 signedOperand = LHS;
7457 unsignedOperand = RHS;
7458 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
7459 signedOperand = RHS;
7460 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00007461 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00007462 CheckTrivialUnsignedComparison(S, E);
7463 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007464 }
7465
John McCallcc7e5bf2010-05-06 08:58:33 +00007466 // Otherwise, calculate the effective range of the signed operand.
7467 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00007468
John McCallcc7e5bf2010-05-06 08:58:33 +00007469 // Go ahead and analyze implicit conversions in the operands. Note
7470 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00007471 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
7472 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00007473
John McCallcc7e5bf2010-05-06 08:58:33 +00007474 // If the signed range is non-negative, -Wsign-compare won't fire,
7475 // but we should still check for comparisons which are always true
7476 // or false.
7477 if (signedRange.NonNegative)
7478 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007479
7480 // For (in)equality comparisons, if the unsigned operand is a
7481 // constant which cannot collide with a overflowed signed operand,
7482 // then reinterpreting the signed operand as unsigned will not
7483 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00007484 if (E->isEqualityOp()) {
7485 unsigned comparisonWidth = S.Context.getIntWidth(T);
7486 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00007487
John McCallcc7e5bf2010-05-06 08:58:33 +00007488 // We should never be unable to prove that the unsigned operand is
7489 // non-negative.
7490 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
7491
7492 if (unsignedRange.Width < comparisonWidth)
7493 return;
7494 }
7495
Douglas Gregorbfb4a212012-05-01 01:53:49 +00007496 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
7497 S.PDiag(diag::warn_mixed_sign_comparison)
7498 << LHS->getType() << RHS->getType()
7499 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00007500}
7501
John McCall1f425642010-11-11 03:21:53 +00007502/// Analyzes an attempt to assign the given value to a bitfield.
7503///
7504/// Returns true if there was something fishy about the attempt.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007505bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
7506 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00007507 assert(Bitfield->isBitField());
7508 if (Bitfield->isInvalidDecl())
7509 return false;
7510
John McCalldeebbcf2010-11-11 05:33:51 +00007511 // White-list bool bitfields.
7512 if (Bitfield->getType()->isBooleanType())
7513 return false;
7514
Douglas Gregor789adec2011-02-04 13:09:01 +00007515 // Ignore value- or type-dependent expressions.
7516 if (Bitfield->getBitWidth()->isValueDependent() ||
7517 Bitfield->getBitWidth()->isTypeDependent() ||
7518 Init->isValueDependent() ||
7519 Init->isTypeDependent())
7520 return false;
7521
John McCall1f425642010-11-11 03:21:53 +00007522 Expr *OriginalInit = Init->IgnoreParenImpCasts();
7523
Richard Smith5fab0c92011-12-28 19:48:30 +00007524 llvm::APSInt Value;
7525 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00007526 return false;
7527
John McCall1f425642010-11-11 03:21:53 +00007528 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00007529 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00007530
7531 if (OriginalWidth <= FieldWidth)
7532 return false;
7533
Eli Friedmanc267a322012-01-26 23:11:39 +00007534 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00007535 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00007536 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00007537
Eli Friedmanc267a322012-01-26 23:11:39 +00007538 // Check whether the stored value is equal to the original value.
7539 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00007540 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00007541 return false;
7542
Eli Friedmanc267a322012-01-26 23:11:39 +00007543 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00007544 // therefore don't strictly fit into a signed bitfield of width 1.
7545 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00007546 return false;
7547
John McCall1f425642010-11-11 03:21:53 +00007548 std::string PrettyValue = Value.toString(10);
7549 std::string PrettyTrunc = TruncatedValue.toString(10);
7550
7551 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
7552 << PrettyValue << PrettyTrunc << OriginalInit->getType()
7553 << Init->getSourceRange();
7554
7555 return true;
7556}
7557
John McCalld2a53122010-11-09 23:24:47 +00007558/// Analyze the given simple or compound assignment for warning-worthy
7559/// operations.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007560void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00007561 // Just recurse on the LHS.
7562 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
7563
7564 // We want to recurse on the RHS as normal unless we're assigning to
7565 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00007566 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007567 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00007568 E->getOperatorLoc())) {
7569 // Recurse, ignoring any implicit conversions on the RHS.
7570 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
7571 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00007572 }
7573 }
7574
7575 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
7576}
7577
John McCall263a48b2010-01-04 23:31:57 +00007578/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007579void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
7580 SourceLocation CContext, unsigned diag,
7581 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00007582 if (pruneControlFlow) {
7583 S.DiagRuntimeBehavior(E->getExprLoc(), E,
7584 S.PDiag(diag)
7585 << SourceType << T << E->getSourceRange()
7586 << SourceRange(CContext));
7587 return;
7588 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00007589 S.Diag(E->getExprLoc(), diag)
7590 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
7591}
7592
Chandler Carruth7f3654f2011-04-05 06:47:57 +00007593/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007594void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
7595 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00007596 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00007597}
7598
Richard Trieube234c32016-04-21 21:04:55 +00007599
7600/// Diagnose an implicit cast from a floating point value to an integer value.
7601void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
7602
7603 SourceLocation CContext) {
7604 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
7605 const bool PruneWarnings = !S.ActiveTemplateInstantiations.empty();
7606
7607 Expr *InnerE = E->IgnoreParenImpCasts();
7608 // We also want to warn on, e.g., "int i = -1.234"
7609 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
7610 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
7611 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
7612
7613 const bool IsLiteral =
7614 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
7615
7616 llvm::APFloat Value(0.0);
7617 bool IsConstant =
7618 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
7619 if (!IsConstant) {
Richard Trieu891f0f12016-04-22 22:14:32 +00007620 return DiagnoseImpCast(S, E, T, CContext,
7621 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +00007622 }
7623
Chandler Carruth016ef402011-04-10 08:36:24 +00007624 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +00007625
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00007626 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
7627 T->hasUnsignedIntegerRepresentation());
Richard Trieube234c32016-04-21 21:04:55 +00007628 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
7629 &isExact) == llvm::APFloat::opOK &&
Richard Trieu891f0f12016-04-22 22:14:32 +00007630 isExact) {
Richard Trieube234c32016-04-21 21:04:55 +00007631 if (IsLiteral) return;
7632 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
7633 PruneWarnings);
7634 }
7635
7636 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +00007637 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +00007638 // Warn on floating point literal to integer.
7639 DiagID = diag::warn_impcast_literal_float_to_integer;
7640 } else if (IntegerValue == 0) {
7641 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
7642 return DiagnoseImpCast(S, E, T, CContext,
7643 diag::warn_impcast_float_integer, PruneWarnings);
7644 }
7645 // Warn on non-zero to zero conversion.
7646 DiagID = diag::warn_impcast_float_to_integer_zero;
7647 } else {
7648 if (IntegerValue.isUnsigned()) {
7649 if (!IntegerValue.isMaxValue()) {
7650 return DiagnoseImpCast(S, E, T, CContext,
7651 diag::warn_impcast_float_integer, PruneWarnings);
7652 }
7653 } else { // IntegerValue.isSigned()
7654 if (!IntegerValue.isMaxSignedValue() &&
7655 !IntegerValue.isMinSignedValue()) {
7656 return DiagnoseImpCast(S, E, T, CContext,
7657 diag::warn_impcast_float_integer, PruneWarnings);
7658 }
7659 }
7660 // Warn on evaluatable floating point expression to integer conversion.
7661 DiagID = diag::warn_impcast_float_to_integer;
7662 }
Chandler Carruth016ef402011-04-10 08:36:24 +00007663
Eli Friedman07185912013-08-29 23:44:43 +00007664 // FIXME: Force the precision of the source value down so we don't print
7665 // digits which are usually useless (we don't really care here if we
7666 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
7667 // would automatically print the shortest representation, but it's a bit
7668 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00007669 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00007670 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
7671 precision = (precision * 59 + 195) / 196;
7672 Value.toString(PrettySourceValue, precision);
7673
David Blaikie9b88cc02012-05-15 17:18:27 +00007674 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +00007675 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +00007676 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00007677 else
David Blaikie9b88cc02012-05-15 17:18:27 +00007678 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00007679
Richard Trieube234c32016-04-21 21:04:55 +00007680 if (PruneWarnings) {
7681 S.DiagRuntimeBehavior(E->getExprLoc(), E,
7682 S.PDiag(DiagID)
7683 << E->getType() << T.getUnqualifiedType()
7684 << PrettySourceValue << PrettyTargetValue
7685 << E->getSourceRange() << SourceRange(CContext));
7686 } else {
7687 S.Diag(E->getExprLoc(), DiagID)
7688 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
7689 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
7690 }
Chandler Carruth016ef402011-04-10 08:36:24 +00007691}
7692
John McCall18a2c2c2010-11-09 22:22:12 +00007693std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
7694 if (!Range.Width) return "0";
7695
7696 llvm::APSInt ValueInRange = Value;
7697 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00007698 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00007699 return ValueInRange.toString(10);
7700}
7701
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007702bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007703 if (!isa<ImplicitCastExpr>(Ex))
7704 return false;
7705
7706 Expr *InnerE = Ex->IgnoreParenImpCasts();
7707 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
7708 const Type *Source =
7709 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
7710 if (Target->isDependentType())
7711 return false;
7712
7713 const BuiltinType *FloatCandidateBT =
7714 dyn_cast<BuiltinType>(ToBool ? Source : Target);
7715 const Type *BoolCandidateType = ToBool ? Target : Source;
7716
7717 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
7718 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
7719}
7720
7721void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
7722 SourceLocation CC) {
7723 unsigned NumArgs = TheCall->getNumArgs();
7724 for (unsigned i = 0; i < NumArgs; ++i) {
7725 Expr *CurrA = TheCall->getArg(i);
7726 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
7727 continue;
7728
7729 bool IsSwapped = ((i > 0) &&
7730 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
7731 IsSwapped |= ((i < (NumArgs - 1)) &&
7732 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
7733 if (IsSwapped) {
7734 // Warn on this floating-point to bool conversion.
7735 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
7736 CurrA->getType(), CC,
7737 diag::warn_impcast_floating_point_to_bool);
7738 }
7739 }
7740}
7741
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007742void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00007743 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
7744 E->getExprLoc()))
7745 return;
7746
Richard Trieu09d6b802016-01-08 23:35:06 +00007747 // Don't warn on functions which have return type nullptr_t.
7748 if (isa<CallExpr>(E))
7749 return;
7750
Richard Trieu5b993502014-10-15 03:42:06 +00007751 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
7752 const Expr::NullPointerConstantKind NullKind =
7753 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
7754 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
7755 return;
7756
7757 // Return if target type is a safe conversion.
7758 if (T->isAnyPointerType() || T->isBlockPointerType() ||
7759 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
7760 return;
7761
7762 SourceLocation Loc = E->getSourceRange().getBegin();
7763
Richard Trieu0a5e1662016-02-13 00:58:53 +00007764 // Venture through the macro stacks to get to the source of macro arguments.
7765 // The new location is a better location than the complete location that was
7766 // passed in.
7767 while (S.SourceMgr.isMacroArgExpansion(Loc))
7768 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
7769
7770 while (S.SourceMgr.isMacroArgExpansion(CC))
7771 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
7772
Richard Trieu5b993502014-10-15 03:42:06 +00007773 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +00007774 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
7775 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
7776 Loc, S.SourceMgr, S.getLangOpts());
7777 if (MacroName == "NULL")
7778 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
Richard Trieu5b993502014-10-15 03:42:06 +00007779 }
7780
7781 // Only warn if the null and context location are in the same macro expansion.
7782 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
7783 return;
7784
7785 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
7786 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
7787 << FixItHint::CreateReplacement(Loc,
7788 S.getFixItZeroLiteralForType(T, Loc));
7789}
7790
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007791void checkObjCArrayLiteral(Sema &S, QualType TargetType,
7792 ObjCArrayLiteral *ArrayLiteral);
7793void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
7794 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +00007795
7796/// Check a single element within a collection literal against the
7797/// target element type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007798void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
7799 Expr *Element, unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00007800 // Skip a bitcast to 'id' or qualified 'id'.
7801 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
7802 if (ICE->getCastKind() == CK_BitCast &&
7803 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
7804 Element = ICE->getSubExpr();
7805 }
7806
7807 QualType ElementType = Element->getType();
7808 ExprResult ElementResult(Element);
7809 if (ElementType->getAs<ObjCObjectPointerType>() &&
7810 S.CheckSingleAssignmentConstraints(TargetElementType,
7811 ElementResult,
7812 false, false)
7813 != Sema::Compatible) {
7814 S.Diag(Element->getLocStart(),
7815 diag::warn_objc_collection_literal_element)
7816 << ElementType << ElementKind << TargetElementType
7817 << Element->getSourceRange();
7818 }
7819
7820 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
7821 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
7822 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
7823 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
7824}
7825
7826/// Check an Objective-C array literal being converted to the given
7827/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007828void checkObjCArrayLiteral(Sema &S, QualType TargetType,
7829 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00007830 if (!S.NSArrayDecl)
7831 return;
7832
7833 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
7834 if (!TargetObjCPtr)
7835 return;
7836
7837 if (TargetObjCPtr->isUnspecialized() ||
7838 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
7839 != S.NSArrayDecl->getCanonicalDecl())
7840 return;
7841
7842 auto TypeArgs = TargetObjCPtr->getTypeArgs();
7843 if (TypeArgs.size() != 1)
7844 return;
7845
7846 QualType TargetElementType = TypeArgs[0];
7847 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
7848 checkObjCCollectionLiteralElement(S, TargetElementType,
7849 ArrayLiteral->getElement(I),
7850 0);
7851 }
7852}
7853
7854/// Check an Objective-C dictionary literal being converted to the given
7855/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007856void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
7857 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00007858 if (!S.NSDictionaryDecl)
7859 return;
7860
7861 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
7862 if (!TargetObjCPtr)
7863 return;
7864
7865 if (TargetObjCPtr->isUnspecialized() ||
7866 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
7867 != S.NSDictionaryDecl->getCanonicalDecl())
7868 return;
7869
7870 auto TypeArgs = TargetObjCPtr->getTypeArgs();
7871 if (TypeArgs.size() != 2)
7872 return;
7873
7874 QualType TargetKeyType = TypeArgs[0];
7875 QualType TargetObjectType = TypeArgs[1];
7876 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
7877 auto Element = DictionaryLiteral->getKeyValueElement(I);
7878 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
7879 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
7880 }
7881}
7882
Richard Trieufc404c72016-02-05 23:02:38 +00007883// Helper function to filter out cases for constant width constant conversion.
7884// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007885bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
7886 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +00007887 // If initializing from a constant, and the constant starts with '0',
7888 // then it is a binary, octal, or hexadecimal. Allow these constants
7889 // to fill all the bits, even if there is a sign change.
7890 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
7891 const char FirstLiteralCharacter =
7892 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
7893 if (FirstLiteralCharacter == '0')
7894 return false;
7895 }
7896
7897 // If the CC location points to a '{', and the type is char, then assume
7898 // assume it is an array initialization.
7899 if (CC.isValid() && T->isCharType()) {
7900 const char FirstContextCharacter =
7901 S.getSourceManager().getCharacterData(CC)[0];
7902 if (FirstContextCharacter == '{')
7903 return false;
7904 }
7905
7906 return true;
7907}
7908
John McCallcc7e5bf2010-05-06 08:58:33 +00007909void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00007910 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007911 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00007912
John McCallcc7e5bf2010-05-06 08:58:33 +00007913 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
7914 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
7915 if (Source == Target) return;
7916 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00007917
Chandler Carruthc22845a2011-07-26 05:40:03 +00007918 // If the conversion context location is invalid don't complain. We also
7919 // don't want to emit a warning if the issue occurs from the expansion of
7920 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
7921 // delay this check as long as possible. Once we detect we are in that
7922 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007923 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00007924 return;
7925
Richard Trieu021baa32011-09-23 20:10:00 +00007926 // Diagnose implicit casts to bool.
7927 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
7928 if (isa<StringLiteral>(E))
7929 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00007930 // and expressions, for instance, assert(0 && "error here"), are
7931 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00007932 return DiagnoseImpCast(S, E, T, CC,
7933 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00007934 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
7935 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
7936 // This covers the literal expressions that evaluate to Objective-C
7937 // objects.
7938 return DiagnoseImpCast(S, E, T, CC,
7939 diag::warn_impcast_objective_c_literal_to_bool);
7940 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00007941 if (Source->isPointerType() || Source->canDecayToPointerType()) {
7942 // Warn on pointer to bool conversion that is always true.
7943 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
7944 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00007945 }
Richard Trieu021baa32011-09-23 20:10:00 +00007946 }
John McCall263a48b2010-01-04 23:31:57 +00007947
Douglas Gregor5054cb02015-07-07 03:58:22 +00007948 // Check implicit casts from Objective-C collection literals to specialized
7949 // collection types, e.g., NSArray<NSString *> *.
7950 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
7951 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
7952 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
7953 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
7954
John McCall263a48b2010-01-04 23:31:57 +00007955 // Strip vector types.
7956 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007957 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007958 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007959 return;
John McCallacf0ee52010-10-08 02:01:28 +00007960 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007961 }
Chris Lattneree7286f2011-06-14 04:51:15 +00007962
7963 // If the vector cast is cast between two vectors of the same size, it is
7964 // a bitcast, not a conversion.
7965 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
7966 return;
John McCall263a48b2010-01-04 23:31:57 +00007967
7968 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
7969 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
7970 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00007971 if (auto VecTy = dyn_cast<VectorType>(Target))
7972 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00007973
7974 // Strip complex types.
7975 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007976 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007977 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007978 return;
7979
John McCallacf0ee52010-10-08 02:01:28 +00007980 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007981 }
John McCall263a48b2010-01-04 23:31:57 +00007982
7983 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
7984 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
7985 }
7986
7987 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
7988 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
7989
7990 // If the source is floating point...
7991 if (SourceBT && SourceBT->isFloatingPoint()) {
7992 // ...and the target is floating point...
7993 if (TargetBT && TargetBT->isFloatingPoint()) {
7994 // ...then warn if we're dropping FP rank.
7995
7996 // Builtin FP kinds are ordered by increasing FP rank.
7997 if (SourceBT->getKind() > TargetBT->getKind()) {
7998 // Don't warn about float constants that are precisely
7999 // representable in the target type.
8000 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00008001 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00008002 // Value might be a float, a float vector, or a float complex.
8003 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00008004 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
8005 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00008006 return;
8007 }
8008
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008009 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008010 return;
8011
John McCallacf0ee52010-10-08 02:01:28 +00008012 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +00008013 }
8014 // ... or possibly if we're increasing rank, too
8015 else if (TargetBT->getKind() > SourceBT->getKind()) {
8016 if (S.SourceMgr.isInSystemMacro(CC))
8017 return;
8018
8019 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +00008020 }
8021 return;
8022 }
8023
Richard Trieube234c32016-04-21 21:04:55 +00008024 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00008025 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008026 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008027 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00008028
Richard Trieube234c32016-04-21 21:04:55 +00008029 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00008030 }
John McCall263a48b2010-01-04 23:31:57 +00008031
Richard Smith54894fd2015-12-30 01:06:52 +00008032 // Detect the case where a call result is converted from floating-point to
8033 // to bool, and the final argument to the call is converted from bool, to
8034 // discover this typo:
8035 //
8036 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
8037 //
8038 // FIXME: This is an incredibly special case; is there some more general
8039 // way to detect this class of misplaced-parentheses bug?
8040 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008041 // Check last argument of function call to see if it is an
8042 // implicit cast from a type matching the type the result
8043 // is being cast to.
8044 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +00008045 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008046 Expr *LastA = CEx->getArg(NumArgs - 1);
8047 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +00008048 if (isa<ImplicitCastExpr>(LastA) &&
8049 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008050 // Warn on this floating-point to bool conversion
8051 DiagnoseImpCast(S, E, T, CC,
8052 diag::warn_impcast_floating_point_to_bool);
8053 }
8054 }
8055 }
John McCall263a48b2010-01-04 23:31:57 +00008056 return;
8057 }
8058
Richard Trieu5b993502014-10-15 03:42:06 +00008059 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00008060
David Blaikie9366d2b2012-06-19 21:19:06 +00008061 if (!Source->isIntegerType() || !Target->isIntegerType())
8062 return;
8063
David Blaikie7555b6a2012-05-15 16:56:36 +00008064 // TODO: remove this early return once the false positives for constant->bool
8065 // in templates, macros, etc, are reduced or removed.
8066 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
8067 return;
8068
John McCallcc7e5bf2010-05-06 08:58:33 +00008069 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00008070 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00008071
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008072 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00008073 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008074 // TODO: this should happen for bitfield stores, too.
8075 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +00008076 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008077 if (S.SourceMgr.isInSystemMacro(CC))
8078 return;
8079
John McCall18a2c2c2010-11-09 22:22:12 +00008080 std::string PrettySourceValue = Value.toString(10);
8081 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008082
Ted Kremenek33ba9952011-10-22 02:37:33 +00008083 S.DiagRuntimeBehavior(E->getExprLoc(), E,
8084 S.PDiag(diag::warn_impcast_integer_precision_constant)
8085 << PrettySourceValue << PrettyTargetValue
8086 << E->getType() << T << E->getSourceRange()
8087 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00008088 return;
8089 }
8090
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008091 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
8092 if (S.SourceMgr.isInSystemMacro(CC))
8093 return;
8094
David Blaikie9455da02012-04-12 22:40:54 +00008095 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00008096 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
8097 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00008098 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00008099 }
8100
Richard Trieudcb55572016-01-29 23:51:16 +00008101 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
8102 SourceRange.NonNegative && Source->isSignedIntegerType()) {
8103 // Warn when doing a signed to signed conversion, warn if the positive
8104 // source value is exactly the width of the target type, which will
8105 // cause a negative value to be stored.
8106
8107 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +00008108 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
8109 !S.SourceMgr.isInSystemMacro(CC)) {
8110 if (isSameWidthConstantConversion(S, E, T, CC)) {
8111 std::string PrettySourceValue = Value.toString(10);
8112 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +00008113
Richard Trieufc404c72016-02-05 23:02:38 +00008114 S.DiagRuntimeBehavior(
8115 E->getExprLoc(), E,
8116 S.PDiag(diag::warn_impcast_integer_precision_constant)
8117 << PrettySourceValue << PrettyTargetValue << E->getType() << T
8118 << E->getSourceRange() << clang::SourceRange(CC));
8119 return;
Richard Trieudcb55572016-01-29 23:51:16 +00008120 }
8121 }
Richard Trieufc404c72016-02-05 23:02:38 +00008122
Richard Trieudcb55572016-01-29 23:51:16 +00008123 // Fall through for non-constants to give a sign conversion warning.
8124 }
8125
John McCallcc7e5bf2010-05-06 08:58:33 +00008126 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
8127 (!TargetRange.NonNegative && SourceRange.NonNegative &&
8128 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008129 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008130 return;
8131
John McCallcc7e5bf2010-05-06 08:58:33 +00008132 unsigned DiagID = diag::warn_impcast_integer_sign;
8133
8134 // Traditionally, gcc has warned about this under -Wsign-compare.
8135 // We also want to warn about it in -Wconversion.
8136 // So if -Wconversion is off, use a completely identical diagnostic
8137 // in the sign-compare group.
8138 // The conditional-checking code will
8139 if (ICContext) {
8140 DiagID = diag::warn_impcast_integer_sign_conditional;
8141 *ICContext = true;
8142 }
8143
John McCallacf0ee52010-10-08 02:01:28 +00008144 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00008145 }
8146
Douglas Gregora78f1932011-02-22 02:45:07 +00008147 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00008148 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
8149 // type, to give us better diagnostics.
8150 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00008151 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00008152 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8153 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
8154 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
8155 SourceType = S.Context.getTypeDeclType(Enum);
8156 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
8157 }
8158 }
8159
Douglas Gregora78f1932011-02-22 02:45:07 +00008160 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
8161 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00008162 if (SourceEnum->getDecl()->hasNameForLinkage() &&
8163 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008164 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008165 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008166 return;
8167
Douglas Gregor364f7db2011-03-12 00:14:31 +00008168 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00008169 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008170 }
John McCall263a48b2010-01-04 23:31:57 +00008171}
8172
David Blaikie18e9ac72012-05-15 21:57:38 +00008173void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
8174 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00008175
8176void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00008177 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008178 E = E->IgnoreParenImpCasts();
8179
8180 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00008181 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00008182
John McCallacf0ee52010-10-08 02:01:28 +00008183 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008184 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00008185 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00008186}
8187
David Blaikie18e9ac72012-05-15 21:57:38 +00008188void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
8189 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00008190 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00008191
8192 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00008193 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
8194 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00008195
8196 // If -Wconversion would have warned about either of the candidates
8197 // for a signedness conversion to the context type...
8198 if (!Suspicious) return;
8199
8200 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008201 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00008202 return;
8203
John McCallcc7e5bf2010-05-06 08:58:33 +00008204 // ...then check whether it would have warned about either of the
8205 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00008206 if (E->getType() == T) return;
8207
8208 Suspicious = false;
8209 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
8210 E->getType(), CC, &Suspicious);
8211 if (!Suspicious)
8212 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00008213 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00008214}
8215
Richard Trieu65724892014-11-15 06:37:39 +00008216/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
8217/// Input argument E is a logical expression.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008218void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +00008219 if (S.getLangOpts().Bool)
8220 return;
8221 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
8222}
8223
John McCallcc7e5bf2010-05-06 08:58:33 +00008224/// AnalyzeImplicitConversions - Find and report any interesting
8225/// implicit conversions in the given expression. There are a couple
8226/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00008227void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00008228 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00008229 Expr *E = OrigE->IgnoreParenImpCasts();
8230
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00008231 if (E->isTypeDependent() || E->isValueDependent())
8232 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00008233
John McCallcc7e5bf2010-05-06 08:58:33 +00008234 // For conditional operators, we analyze the arguments as if they
8235 // were being fed directly into the output.
8236 if (isa<ConditionalOperator>(E)) {
8237 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00008238 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00008239 return;
8240 }
8241
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008242 // Check implicit argument conversions for function calls.
8243 if (CallExpr *Call = dyn_cast<CallExpr>(E))
8244 CheckImplicitArgumentConversions(S, Call, CC);
8245
John McCallcc7e5bf2010-05-06 08:58:33 +00008246 // Go ahead and check any implicit conversions we might have skipped.
8247 // The non-canonical typecheck is just an optimization;
8248 // CheckImplicitConversion will filter out dead implicit conversions.
8249 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00008250 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008251
8252 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +00008253
8254 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
8255 // The bound subexpressions in a PseudoObjectExpr are not reachable
8256 // as transitive children.
8257 // FIXME: Use a more uniform representation for this.
8258 for (auto *SE : POE->semantics())
8259 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
8260 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00008261 }
Richard Smithd7bed4d2015-11-22 02:57:17 +00008262
John McCallcc7e5bf2010-05-06 08:58:33 +00008263 // Skip past explicit casts.
8264 if (isa<ExplicitCastExpr>(E)) {
8265 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00008266 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008267 }
8268
John McCalld2a53122010-11-09 23:24:47 +00008269 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8270 // Do a somewhat different check with comparison operators.
8271 if (BO->isComparisonOp())
8272 return AnalyzeComparison(S, BO);
8273
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008274 // And with simple assignments.
8275 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00008276 return AnalyzeAssignment(S, BO);
8277 }
John McCallcc7e5bf2010-05-06 08:58:33 +00008278
8279 // These break the otherwise-useful invariant below. Fortunately,
8280 // we don't really need to recurse into them, because any internal
8281 // expressions should have been analyzed already when they were
8282 // built into statements.
8283 if (isa<StmtExpr>(E)) return;
8284
8285 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00008286 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00008287
8288 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00008289 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00008290 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00008291 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +00008292 for (Stmt *SubStmt : E->children()) {
8293 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00008294 if (!ChildExpr)
8295 continue;
8296
Richard Trieu955231d2014-01-25 01:10:35 +00008297 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00008298 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00008299 // Ignore checking string literals that are in logical and operators.
8300 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00008301 continue;
8302 AnalyzeImplicitConversions(S, ChildExpr, CC);
8303 }
Richard Trieu791b86e2014-11-19 06:08:18 +00008304
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00008305 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00008306 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
8307 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00008308 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00008309
8310 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
8311 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00008312 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00008313 }
Richard Trieu791b86e2014-11-19 06:08:18 +00008314
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00008315 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
8316 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00008317 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008318}
8319
8320} // end anonymous namespace
8321
Richard Trieuc1888e02014-06-28 23:25:37 +00008322// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
8323// Returns true when emitting a warning about taking the address of a reference.
8324static bool CheckForReference(Sema &SemaRef, const Expr *E,
8325 PartialDiagnostic PD) {
8326 E = E->IgnoreParenImpCasts();
8327
8328 const FunctionDecl *FD = nullptr;
8329
8330 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8331 if (!DRE->getDecl()->getType()->isReferenceType())
8332 return false;
8333 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
8334 if (!M->getMemberDecl()->getType()->isReferenceType())
8335 return false;
8336 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00008337 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00008338 return false;
8339 FD = Call->getDirectCallee();
8340 } else {
8341 return false;
8342 }
8343
8344 SemaRef.Diag(E->getExprLoc(), PD);
8345
8346 // If possible, point to location of function.
8347 if (FD) {
8348 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
8349 }
8350
8351 return true;
8352}
8353
Richard Trieu4cbff5c2014-08-08 22:41:43 +00008354// Returns true if the SourceLocation is expanded from any macro body.
8355// Returns false if the SourceLocation is invalid, is from not in a macro
8356// expansion, or is from expanded from a top-level macro argument.
8357static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
8358 if (Loc.isInvalid())
8359 return false;
8360
8361 while (Loc.isMacroID()) {
8362 if (SM.isMacroBodyExpansion(Loc))
8363 return true;
8364 Loc = SM.getImmediateMacroCallerLoc(Loc);
8365 }
8366
8367 return false;
8368}
8369
Richard Trieu3bb8b562014-02-26 02:36:06 +00008370/// \brief Diagnose pointers that are always non-null.
8371/// \param E the expression containing the pointer
8372/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
8373/// compared to a null pointer
8374/// \param IsEqual True when the comparison is equal to a null pointer
8375/// \param Range Extra SourceRange to highlight in the diagnostic
8376void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
8377 Expr::NullPointerConstantKind NullKind,
8378 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00008379 if (!E)
8380 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008381
8382 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00008383 if (E->getExprLoc().isMacroID()) {
8384 const SourceManager &SM = getSourceManager();
8385 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
8386 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00008387 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00008388 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00008389 E = E->IgnoreImpCasts();
8390
8391 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
8392
Richard Trieuf7432752014-06-06 21:39:26 +00008393 if (isa<CXXThisExpr>(E)) {
8394 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
8395 : diag::warn_this_bool_conversion;
8396 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
8397 return;
8398 }
8399
Richard Trieu3bb8b562014-02-26 02:36:06 +00008400 bool IsAddressOf = false;
8401
8402 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
8403 if (UO->getOpcode() != UO_AddrOf)
8404 return;
8405 IsAddressOf = true;
8406 E = UO->getSubExpr();
8407 }
8408
Richard Trieuc1888e02014-06-28 23:25:37 +00008409 if (IsAddressOf) {
8410 unsigned DiagID = IsCompare
8411 ? diag::warn_address_of_reference_null_compare
8412 : diag::warn_address_of_reference_bool_conversion;
8413 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
8414 << IsEqual;
8415 if (CheckForReference(*this, E, PD)) {
8416 return;
8417 }
8418 }
8419
George Burgess IV850269a2015-12-08 22:02:00 +00008420 auto ComplainAboutNonnullParamOrCall = [&](bool IsParam) {
8421 std::string Str;
8422 llvm::raw_string_ostream S(Str);
8423 E->printPretty(S, nullptr, getPrintingPolicy());
8424 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
8425 : diag::warn_cast_nonnull_to_bool;
8426 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
8427 << E->getSourceRange() << Range << IsEqual;
8428 };
8429
8430 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
8431 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
8432 if (auto *Callee = Call->getDirectCallee()) {
8433 if (Callee->hasAttr<ReturnsNonNullAttr>()) {
8434 ComplainAboutNonnullParamOrCall(false);
8435 return;
8436 }
8437 }
8438 }
8439
Richard Trieu3bb8b562014-02-26 02:36:06 +00008440 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00008441 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008442 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
8443 D = R->getDecl();
8444 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
8445 D = M->getMemberDecl();
8446 }
8447
8448 // Weak Decls can be null.
8449 if (!D || D->isWeak())
8450 return;
George Burgess IV850269a2015-12-08 22:02:00 +00008451
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008452 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +00008453 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
8454 if (getCurFunction() &&
8455 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
8456 if (PV->hasAttr<NonNullAttr>()) {
8457 ComplainAboutNonnullParamOrCall(true);
8458 return;
8459 }
8460
8461 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
8462 auto ParamIter = std::find(FD->param_begin(), FD->param_end(), PV);
8463 assert(ParamIter != FD->param_end());
8464 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
8465
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008466 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
8467 if (!NonNull->args_size()) {
George Burgess IV850269a2015-12-08 22:02:00 +00008468 ComplainAboutNonnullParamOrCall(true);
8469 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008470 }
George Burgess IV850269a2015-12-08 22:02:00 +00008471
8472 for (unsigned ArgNo : NonNull->args()) {
8473 if (ArgNo == ParamNo) {
8474 ComplainAboutNonnullParamOrCall(true);
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008475 return;
8476 }
George Burgess IV850269a2015-12-08 22:02:00 +00008477 }
8478 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008479 }
8480 }
George Burgess IV850269a2015-12-08 22:02:00 +00008481 }
8482
Richard Trieu3bb8b562014-02-26 02:36:06 +00008483 QualType T = D->getType();
8484 const bool IsArray = T->isArrayType();
8485 const bool IsFunction = T->isFunctionType();
8486
Richard Trieuc1888e02014-06-28 23:25:37 +00008487 // Address of function is used to silence the function warning.
8488 if (IsAddressOf && IsFunction) {
8489 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008490 }
8491
8492 // Found nothing.
8493 if (!IsAddressOf && !IsFunction && !IsArray)
8494 return;
8495
8496 // Pretty print the expression for the diagnostic.
8497 std::string Str;
8498 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00008499 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00008500
8501 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
8502 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +00008503 enum {
8504 AddressOf,
8505 FunctionPointer,
8506 ArrayPointer
8507 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008508 if (IsAddressOf)
8509 DiagType = AddressOf;
8510 else if (IsFunction)
8511 DiagType = FunctionPointer;
8512 else if (IsArray)
8513 DiagType = ArrayPointer;
8514 else
8515 llvm_unreachable("Could not determine diagnostic.");
8516 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
8517 << Range << IsEqual;
8518
8519 if (!IsFunction)
8520 return;
8521
8522 // Suggest '&' to silence the function warning.
8523 Diag(E->getExprLoc(), diag::note_function_warning_silence)
8524 << FixItHint::CreateInsertion(E->getLocStart(), "&");
8525
8526 // Check to see if '()' fixit should be emitted.
8527 QualType ReturnType;
8528 UnresolvedSet<4> NonTemplateOverloads;
8529 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
8530 if (ReturnType.isNull())
8531 return;
8532
8533 if (IsCompare) {
8534 // There are two cases here. If there is null constant, the only suggest
8535 // for a pointer return type. If the null is 0, then suggest if the return
8536 // type is a pointer or an integer type.
8537 if (!ReturnType->isPointerType()) {
8538 if (NullKind == Expr::NPCK_ZeroExpression ||
8539 NullKind == Expr::NPCK_ZeroLiteral) {
8540 if (!ReturnType->isIntegerType())
8541 return;
8542 } else {
8543 return;
8544 }
8545 }
8546 } else { // !IsCompare
8547 // For function to bool, only suggest if the function pointer has bool
8548 // return type.
8549 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
8550 return;
8551 }
8552 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00008553 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00008554}
8555
John McCallcc7e5bf2010-05-06 08:58:33 +00008556/// Diagnoses "dangerous" implicit conversions within the given
8557/// expression (which is a full expression). Implements -Wconversion
8558/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00008559///
8560/// \param CC the "context" location of the implicit conversion, i.e.
8561/// the most location of the syntactic entity requiring the implicit
8562/// conversion
8563void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008564 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00008565 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00008566 return;
8567
8568 // Don't diagnose for value- or type-dependent expressions.
8569 if (E->isTypeDependent() || E->isValueDependent())
8570 return;
8571
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008572 // Check for array bounds violations in cases where the check isn't triggered
8573 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
8574 // ArraySubscriptExpr is on the RHS of a variable initialization.
8575 CheckArrayAccess(E);
8576
John McCallacf0ee52010-10-08 02:01:28 +00008577 // This is not the right CC for (e.g.) a variable initialization.
8578 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008579}
8580
Richard Trieu65724892014-11-15 06:37:39 +00008581/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
8582/// Input argument E is a logical expression.
8583void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
8584 ::CheckBoolLikeConversion(*this, E, CC);
8585}
8586
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008587/// Diagnose when expression is an integer constant expression and its evaluation
8588/// results in integer overflow
8589void Sema::CheckForIntOverflow (Expr *E) {
Akira Hatanakadfe2156f2016-02-10 06:06:06 +00008590 // Use a work list to deal with nested struct initializers.
8591 SmallVector<Expr *, 2> Exprs(1, E);
8592
8593 do {
8594 Expr *E = Exprs.pop_back_val();
8595
8596 if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
8597 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
8598 continue;
8599 }
8600
8601 if (auto InitList = dyn_cast<InitListExpr>(E))
8602 Exprs.append(InitList->inits().begin(), InitList->inits().end());
8603 } while (!Exprs.empty());
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008604}
8605
Richard Smithc406cb72013-01-17 01:17:56 +00008606namespace {
8607/// \brief Visitor for expressions which looks for unsequenced operations on the
8608/// same object.
8609class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00008610 typedef EvaluatedExprVisitor<SequenceChecker> Base;
8611
Richard Smithc406cb72013-01-17 01:17:56 +00008612 /// \brief A tree of sequenced regions within an expression. Two regions are
8613 /// unsequenced if one is an ancestor or a descendent of the other. When we
8614 /// finish processing an expression with sequencing, such as a comma
8615 /// expression, we fold its tree nodes into its parent, since they are
8616 /// unsequenced with respect to nodes we will visit later.
8617 class SequenceTree {
8618 struct Value {
8619 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
8620 unsigned Parent : 31;
8621 bool Merged : 1;
8622 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008623 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00008624
8625 public:
8626 /// \brief A region within an expression which may be sequenced with respect
8627 /// to some other region.
8628 class Seq {
8629 explicit Seq(unsigned N) : Index(N) {}
8630 unsigned Index;
8631 friend class SequenceTree;
8632 public:
8633 Seq() : Index(0) {}
8634 };
8635
8636 SequenceTree() { Values.push_back(Value(0)); }
8637 Seq root() const { return Seq(0); }
8638
8639 /// \brief Create a new sequence of operations, which is an unsequenced
8640 /// subset of \p Parent. This sequence of operations is sequenced with
8641 /// respect to other children of \p Parent.
8642 Seq allocate(Seq Parent) {
8643 Values.push_back(Value(Parent.Index));
8644 return Seq(Values.size() - 1);
8645 }
8646
8647 /// \brief Merge a sequence of operations into its parent.
8648 void merge(Seq S) {
8649 Values[S.Index].Merged = true;
8650 }
8651
8652 /// \brief Determine whether two operations are unsequenced. This operation
8653 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
8654 /// should have been merged into its parent as appropriate.
8655 bool isUnsequenced(Seq Cur, Seq Old) {
8656 unsigned C = representative(Cur.Index);
8657 unsigned Target = representative(Old.Index);
8658 while (C >= Target) {
8659 if (C == Target)
8660 return true;
8661 C = Values[C].Parent;
8662 }
8663 return false;
8664 }
8665
8666 private:
8667 /// \brief Pick a representative for a sequence.
8668 unsigned representative(unsigned K) {
8669 if (Values[K].Merged)
8670 // Perform path compression as we go.
8671 return Values[K].Parent = representative(Values[K].Parent);
8672 return K;
8673 }
8674 };
8675
8676 /// An object for which we can track unsequenced uses.
8677 typedef NamedDecl *Object;
8678
8679 /// Different flavors of object usage which we track. We only track the
8680 /// least-sequenced usage of each kind.
8681 enum UsageKind {
8682 /// A read of an object. Multiple unsequenced reads are OK.
8683 UK_Use,
8684 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00008685 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00008686 UK_ModAsValue,
8687 /// A modification of an object which is not sequenced before the value
8688 /// computation of the expression, such as n++.
8689 UK_ModAsSideEffect,
8690
8691 UK_Count = UK_ModAsSideEffect + 1
8692 };
8693
8694 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00008695 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00008696 Expr *Use;
8697 SequenceTree::Seq Seq;
8698 };
8699
8700 struct UsageInfo {
8701 UsageInfo() : Diagnosed(false) {}
8702 Usage Uses[UK_Count];
8703 /// Have we issued a diagnostic for this variable already?
8704 bool Diagnosed;
8705 };
8706 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
8707
8708 Sema &SemaRef;
8709 /// Sequenced regions within the expression.
8710 SequenceTree Tree;
8711 /// Declaration modifications and references which we have seen.
8712 UsageInfoMap UsageMap;
8713 /// The region we are currently within.
8714 SequenceTree::Seq Region;
8715 /// Filled in with declarations which were modified as a side-effect
8716 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008717 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00008718 /// Expressions to check later. We defer checking these to reduce
8719 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008720 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00008721
8722 /// RAII object wrapping the visitation of a sequenced subexpression of an
8723 /// expression. At the end of this process, the side-effects of the evaluation
8724 /// become sequenced with respect to the value computation of the result, so
8725 /// we downgrade any UK_ModAsSideEffect within the evaluation to
8726 /// UK_ModAsValue.
8727 struct SequencedSubexpression {
8728 SequencedSubexpression(SequenceChecker &Self)
8729 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
8730 Self.ModAsSideEffect = &ModAsSideEffect;
8731 }
8732 ~SequencedSubexpression() {
Richard Smithe8efd992014-12-03 01:05:50 +00008733 for (auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend();
8734 MI != ME; ++MI) {
8735 UsageInfo &U = Self.UsageMap[MI->first];
8736 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
8737 Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue);
8738 SideEffectUsage = MI->second;
Richard Smithc406cb72013-01-17 01:17:56 +00008739 }
8740 Self.ModAsSideEffect = OldModAsSideEffect;
8741 }
8742
8743 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008744 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
8745 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00008746 };
8747
Richard Smith40238f02013-06-20 22:21:56 +00008748 /// RAII object wrapping the visitation of a subexpression which we might
8749 /// choose to evaluate as a constant. If any subexpression is evaluated and
8750 /// found to be non-constant, this allows us to suppress the evaluation of
8751 /// the outer expression.
8752 class EvaluationTracker {
8753 public:
8754 EvaluationTracker(SequenceChecker &Self)
8755 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
8756 Self.EvalTracker = this;
8757 }
8758 ~EvaluationTracker() {
8759 Self.EvalTracker = Prev;
8760 if (Prev)
8761 Prev->EvalOK &= EvalOK;
8762 }
8763
8764 bool evaluate(const Expr *E, bool &Result) {
8765 if (!EvalOK || E->isValueDependent())
8766 return false;
8767 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
8768 return EvalOK;
8769 }
8770
8771 private:
8772 SequenceChecker &Self;
8773 EvaluationTracker *Prev;
8774 bool EvalOK;
8775 } *EvalTracker;
8776
Richard Smithc406cb72013-01-17 01:17:56 +00008777 /// \brief Find the object which is produced by the specified expression,
8778 /// if any.
8779 Object getObject(Expr *E, bool Mod) const {
8780 E = E->IgnoreParenCasts();
8781 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
8782 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
8783 return getObject(UO->getSubExpr(), Mod);
8784 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8785 if (BO->getOpcode() == BO_Comma)
8786 return getObject(BO->getRHS(), Mod);
8787 if (Mod && BO->isAssignmentOp())
8788 return getObject(BO->getLHS(), Mod);
8789 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
8790 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
8791 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
8792 return ME->getMemberDecl();
8793 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8794 // FIXME: If this is a reference, map through to its value.
8795 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00008796 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00008797 }
8798
8799 /// \brief Note that an object was modified or used by an expression.
8800 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
8801 Usage &U = UI.Uses[UK];
8802 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
8803 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
8804 ModAsSideEffect->push_back(std::make_pair(O, U));
8805 U.Use = Ref;
8806 U.Seq = Region;
8807 }
8808 }
8809 /// \brief Check whether a modification or use conflicts with a prior usage.
8810 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
8811 bool IsModMod) {
8812 if (UI.Diagnosed)
8813 return;
8814
8815 const Usage &U = UI.Uses[OtherKind];
8816 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
8817 return;
8818
8819 Expr *Mod = U.Use;
8820 Expr *ModOrUse = Ref;
8821 if (OtherKind == UK_Use)
8822 std::swap(Mod, ModOrUse);
8823
8824 SemaRef.Diag(Mod->getExprLoc(),
8825 IsModMod ? diag::warn_unsequenced_mod_mod
8826 : diag::warn_unsequenced_mod_use)
8827 << O << SourceRange(ModOrUse->getExprLoc());
8828 UI.Diagnosed = true;
8829 }
8830
8831 void notePreUse(Object O, Expr *Use) {
8832 UsageInfo &U = UsageMap[O];
8833 // Uses conflict with other modifications.
8834 checkUsage(O, U, Use, UK_ModAsValue, false);
8835 }
8836 void notePostUse(Object O, Expr *Use) {
8837 UsageInfo &U = UsageMap[O];
8838 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
8839 addUsage(U, O, Use, UK_Use);
8840 }
8841
8842 void notePreMod(Object O, Expr *Mod) {
8843 UsageInfo &U = UsageMap[O];
8844 // Modifications conflict with other modifications and with uses.
8845 checkUsage(O, U, Mod, UK_ModAsValue, true);
8846 checkUsage(O, U, Mod, UK_Use, false);
8847 }
8848 void notePostMod(Object O, Expr *Use, UsageKind UK) {
8849 UsageInfo &U = UsageMap[O];
8850 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
8851 addUsage(U, O, Use, UK);
8852 }
8853
8854public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008855 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00008856 : Base(S.Context), SemaRef(S), Region(Tree.root()),
8857 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00008858 Visit(E);
8859 }
8860
8861 void VisitStmt(Stmt *S) {
8862 // Skip all statements which aren't expressions for now.
8863 }
8864
8865 void VisitExpr(Expr *E) {
8866 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00008867 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00008868 }
8869
8870 void VisitCastExpr(CastExpr *E) {
8871 Object O = Object();
8872 if (E->getCastKind() == CK_LValueToRValue)
8873 O = getObject(E->getSubExpr(), false);
8874
8875 if (O)
8876 notePreUse(O, E);
8877 VisitExpr(E);
8878 if (O)
8879 notePostUse(O, E);
8880 }
8881
8882 void VisitBinComma(BinaryOperator *BO) {
8883 // C++11 [expr.comma]p1:
8884 // Every value computation and side effect associated with the left
8885 // expression is sequenced before every value computation and side
8886 // effect associated with the right expression.
8887 SequenceTree::Seq LHS = Tree.allocate(Region);
8888 SequenceTree::Seq RHS = Tree.allocate(Region);
8889 SequenceTree::Seq OldRegion = Region;
8890
8891 {
8892 SequencedSubexpression SeqLHS(*this);
8893 Region = LHS;
8894 Visit(BO->getLHS());
8895 }
8896
8897 Region = RHS;
8898 Visit(BO->getRHS());
8899
8900 Region = OldRegion;
8901
8902 // Forget that LHS and RHS are sequenced. They are both unsequenced
8903 // with respect to other stuff.
8904 Tree.merge(LHS);
8905 Tree.merge(RHS);
8906 }
8907
8908 void VisitBinAssign(BinaryOperator *BO) {
8909 // The modification is sequenced after the value computation of the LHS
8910 // and RHS, so check it before inspecting the operands and update the
8911 // map afterwards.
8912 Object O = getObject(BO->getLHS(), true);
8913 if (!O)
8914 return VisitExpr(BO);
8915
8916 notePreMod(O, BO);
8917
8918 // C++11 [expr.ass]p7:
8919 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
8920 // only once.
8921 //
8922 // Therefore, for a compound assignment operator, O is considered used
8923 // everywhere except within the evaluation of E1 itself.
8924 if (isa<CompoundAssignOperator>(BO))
8925 notePreUse(O, BO);
8926
8927 Visit(BO->getLHS());
8928
8929 if (isa<CompoundAssignOperator>(BO))
8930 notePostUse(O, BO);
8931
8932 Visit(BO->getRHS());
8933
Richard Smith83e37bee2013-06-26 23:16:51 +00008934 // C++11 [expr.ass]p1:
8935 // the assignment is sequenced [...] before the value computation of the
8936 // assignment expression.
8937 // C11 6.5.16/3 has no such rule.
8938 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
8939 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00008940 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008941
Richard Smithc406cb72013-01-17 01:17:56 +00008942 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
8943 VisitBinAssign(CAO);
8944 }
8945
8946 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
8947 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
8948 void VisitUnaryPreIncDec(UnaryOperator *UO) {
8949 Object O = getObject(UO->getSubExpr(), true);
8950 if (!O)
8951 return VisitExpr(UO);
8952
8953 notePreMod(O, UO);
8954 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00008955 // C++11 [expr.pre.incr]p1:
8956 // the expression ++x is equivalent to x+=1
8957 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
8958 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00008959 }
8960
8961 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
8962 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
8963 void VisitUnaryPostIncDec(UnaryOperator *UO) {
8964 Object O = getObject(UO->getSubExpr(), true);
8965 if (!O)
8966 return VisitExpr(UO);
8967
8968 notePreMod(O, UO);
8969 Visit(UO->getSubExpr());
8970 notePostMod(O, UO, UK_ModAsSideEffect);
8971 }
8972
8973 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
8974 void VisitBinLOr(BinaryOperator *BO) {
8975 // The side-effects of the LHS of an '&&' are sequenced before the
8976 // value computation of the RHS, and hence before the value computation
8977 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
8978 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00008979 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00008980 {
8981 SequencedSubexpression Sequenced(*this);
8982 Visit(BO->getLHS());
8983 }
8984
8985 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00008986 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00008987 if (!Result)
8988 Visit(BO->getRHS());
8989 } else {
8990 // Check for unsequenced operations in the RHS, treating it as an
8991 // entirely separate evaluation.
8992 //
8993 // FIXME: If there are operations in the RHS which are unsequenced
8994 // with respect to operations outside the RHS, and those operations
8995 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00008996 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00008997 }
Richard Smithc406cb72013-01-17 01:17:56 +00008998 }
8999 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00009000 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00009001 {
9002 SequencedSubexpression Sequenced(*this);
9003 Visit(BO->getLHS());
9004 }
9005
9006 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00009007 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00009008 if (Result)
9009 Visit(BO->getRHS());
9010 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00009011 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00009012 }
Richard Smithc406cb72013-01-17 01:17:56 +00009013 }
9014
9015 // Only visit the condition, unless we can be sure which subexpression will
9016 // be chosen.
9017 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00009018 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00009019 {
9020 SequencedSubexpression Sequenced(*this);
9021 Visit(CO->getCond());
9022 }
Richard Smithc406cb72013-01-17 01:17:56 +00009023
9024 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00009025 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00009026 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00009027 else {
Richard Smithd33f5202013-01-17 23:18:09 +00009028 WorkList.push_back(CO->getTrueExpr());
9029 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00009030 }
Richard Smithc406cb72013-01-17 01:17:56 +00009031 }
9032
Richard Smithe3dbfe02013-06-30 10:40:20 +00009033 void VisitCallExpr(CallExpr *CE) {
9034 // C++11 [intro.execution]p15:
9035 // When calling a function [...], every value computation and side effect
9036 // associated with any argument expression, or with the postfix expression
9037 // designating the called function, is sequenced before execution of every
9038 // expression or statement in the body of the function [and thus before
9039 // the value computation of its result].
9040 SequencedSubexpression Sequenced(*this);
9041 Base::VisitCallExpr(CE);
9042
9043 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
9044 }
9045
Richard Smithc406cb72013-01-17 01:17:56 +00009046 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00009047 // This is a call, so all subexpressions are sequenced before the result.
9048 SequencedSubexpression Sequenced(*this);
9049
Richard Smithc406cb72013-01-17 01:17:56 +00009050 if (!CCE->isListInitialization())
9051 return VisitExpr(CCE);
9052
9053 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009054 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00009055 SequenceTree::Seq Parent = Region;
9056 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
9057 E = CCE->arg_end();
9058 I != E; ++I) {
9059 Region = Tree.allocate(Parent);
9060 Elts.push_back(Region);
9061 Visit(*I);
9062 }
9063
9064 // Forget that the initializers are sequenced.
9065 Region = Parent;
9066 for (unsigned I = 0; I < Elts.size(); ++I)
9067 Tree.merge(Elts[I]);
9068 }
9069
9070 void VisitInitListExpr(InitListExpr *ILE) {
9071 if (!SemaRef.getLangOpts().CPlusPlus11)
9072 return VisitExpr(ILE);
9073
9074 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009075 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00009076 SequenceTree::Seq Parent = Region;
9077 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
9078 Expr *E = ILE->getInit(I);
9079 if (!E) continue;
9080 Region = Tree.allocate(Parent);
9081 Elts.push_back(Region);
9082 Visit(E);
9083 }
9084
9085 // Forget that the initializers are sequenced.
9086 Region = Parent;
9087 for (unsigned I = 0; I < Elts.size(); ++I)
9088 Tree.merge(Elts[I]);
9089 }
9090};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009091} // end anonymous namespace
Richard Smithc406cb72013-01-17 01:17:56 +00009092
9093void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009094 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00009095 WorkList.push_back(E);
9096 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00009097 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00009098 SequenceChecker(*this, Item, WorkList);
9099 }
Richard Smithc406cb72013-01-17 01:17:56 +00009100}
9101
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009102void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
9103 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00009104 CheckImplicitConversions(E, CheckLoc);
9105 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009106 if (!IsConstexpr && !E->isValueDependent())
9107 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00009108}
9109
John McCall1f425642010-11-11 03:21:53 +00009110void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
9111 FieldDecl *BitField,
9112 Expr *Init) {
9113 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
9114}
9115
David Majnemer61a5bbf2015-04-07 22:08:51 +00009116static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
9117 SourceLocation Loc) {
9118 if (!PType->isVariablyModifiedType())
9119 return;
9120 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
9121 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
9122 return;
9123 }
David Majnemerdf8f73f2015-04-09 19:53:25 +00009124 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
9125 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
9126 return;
9127 }
David Majnemer61a5bbf2015-04-07 22:08:51 +00009128 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
9129 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
9130 return;
9131 }
9132
9133 const ArrayType *AT = S.Context.getAsArrayType(PType);
9134 if (!AT)
9135 return;
9136
9137 if (AT->getSizeModifier() != ArrayType::Star) {
9138 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
9139 return;
9140 }
9141
9142 S.Diag(Loc, diag::err_array_star_in_function_definition);
9143}
9144
Mike Stump0c2ec772010-01-21 03:59:47 +00009145/// CheckParmsForFunctionDef - Check that the parameters of the given
9146/// function are appropriate for the definition of a function. This
9147/// takes care of any checks that cannot be performed on the
9148/// declaration itself, e.g., that the types of each of the function
9149/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00009150bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
9151 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00009152 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00009153 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00009154 for (; P != PEnd; ++P) {
9155 ParmVarDecl *Param = *P;
9156
Mike Stump0c2ec772010-01-21 03:59:47 +00009157 // C99 6.7.5.3p4: the parameters in a parameter type list in a
9158 // function declarator that is part of a function definition of
9159 // that function shall not have incomplete type.
9160 //
9161 // This is also C++ [dcl.fct]p6.
9162 if (!Param->isInvalidDecl() &&
9163 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00009164 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00009165 Param->setInvalidDecl();
9166 HasInvalidParm = true;
9167 }
9168
9169 // C99 6.9.1p5: If the declarator includes a parameter type list, the
9170 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00009171 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00009172 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00009173 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00009174 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00009175 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00009176
9177 // C99 6.7.5.3p12:
9178 // If the function declarator is not part of a definition of that
9179 // function, parameters may have incomplete type and may use the [*]
9180 // notation in their sequences of declarator specifiers to specify
9181 // variable length array types.
9182 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +00009183 // FIXME: This diagnostic should point the '[*]' if source-location
9184 // information is added for it.
9185 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00009186
9187 // MSVC destroys objects passed by value in the callee. Therefore a
9188 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00009189 // object's destructor. However, we don't perform any direct access check
9190 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00009191 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
9192 .getCXXABI()
9193 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00009194 if (!Param->isInvalidDecl()) {
9195 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
9196 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
9197 if (!ClassDecl->isInvalidDecl() &&
9198 !ClassDecl->hasIrrelevantDestructor() &&
9199 !ClassDecl->isDependentContext()) {
9200 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
9201 MarkFunctionReferenced(Param->getLocation(), Destructor);
9202 DiagnoseUseOfDecl(Destructor, Param->getLocation());
9203 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00009204 }
9205 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00009206 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009207
9208 // Parameters with the pass_object_size attribute only need to be marked
9209 // constant at function definitions. Because we lack information about
9210 // whether we're on a declaration or definition when we're instantiating the
9211 // attribute, we need to check for constness here.
9212 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
9213 if (!Param->getType().isConstQualified())
9214 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
9215 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +00009216 }
9217
9218 return HasInvalidParm;
9219}
John McCall2b5c1b22010-08-12 21:44:57 +00009220
9221/// CheckCastAlign - Implements -Wcast-align, which warns when a
9222/// pointer cast increases the alignment requirements.
9223void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
9224 // This is actually a lot of work to potentially be doing on every
9225 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009226 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00009227 return;
9228
9229 // Ignore dependent types.
9230 if (T->isDependentType() || Op->getType()->isDependentType())
9231 return;
9232
9233 // Require that the destination be a pointer type.
9234 const PointerType *DestPtr = T->getAs<PointerType>();
9235 if (!DestPtr) return;
9236
9237 // If the destination has alignment 1, we're done.
9238 QualType DestPointee = DestPtr->getPointeeType();
9239 if (DestPointee->isIncompleteType()) return;
9240 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
9241 if (DestAlign.isOne()) return;
9242
9243 // Require that the source be a pointer type.
9244 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
9245 if (!SrcPtr) return;
9246 QualType SrcPointee = SrcPtr->getPointeeType();
9247
9248 // Whitelist casts from cv void*. We already implicitly
9249 // whitelisted casts to cv void*, since they have alignment 1.
9250 // Also whitelist casts involving incomplete types, which implicitly
9251 // includes 'void'.
9252 if (SrcPointee->isIncompleteType()) return;
9253
9254 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
9255 if (SrcAlign >= DestAlign) return;
9256
9257 Diag(TRange.getBegin(), diag::warn_cast_align)
9258 << Op->getType() << T
9259 << static_cast<unsigned>(SrcAlign.getQuantity())
9260 << static_cast<unsigned>(DestAlign.getQuantity())
9261 << TRange << Op->getSourceRange();
9262}
9263
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009264static const Type* getElementType(const Expr *BaseExpr) {
9265 const Type* EltType = BaseExpr->getType().getTypePtr();
9266 if (EltType->isAnyPointerType())
9267 return EltType->getPointeeType().getTypePtr();
9268 else if (EltType->isArrayType())
9269 return EltType->getBaseElementTypeUnsafe();
9270 return EltType;
9271}
9272
Chandler Carruth28389f02011-08-05 09:10:50 +00009273/// \brief Check whether this array fits the idiom of a size-one tail padded
9274/// array member of a struct.
9275///
9276/// We avoid emitting out-of-bounds access warnings for such arrays as they are
9277/// commonly used to emulate flexible arrays in C89 code.
9278static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
9279 const NamedDecl *ND) {
9280 if (Size != 1 || !ND) return false;
9281
9282 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
9283 if (!FD) return false;
9284
9285 // Don't consider sizes resulting from macro expansions or template argument
9286 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00009287
9288 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00009289 while (TInfo) {
9290 TypeLoc TL = TInfo->getTypeLoc();
9291 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00009292 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
9293 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00009294 TInfo = TDL->getTypeSourceInfo();
9295 continue;
9296 }
David Blaikie6adc78e2013-02-18 22:06:02 +00009297 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
9298 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00009299 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
9300 return false;
9301 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00009302 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00009303 }
Chandler Carruth28389f02011-08-05 09:10:50 +00009304
9305 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00009306 if (!RD) return false;
9307 if (RD->isUnion()) return false;
9308 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
9309 if (!CRD->isStandardLayout()) return false;
9310 }
Chandler Carruth28389f02011-08-05 09:10:50 +00009311
Benjamin Kramer8c543672011-08-06 03:04:42 +00009312 // See if this is the last field decl in the record.
9313 const Decl *D = FD;
9314 while ((D = D->getNextDeclInContext()))
9315 if (isa<FieldDecl>(D))
9316 return false;
9317 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00009318}
9319
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009320void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009321 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00009322 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009323 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009324 if (IndexExpr->isValueDependent())
9325 return;
9326
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00009327 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009328 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009329 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009330 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009331 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00009332 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00009333
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009334 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +00009335 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +00009336 return;
Richard Smith13f67182011-12-16 19:31:14 +00009337 if (IndexNegated)
9338 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00009339
Craig Topperc3ec1492014-05-26 06:22:03 +00009340 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00009341 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
9342 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00009343 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00009344 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00009345
Ted Kremeneke4b316c2011-02-23 23:06:04 +00009346 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00009347 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00009348 if (!size.isStrictlyPositive())
9349 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009350
9351 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00009352 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009353 // Make sure we're comparing apples to apples when comparing index to size
9354 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
9355 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00009356 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00009357 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009358 if (ptrarith_typesize != array_typesize) {
9359 // There's a cast to a different size type involved
9360 uint64_t ratio = array_typesize / ptrarith_typesize;
9361 // TODO: Be smarter about handling cases where array_typesize is not a
9362 // multiple of ptrarith_typesize
9363 if (ptrarith_typesize * ratio == array_typesize)
9364 size *= llvm::APInt(size.getBitWidth(), ratio);
9365 }
9366 }
9367
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009368 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009369 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00009370 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009371 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00009372
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009373 // For array subscripting the index must be less than size, but for pointer
9374 // arithmetic also allow the index (offset) to be equal to size since
9375 // computing the next address after the end of the array is legal and
9376 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009377 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00009378 return;
9379
9380 // Also don't warn for arrays of size 1 which are members of some
9381 // structure. These are often used to approximate flexible arrays in C89
9382 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009383 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00009384 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009385
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009386 // Suppress the warning if the subscript expression (as identified by the
9387 // ']' location) and the index expression are both from macro expansions
9388 // within a system header.
9389 if (ASE) {
9390 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
9391 ASE->getRBracketLoc());
9392 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
9393 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
9394 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00009395 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009396 return;
9397 }
9398 }
9399
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009400 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009401 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009402 DiagID = diag::warn_array_index_exceeds_bounds;
9403
9404 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
9405 PDiag(DiagID) << index.toString(10, true)
9406 << size.toString(10, true)
9407 << (unsigned)size.getLimitedValue(~0U)
9408 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009409 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009410 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009411 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009412 DiagID = diag::warn_ptr_arith_precedes_bounds;
9413 if (index.isNegative()) index = -index;
9414 }
9415
9416 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
9417 PDiag(DiagID) << index.toString(10, true)
9418 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00009419 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00009420
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00009421 if (!ND) {
9422 // Try harder to find a NamedDecl to point at in the note.
9423 while (const ArraySubscriptExpr *ASE =
9424 dyn_cast<ArraySubscriptExpr>(BaseExpr))
9425 BaseExpr = ASE->getBase()->IgnoreParenCasts();
9426 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
9427 ND = dyn_cast<NamedDecl>(DRE->getDecl());
9428 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
9429 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
9430 }
9431
Chandler Carruth1af88f12011-02-17 21:10:52 +00009432 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009433 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
9434 PDiag(diag::note_array_index_out_of_bounds)
9435 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00009436}
9437
Ted Kremenekdf26df72011-03-01 18:41:00 +00009438void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009439 int AllowOnePastEnd = 0;
9440 while (expr) {
9441 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00009442 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009443 case Stmt::ArraySubscriptExprClass: {
9444 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009445 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009446 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00009447 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009448 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +00009449 case Stmt::OMPArraySectionExprClass: {
9450 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
9451 if (ASE->getLowerBound())
9452 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
9453 /*ASE=*/nullptr, AllowOnePastEnd > 0);
9454 return;
9455 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009456 case Stmt::UnaryOperatorClass: {
9457 // Only unwrap the * and & unary operators
9458 const UnaryOperator *UO = cast<UnaryOperator>(expr);
9459 expr = UO->getSubExpr();
9460 switch (UO->getOpcode()) {
9461 case UO_AddrOf:
9462 AllowOnePastEnd++;
9463 break;
9464 case UO_Deref:
9465 AllowOnePastEnd--;
9466 break;
9467 default:
9468 return;
9469 }
9470 break;
9471 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00009472 case Stmt::ConditionalOperatorClass: {
9473 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
9474 if (const Expr *lhs = cond->getLHS())
9475 CheckArrayAccess(lhs);
9476 if (const Expr *rhs = cond->getRHS())
9477 CheckArrayAccess(rhs);
9478 return;
9479 }
9480 default:
9481 return;
9482 }
Peter Collingbourne91147592011-04-15 00:35:48 +00009483 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00009484}
John McCall31168b02011-06-15 23:02:42 +00009485
9486//===--- CHECK: Objective-C retain cycles ----------------------------------//
9487
9488namespace {
9489 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00009490 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00009491 VarDecl *Variable;
9492 SourceRange Range;
9493 SourceLocation Loc;
9494 bool Indirect;
9495
9496 void setLocsFrom(Expr *e) {
9497 Loc = e->getExprLoc();
9498 Range = e->getSourceRange();
9499 }
9500 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009501} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +00009502
9503/// Consider whether capturing the given variable can possibly lead to
9504/// a retain cycle.
9505static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00009506 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00009507 // lifetime. In MRR, it's captured strongly if the variable is
9508 // __block and has an appropriate type.
9509 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
9510 return false;
9511
9512 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009513 if (ref)
9514 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00009515 return true;
9516}
9517
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009518static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00009519 while (true) {
9520 e = e->IgnoreParens();
9521 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
9522 switch (cast->getCastKind()) {
9523 case CK_BitCast:
9524 case CK_LValueBitCast:
9525 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00009526 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00009527 e = cast->getSubExpr();
9528 continue;
9529
John McCall31168b02011-06-15 23:02:42 +00009530 default:
9531 return false;
9532 }
9533 }
9534
9535 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
9536 ObjCIvarDecl *ivar = ref->getDecl();
9537 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
9538 return false;
9539
9540 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009541 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00009542 return false;
9543
9544 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
9545 owner.Indirect = true;
9546 return true;
9547 }
9548
9549 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
9550 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
9551 if (!var) return false;
9552 return considerVariable(var, ref, owner);
9553 }
9554
John McCall31168b02011-06-15 23:02:42 +00009555 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
9556 if (member->isArrow()) return false;
9557
9558 // Don't count this as an indirect ownership.
9559 e = member->getBase();
9560 continue;
9561 }
9562
John McCallfe96e0b2011-11-06 09:01:30 +00009563 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
9564 // Only pay attention to pseudo-objects on property references.
9565 ObjCPropertyRefExpr *pre
9566 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
9567 ->IgnoreParens());
9568 if (!pre) return false;
9569 if (pre->isImplicitProperty()) return false;
9570 ObjCPropertyDecl *property = pre->getExplicitProperty();
9571 if (!property->isRetaining() &&
9572 !(property->getPropertyIvarDecl() &&
9573 property->getPropertyIvarDecl()->getType()
9574 .getObjCLifetime() == Qualifiers::OCL_Strong))
9575 return false;
9576
9577 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009578 if (pre->isSuperReceiver()) {
9579 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
9580 if (!owner.Variable)
9581 return false;
9582 owner.Loc = pre->getLocation();
9583 owner.Range = pre->getSourceRange();
9584 return true;
9585 }
John McCallfe96e0b2011-11-06 09:01:30 +00009586 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
9587 ->getSourceExpr());
9588 continue;
9589 }
9590
John McCall31168b02011-06-15 23:02:42 +00009591 // Array ivars?
9592
9593 return false;
9594 }
9595}
9596
9597namespace {
9598 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
9599 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
9600 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009601 Context(Context), Variable(variable), Capturer(nullptr),
9602 VarWillBeReased(false) {}
9603 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +00009604 VarDecl *Variable;
9605 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009606 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +00009607
9608 void VisitDeclRefExpr(DeclRefExpr *ref) {
9609 if (ref->getDecl() == Variable && !Capturer)
9610 Capturer = ref;
9611 }
9612
John McCall31168b02011-06-15 23:02:42 +00009613 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
9614 if (Capturer) return;
9615 Visit(ref->getBase());
9616 if (Capturer && ref->isFreeIvar())
9617 Capturer = ref;
9618 }
9619
9620 void VisitBlockExpr(BlockExpr *block) {
9621 // Look inside nested blocks
9622 if (block->getBlockDecl()->capturesVariable(Variable))
9623 Visit(block->getBlockDecl()->getBody());
9624 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00009625
9626 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
9627 if (Capturer) return;
9628 if (OVE->getSourceExpr())
9629 Visit(OVE->getSourceExpr());
9630 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009631 void VisitBinaryOperator(BinaryOperator *BinOp) {
9632 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
9633 return;
9634 Expr *LHS = BinOp->getLHS();
9635 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
9636 if (DRE->getDecl() != Variable)
9637 return;
9638 if (Expr *RHS = BinOp->getRHS()) {
9639 RHS = RHS->IgnoreParenCasts();
9640 llvm::APSInt Value;
9641 VarWillBeReased =
9642 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
9643 }
9644 }
9645 }
John McCall31168b02011-06-15 23:02:42 +00009646 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009647} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +00009648
9649/// Check whether the given argument is a block which captures a
9650/// variable.
9651static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
9652 assert(owner.Variable && owner.Loc.isValid());
9653
9654 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00009655
9656 // Look through [^{...} copy] and Block_copy(^{...}).
9657 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
9658 Selector Cmd = ME->getSelector();
9659 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
9660 e = ME->getInstanceReceiver();
9661 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +00009662 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +00009663 e = e->IgnoreParenCasts();
9664 }
9665 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
9666 if (CE->getNumArgs() == 1) {
9667 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00009668 if (Fn) {
9669 const IdentifierInfo *FnI = Fn->getIdentifier();
9670 if (FnI && FnI->isStr("_Block_copy")) {
9671 e = CE->getArg(0)->IgnoreParenCasts();
9672 }
9673 }
Jordan Rose67e887c2012-09-17 17:54:30 +00009674 }
9675 }
9676
John McCall31168b02011-06-15 23:02:42 +00009677 BlockExpr *block = dyn_cast<BlockExpr>(e);
9678 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +00009679 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00009680
9681 FindCaptureVisitor visitor(S.Context, owner.Variable);
9682 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009683 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +00009684}
9685
9686static void diagnoseRetainCycle(Sema &S, Expr *capturer,
9687 RetainCycleOwner &owner) {
9688 assert(capturer);
9689 assert(owner.Variable && owner.Loc.isValid());
9690
9691 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
9692 << owner.Variable << capturer->getSourceRange();
9693 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
9694 << owner.Indirect << owner.Range;
9695}
9696
9697/// Check for a keyword selector that starts with the word 'add' or
9698/// 'set'.
9699static bool isSetterLikeSelector(Selector sel) {
9700 if (sel.isUnarySelector()) return false;
9701
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009702 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00009703 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00009704 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00009705 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00009706 else if (str.startswith("add")) {
9707 // Specially whitelist 'addOperationWithBlock:'.
9708 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
9709 return false;
9710 str = str.substr(3);
9711 }
John McCall31168b02011-06-15 23:02:42 +00009712 else
9713 return false;
9714
9715 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00009716 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00009717}
9718
Benjamin Kramer3a743452015-03-09 15:03:32 +00009719static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
9720 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009721 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
9722 Message->getReceiverInterface(),
9723 NSAPI::ClassId_NSMutableArray);
9724 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009725 return None;
9726 }
9727
9728 Selector Sel = Message->getSelector();
9729
9730 Optional<NSAPI::NSArrayMethodKind> MKOpt =
9731 S.NSAPIObj->getNSArrayMethodKind(Sel);
9732 if (!MKOpt) {
9733 return None;
9734 }
9735
9736 NSAPI::NSArrayMethodKind MK = *MKOpt;
9737
9738 switch (MK) {
9739 case NSAPI::NSMutableArr_addObject:
9740 case NSAPI::NSMutableArr_insertObjectAtIndex:
9741 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
9742 return 0;
9743 case NSAPI::NSMutableArr_replaceObjectAtIndex:
9744 return 1;
9745
9746 default:
9747 return None;
9748 }
9749
9750 return None;
9751}
9752
9753static
9754Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
9755 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009756 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
9757 Message->getReceiverInterface(),
9758 NSAPI::ClassId_NSMutableDictionary);
9759 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009760 return None;
9761 }
9762
9763 Selector Sel = Message->getSelector();
9764
9765 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
9766 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
9767 if (!MKOpt) {
9768 return None;
9769 }
9770
9771 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
9772
9773 switch (MK) {
9774 case NSAPI::NSMutableDict_setObjectForKey:
9775 case NSAPI::NSMutableDict_setValueForKey:
9776 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
9777 return 0;
9778
9779 default:
9780 return None;
9781 }
9782
9783 return None;
9784}
9785
9786static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009787 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
9788 Message->getReceiverInterface(),
9789 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +00009790
Alex Denisov5dfac812015-08-06 04:51:14 +00009791 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
9792 Message->getReceiverInterface(),
9793 NSAPI::ClassId_NSMutableOrderedSet);
9794 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009795 return None;
9796 }
9797
9798 Selector Sel = Message->getSelector();
9799
9800 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
9801 if (!MKOpt) {
9802 return None;
9803 }
9804
9805 NSAPI::NSSetMethodKind MK = *MKOpt;
9806
9807 switch (MK) {
9808 case NSAPI::NSMutableSet_addObject:
9809 case NSAPI::NSOrderedSet_setObjectAtIndex:
9810 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
9811 case NSAPI::NSOrderedSet_insertObjectAtIndex:
9812 return 0;
9813 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
9814 return 1;
9815 }
9816
9817 return None;
9818}
9819
9820void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
9821 if (!Message->isInstanceMessage()) {
9822 return;
9823 }
9824
9825 Optional<int> ArgOpt;
9826
9827 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
9828 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
9829 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
9830 return;
9831 }
9832
9833 int ArgIndex = *ArgOpt;
9834
Alex Denisove1d882c2015-03-04 17:55:52 +00009835 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
9836 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
9837 Arg = OE->getSourceExpr()->IgnoreImpCasts();
9838 }
9839
Alex Denisov5dfac812015-08-06 04:51:14 +00009840 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009841 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009842 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009843 Diag(Message->getSourceRange().getBegin(),
9844 diag::warn_objc_circular_container)
Alex Denisov5dfac812015-08-06 04:51:14 +00009845 << ArgRE->getDecl()->getName() << StringRef("super");
Alex Denisove1d882c2015-03-04 17:55:52 +00009846 }
9847 }
Alex Denisov5dfac812015-08-06 04:51:14 +00009848 } else {
9849 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
9850
9851 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
9852 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
9853 }
9854
9855 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
9856 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
9857 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
9858 ValueDecl *Decl = ReceiverRE->getDecl();
9859 Diag(Message->getSourceRange().getBegin(),
9860 diag::warn_objc_circular_container)
9861 << Decl->getName() << Decl->getName();
9862 if (!ArgRE->isObjCSelfExpr()) {
9863 Diag(Decl->getLocation(),
9864 diag::note_objc_circular_container_declared_here)
9865 << Decl->getName();
9866 }
9867 }
9868 }
9869 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
9870 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
9871 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
9872 ObjCIvarDecl *Decl = IvarRE->getDecl();
9873 Diag(Message->getSourceRange().getBegin(),
9874 diag::warn_objc_circular_container)
9875 << Decl->getName() << Decl->getName();
9876 Diag(Decl->getLocation(),
9877 diag::note_objc_circular_container_declared_here)
9878 << Decl->getName();
9879 }
Alex Denisove1d882c2015-03-04 17:55:52 +00009880 }
9881 }
9882 }
Alex Denisove1d882c2015-03-04 17:55:52 +00009883}
9884
John McCall31168b02011-06-15 23:02:42 +00009885/// Check a message send to see if it's likely to cause a retain cycle.
9886void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
9887 // Only check instance methods whose selector looks like a setter.
9888 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
9889 return;
9890
9891 // Try to find a variable that the receiver is strongly owned by.
9892 RetainCycleOwner owner;
9893 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009894 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00009895 return;
9896 } else {
9897 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
9898 owner.Variable = getCurMethodDecl()->getSelfDecl();
9899 owner.Loc = msg->getSuperLoc();
9900 owner.Range = msg->getSuperLoc();
9901 }
9902
9903 // Check whether the receiver is captured by any of the arguments.
9904 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
9905 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
9906 return diagnoseRetainCycle(*this, capturer, owner);
9907}
9908
9909/// Check a property assign to see if it's likely to cause a retain cycle.
9910void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
9911 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009912 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00009913 return;
9914
9915 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
9916 diagnoseRetainCycle(*this, capturer, owner);
9917}
9918
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009919void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
9920 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +00009921 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009922 return;
9923
9924 // Because we don't have an expression for the variable, we have to set the
9925 // location explicitly here.
9926 Owner.Loc = Var->getLocation();
9927 Owner.Range = Var->getSourceRange();
9928
9929 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
9930 diagnoseRetainCycle(*this, Capturer, Owner);
9931}
9932
Ted Kremenek9304da92012-12-21 08:04:28 +00009933static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
9934 Expr *RHS, bool isProperty) {
9935 // Check if RHS is an Objective-C object literal, which also can get
9936 // immediately zapped in a weak reference. Note that we explicitly
9937 // allow ObjCStringLiterals, since those are designed to never really die.
9938 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009939
Ted Kremenek64873352012-12-21 22:46:35 +00009940 // This enum needs to match with the 'select' in
9941 // warn_objc_arc_literal_assign (off-by-1).
9942 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
9943 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
9944 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009945
9946 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00009947 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00009948 << (isProperty ? 0 : 1)
9949 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009950
9951 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00009952}
9953
Ted Kremenekc1f014a2012-12-21 19:45:30 +00009954static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
9955 Qualifiers::ObjCLifetime LT,
9956 Expr *RHS, bool isProperty) {
9957 // Strip off any implicit cast added to get to the one ARC-specific.
9958 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
9959 if (cast->getCastKind() == CK_ARCConsumeObject) {
9960 S.Diag(Loc, diag::warn_arc_retained_assign)
9961 << (LT == Qualifiers::OCL_ExplicitNone)
9962 << (isProperty ? 0 : 1)
9963 << RHS->getSourceRange();
9964 return true;
9965 }
9966 RHS = cast->getSubExpr();
9967 }
9968
9969 if (LT == Qualifiers::OCL_Weak &&
9970 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
9971 return true;
9972
9973 return false;
9974}
9975
Ted Kremenekb36234d2012-12-21 08:04:20 +00009976bool Sema::checkUnsafeAssigns(SourceLocation Loc,
9977 QualType LHS, Expr *RHS) {
9978 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
9979
9980 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
9981 return false;
9982
9983 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
9984 return true;
9985
9986 return false;
9987}
9988
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009989void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
9990 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009991 QualType LHSType;
9992 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00009993 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009994 ObjCPropertyRefExpr *PRE
9995 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
9996 if (PRE && !PRE->isImplicitProperty()) {
9997 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
9998 if (PD)
9999 LHSType = PD->getType();
10000 }
10001
10002 if (LHSType.isNull())
10003 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +000010004
10005 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
10006
10007 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010008 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +000010009 getCurFunction()->markSafeWeakUse(LHS);
10010 }
10011
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010012 if (checkUnsafeAssigns(Loc, LHSType, RHS))
10013 return;
Jordan Rose657b5f42012-09-28 22:21:35 +000010014
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010015 // FIXME. Check for other life times.
10016 if (LT != Qualifiers::OCL_None)
10017 return;
10018
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010019 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010020 if (PRE->isImplicitProperty())
10021 return;
10022 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
10023 if (!PD)
10024 return;
10025
Bill Wendling44426052012-12-20 19:22:21 +000010026 unsigned Attributes = PD->getPropertyAttributes();
10027 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010028 // when 'assign' attribute was not explicitly specified
10029 // by user, ignore it and rely on property type itself
10030 // for lifetime info.
10031 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
10032 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
10033 LHSType->isObjCRetainableType())
10034 return;
10035
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010036 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +000010037 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010038 Diag(Loc, diag::warn_arc_retained_property_assign)
10039 << RHS->getSourceRange();
10040 return;
10041 }
10042 RHS = cast->getSubExpr();
10043 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010044 }
Bill Wendling44426052012-12-20 19:22:21 +000010045 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +000010046 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
10047 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +000010048 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010049 }
10050}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010051
10052//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
10053
10054namespace {
10055bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
10056 SourceLocation StmtLoc,
10057 const NullStmt *Body) {
10058 // Do not warn if the body is a macro that expands to nothing, e.g:
10059 //
10060 // #define CALL(x)
10061 // if (condition)
10062 // CALL(0);
10063 //
10064 if (Body->hasLeadingEmptyMacro())
10065 return false;
10066
10067 // Get line numbers of statement and body.
10068 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +000010069 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010070 &StmtLineInvalid);
10071 if (StmtLineInvalid)
10072 return false;
10073
10074 bool BodyLineInvalid;
10075 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
10076 &BodyLineInvalid);
10077 if (BodyLineInvalid)
10078 return false;
10079
10080 // Warn if null statement and body are on the same line.
10081 if (StmtLine != BodyLine)
10082 return false;
10083
10084 return true;
10085}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010086} // end anonymous namespace
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010087
10088void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
10089 const Stmt *Body,
10090 unsigned DiagID) {
10091 // Since this is a syntactic check, don't emit diagnostic for template
10092 // instantiations, this just adds noise.
10093 if (CurrentInstantiationScope)
10094 return;
10095
10096 // The body should be a null statement.
10097 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
10098 if (!NBody)
10099 return;
10100
10101 // Do the usual checks.
10102 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
10103 return;
10104
10105 Diag(NBody->getSemiLoc(), DiagID);
10106 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
10107}
10108
10109void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
10110 const Stmt *PossibleBody) {
10111 assert(!CurrentInstantiationScope); // Ensured by caller
10112
10113 SourceLocation StmtLoc;
10114 const Stmt *Body;
10115 unsigned DiagID;
10116 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
10117 StmtLoc = FS->getRParenLoc();
10118 Body = FS->getBody();
10119 DiagID = diag::warn_empty_for_body;
10120 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
10121 StmtLoc = WS->getCond()->getSourceRange().getEnd();
10122 Body = WS->getBody();
10123 DiagID = diag::warn_empty_while_body;
10124 } else
10125 return; // Neither `for' nor `while'.
10126
10127 // The body should be a null statement.
10128 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
10129 if (!NBody)
10130 return;
10131
10132 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010133 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010134 return;
10135
10136 // Do the usual checks.
10137 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
10138 return;
10139
10140 // `for(...);' and `while(...);' are popular idioms, so in order to keep
10141 // noise level low, emit diagnostics only if for/while is followed by a
10142 // CompoundStmt, e.g.:
10143 // for (int i = 0; i < n; i++);
10144 // {
10145 // a(i);
10146 // }
10147 // or if for/while is followed by a statement with more indentation
10148 // than for/while itself:
10149 // for (int i = 0; i < n; i++);
10150 // a(i);
10151 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
10152 if (!ProbableTypo) {
10153 bool BodyColInvalid;
10154 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
10155 PossibleBody->getLocStart(),
10156 &BodyColInvalid);
10157 if (BodyColInvalid)
10158 return;
10159
10160 bool StmtColInvalid;
10161 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
10162 S->getLocStart(),
10163 &StmtColInvalid);
10164 if (StmtColInvalid)
10165 return;
10166
10167 if (BodyCol > StmtCol)
10168 ProbableTypo = true;
10169 }
10170
10171 if (ProbableTypo) {
10172 Diag(NBody->getSemiLoc(), DiagID);
10173 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
10174 }
10175}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010176
Richard Trieu36d0b2b2015-01-13 02:32:02 +000010177//===--- CHECK: Warn on self move with std::move. -------------------------===//
10178
10179/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
10180void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
10181 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +000010182 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
10183 return;
10184
10185 if (!ActiveTemplateInstantiations.empty())
10186 return;
10187
10188 // Strip parens and casts away.
10189 LHSExpr = LHSExpr->IgnoreParenImpCasts();
10190 RHSExpr = RHSExpr->IgnoreParenImpCasts();
10191
10192 // Check for a call expression
10193 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
10194 if (!CE || CE->getNumArgs() != 1)
10195 return;
10196
10197 // Check for a call to std::move
10198 const FunctionDecl *FD = CE->getDirectCallee();
10199 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
10200 !FD->getIdentifier()->isStr("move"))
10201 return;
10202
10203 // Get argument from std::move
10204 RHSExpr = CE->getArg(0);
10205
10206 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
10207 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
10208
10209 // Two DeclRefExpr's, check that the decls are the same.
10210 if (LHSDeclRef && RHSDeclRef) {
10211 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
10212 return;
10213 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
10214 RHSDeclRef->getDecl()->getCanonicalDecl())
10215 return;
10216
10217 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10218 << LHSExpr->getSourceRange()
10219 << RHSExpr->getSourceRange();
10220 return;
10221 }
10222
10223 // Member variables require a different approach to check for self moves.
10224 // MemberExpr's are the same if every nested MemberExpr refers to the same
10225 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
10226 // the base Expr's are CXXThisExpr's.
10227 const Expr *LHSBase = LHSExpr;
10228 const Expr *RHSBase = RHSExpr;
10229 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
10230 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
10231 if (!LHSME || !RHSME)
10232 return;
10233
10234 while (LHSME && RHSME) {
10235 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
10236 RHSME->getMemberDecl()->getCanonicalDecl())
10237 return;
10238
10239 LHSBase = LHSME->getBase();
10240 RHSBase = RHSME->getBase();
10241 LHSME = dyn_cast<MemberExpr>(LHSBase);
10242 RHSME = dyn_cast<MemberExpr>(RHSBase);
10243 }
10244
10245 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
10246 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
10247 if (LHSDeclRef && RHSDeclRef) {
10248 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
10249 return;
10250 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
10251 RHSDeclRef->getDecl()->getCanonicalDecl())
10252 return;
10253
10254 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10255 << LHSExpr->getSourceRange()
10256 << RHSExpr->getSourceRange();
10257 return;
10258 }
10259
10260 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
10261 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10262 << LHSExpr->getSourceRange()
10263 << RHSExpr->getSourceRange();
10264}
10265
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010266//===--- Layout compatibility ----------------------------------------------//
10267
10268namespace {
10269
10270bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
10271
10272/// \brief Check if two enumeration types are layout-compatible.
10273bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
10274 // C++11 [dcl.enum] p8:
10275 // Two enumeration types are layout-compatible if they have the same
10276 // underlying type.
10277 return ED1->isComplete() && ED2->isComplete() &&
10278 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
10279}
10280
10281/// \brief Check if two fields are layout-compatible.
10282bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
10283 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
10284 return false;
10285
10286 if (Field1->isBitField() != Field2->isBitField())
10287 return false;
10288
10289 if (Field1->isBitField()) {
10290 // Make sure that the bit-fields are the same length.
10291 unsigned Bits1 = Field1->getBitWidthValue(C);
10292 unsigned Bits2 = Field2->getBitWidthValue(C);
10293
10294 if (Bits1 != Bits2)
10295 return false;
10296 }
10297
10298 return true;
10299}
10300
10301/// \brief Check if two standard-layout structs are layout-compatible.
10302/// (C++11 [class.mem] p17)
10303bool isLayoutCompatibleStruct(ASTContext &C,
10304 RecordDecl *RD1,
10305 RecordDecl *RD2) {
10306 // If both records are C++ classes, check that base classes match.
10307 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
10308 // If one of records is a CXXRecordDecl we are in C++ mode,
10309 // thus the other one is a CXXRecordDecl, too.
10310 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
10311 // Check number of base classes.
10312 if (D1CXX->getNumBases() != D2CXX->getNumBases())
10313 return false;
10314
10315 // Check the base classes.
10316 for (CXXRecordDecl::base_class_const_iterator
10317 Base1 = D1CXX->bases_begin(),
10318 BaseEnd1 = D1CXX->bases_end(),
10319 Base2 = D2CXX->bases_begin();
10320 Base1 != BaseEnd1;
10321 ++Base1, ++Base2) {
10322 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
10323 return false;
10324 }
10325 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
10326 // If only RD2 is a C++ class, it should have zero base classes.
10327 if (D2CXX->getNumBases() > 0)
10328 return false;
10329 }
10330
10331 // Check the fields.
10332 RecordDecl::field_iterator Field2 = RD2->field_begin(),
10333 Field2End = RD2->field_end(),
10334 Field1 = RD1->field_begin(),
10335 Field1End = RD1->field_end();
10336 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
10337 if (!isLayoutCompatible(C, *Field1, *Field2))
10338 return false;
10339 }
10340 if (Field1 != Field1End || Field2 != Field2End)
10341 return false;
10342
10343 return true;
10344}
10345
10346/// \brief Check if two standard-layout unions are layout-compatible.
10347/// (C++11 [class.mem] p18)
10348bool isLayoutCompatibleUnion(ASTContext &C,
10349 RecordDecl *RD1,
10350 RecordDecl *RD2) {
10351 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010352 for (auto *Field2 : RD2->fields())
10353 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010354
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010355 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010356 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
10357 I = UnmatchedFields.begin(),
10358 E = UnmatchedFields.end();
10359
10360 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010361 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010362 bool Result = UnmatchedFields.erase(*I);
10363 (void) Result;
10364 assert(Result);
10365 break;
10366 }
10367 }
10368 if (I == E)
10369 return false;
10370 }
10371
10372 return UnmatchedFields.empty();
10373}
10374
10375bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
10376 if (RD1->isUnion() != RD2->isUnion())
10377 return false;
10378
10379 if (RD1->isUnion())
10380 return isLayoutCompatibleUnion(C, RD1, RD2);
10381 else
10382 return isLayoutCompatibleStruct(C, RD1, RD2);
10383}
10384
10385/// \brief Check if two types are layout-compatible in C++11 sense.
10386bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
10387 if (T1.isNull() || T2.isNull())
10388 return false;
10389
10390 // C++11 [basic.types] p11:
10391 // If two types T1 and T2 are the same type, then T1 and T2 are
10392 // layout-compatible types.
10393 if (C.hasSameType(T1, T2))
10394 return true;
10395
10396 T1 = T1.getCanonicalType().getUnqualifiedType();
10397 T2 = T2.getCanonicalType().getUnqualifiedType();
10398
10399 const Type::TypeClass TC1 = T1->getTypeClass();
10400 const Type::TypeClass TC2 = T2->getTypeClass();
10401
10402 if (TC1 != TC2)
10403 return false;
10404
10405 if (TC1 == Type::Enum) {
10406 return isLayoutCompatible(C,
10407 cast<EnumType>(T1)->getDecl(),
10408 cast<EnumType>(T2)->getDecl());
10409 } else if (TC1 == Type::Record) {
10410 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
10411 return false;
10412
10413 return isLayoutCompatible(C,
10414 cast<RecordType>(T1)->getDecl(),
10415 cast<RecordType>(T2)->getDecl());
10416 }
10417
10418 return false;
10419}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010420} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010421
10422//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
10423
10424namespace {
10425/// \brief Given a type tag expression find the type tag itself.
10426///
10427/// \param TypeExpr Type tag expression, as it appears in user's code.
10428///
10429/// \param VD Declaration of an identifier that appears in a type tag.
10430///
10431/// \param MagicValue Type tag magic value.
10432bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
10433 const ValueDecl **VD, uint64_t *MagicValue) {
10434 while(true) {
10435 if (!TypeExpr)
10436 return false;
10437
10438 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
10439
10440 switch (TypeExpr->getStmtClass()) {
10441 case Stmt::UnaryOperatorClass: {
10442 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
10443 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
10444 TypeExpr = UO->getSubExpr();
10445 continue;
10446 }
10447 return false;
10448 }
10449
10450 case Stmt::DeclRefExprClass: {
10451 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
10452 *VD = DRE->getDecl();
10453 return true;
10454 }
10455
10456 case Stmt::IntegerLiteralClass: {
10457 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
10458 llvm::APInt MagicValueAPInt = IL->getValue();
10459 if (MagicValueAPInt.getActiveBits() <= 64) {
10460 *MagicValue = MagicValueAPInt.getZExtValue();
10461 return true;
10462 } else
10463 return false;
10464 }
10465
10466 case Stmt::BinaryConditionalOperatorClass:
10467 case Stmt::ConditionalOperatorClass: {
10468 const AbstractConditionalOperator *ACO =
10469 cast<AbstractConditionalOperator>(TypeExpr);
10470 bool Result;
10471 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
10472 if (Result)
10473 TypeExpr = ACO->getTrueExpr();
10474 else
10475 TypeExpr = ACO->getFalseExpr();
10476 continue;
10477 }
10478 return false;
10479 }
10480
10481 case Stmt::BinaryOperatorClass: {
10482 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
10483 if (BO->getOpcode() == BO_Comma) {
10484 TypeExpr = BO->getRHS();
10485 continue;
10486 }
10487 return false;
10488 }
10489
10490 default:
10491 return false;
10492 }
10493 }
10494}
10495
10496/// \brief Retrieve the C type corresponding to type tag TypeExpr.
10497///
10498/// \param TypeExpr Expression that specifies a type tag.
10499///
10500/// \param MagicValues Registered magic values.
10501///
10502/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
10503/// kind.
10504///
10505/// \param TypeInfo Information about the corresponding C type.
10506///
10507/// \returns true if the corresponding C type was found.
10508bool GetMatchingCType(
10509 const IdentifierInfo *ArgumentKind,
10510 const Expr *TypeExpr, const ASTContext &Ctx,
10511 const llvm::DenseMap<Sema::TypeTagMagicValue,
10512 Sema::TypeTagData> *MagicValues,
10513 bool &FoundWrongKind,
10514 Sema::TypeTagData &TypeInfo) {
10515 FoundWrongKind = false;
10516
10517 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000010518 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010519
10520 uint64_t MagicValue;
10521
10522 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
10523 return false;
10524
10525 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000010526 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010527 if (I->getArgumentKind() != ArgumentKind) {
10528 FoundWrongKind = true;
10529 return false;
10530 }
10531 TypeInfo.Type = I->getMatchingCType();
10532 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
10533 TypeInfo.MustBeNull = I->getMustBeNull();
10534 return true;
10535 }
10536 return false;
10537 }
10538
10539 if (!MagicValues)
10540 return false;
10541
10542 llvm::DenseMap<Sema::TypeTagMagicValue,
10543 Sema::TypeTagData>::const_iterator I =
10544 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
10545 if (I == MagicValues->end())
10546 return false;
10547
10548 TypeInfo = I->second;
10549 return true;
10550}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010551} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010552
10553void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
10554 uint64_t MagicValue, QualType Type,
10555 bool LayoutCompatible,
10556 bool MustBeNull) {
10557 if (!TypeTagForDatatypeMagicValues)
10558 TypeTagForDatatypeMagicValues.reset(
10559 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
10560
10561 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
10562 (*TypeTagForDatatypeMagicValues)[Magic] =
10563 TypeTagData(Type, LayoutCompatible, MustBeNull);
10564}
10565
10566namespace {
10567bool IsSameCharType(QualType T1, QualType T2) {
10568 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
10569 if (!BT1)
10570 return false;
10571
10572 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
10573 if (!BT2)
10574 return false;
10575
10576 BuiltinType::Kind T1Kind = BT1->getKind();
10577 BuiltinType::Kind T2Kind = BT2->getKind();
10578
10579 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
10580 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
10581 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
10582 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
10583}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010584} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010585
10586void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
10587 const Expr * const *ExprArgs) {
10588 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
10589 bool IsPointerAttr = Attr->getIsPointer();
10590
10591 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
10592 bool FoundWrongKind;
10593 TypeTagData TypeInfo;
10594 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
10595 TypeTagForDatatypeMagicValues.get(),
10596 FoundWrongKind, TypeInfo)) {
10597 if (FoundWrongKind)
10598 Diag(TypeTagExpr->getExprLoc(),
10599 diag::warn_type_tag_for_datatype_wrong_kind)
10600 << TypeTagExpr->getSourceRange();
10601 return;
10602 }
10603
10604 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
10605 if (IsPointerAttr) {
10606 // Skip implicit cast of pointer to `void *' (as a function argument).
10607 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000010608 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000010609 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010610 ArgumentExpr = ICE->getSubExpr();
10611 }
10612 QualType ArgumentType = ArgumentExpr->getType();
10613
10614 // Passing a `void*' pointer shouldn't trigger a warning.
10615 if (IsPointerAttr && ArgumentType->isVoidPointerType())
10616 return;
10617
10618 if (TypeInfo.MustBeNull) {
10619 // Type tag with matching void type requires a null pointer.
10620 if (!ArgumentExpr->isNullPointerConstant(Context,
10621 Expr::NPC_ValueDependentIsNotNull)) {
10622 Diag(ArgumentExpr->getExprLoc(),
10623 diag::warn_type_safety_null_pointer_required)
10624 << ArgumentKind->getName()
10625 << ArgumentExpr->getSourceRange()
10626 << TypeTagExpr->getSourceRange();
10627 }
10628 return;
10629 }
10630
10631 QualType RequiredType = TypeInfo.Type;
10632 if (IsPointerAttr)
10633 RequiredType = Context.getPointerType(RequiredType);
10634
10635 bool mismatch = false;
10636 if (!TypeInfo.LayoutCompatible) {
10637 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
10638
10639 // C++11 [basic.fundamental] p1:
10640 // Plain char, signed char, and unsigned char are three distinct types.
10641 //
10642 // But we treat plain `char' as equivalent to `signed char' or `unsigned
10643 // char' depending on the current char signedness mode.
10644 if (mismatch)
10645 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
10646 RequiredType->getPointeeType())) ||
10647 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
10648 mismatch = false;
10649 } else
10650 if (IsPointerAttr)
10651 mismatch = !isLayoutCompatible(Context,
10652 ArgumentType->getPointeeType(),
10653 RequiredType->getPointeeType());
10654 else
10655 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
10656
10657 if (mismatch)
10658 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000010659 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010660 << TypeInfo.LayoutCompatible << RequiredType
10661 << ArgumentExpr->getSourceRange()
10662 << TypeTagExpr->getSourceRange();
10663}