blob: 31a20cb806a2b2360b3f5efb82aff9219634badc [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)
3139 // 2) binary, vector mask: (lhs, rhs, mask)
3140 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
3141 QualType resType = TheCall->getArg(0)->getType();
3142 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00003143
Douglas Gregorc25f7662009-05-19 22:10:17 +00003144 if (!TheCall->getArg(0)->isTypeDependent() &&
3145 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00003146 QualType LHSType = TheCall->getArg(0)->getType();
3147 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00003148
Craig Topperbaca3892013-07-29 06:47:04 +00003149 if (!LHSType->isVectorType() || !RHSType->isVectorType())
3150 return ExprError(Diag(TheCall->getLocStart(),
3151 diag::err_shufflevector_non_vector)
3152 << SourceRange(TheCall->getArg(0)->getLocStart(),
3153 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00003154
Nate Begemana0110022010-06-08 00:16:34 +00003155 numElements = LHSType->getAs<VectorType>()->getNumElements();
3156 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00003157
Nate Begemana0110022010-06-08 00:16:34 +00003158 // Check to see if we have a call with 2 vector arguments, the unary shuffle
3159 // with mask. If so, verify that RHS is an integer vector type with the
3160 // same number of elts as lhs.
3161 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00003162 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00003163 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00003164 return ExprError(Diag(TheCall->getLocStart(),
3165 diag::err_shufflevector_incompatible_vector)
3166 << SourceRange(TheCall->getArg(1)->getLocStart(),
3167 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00003168 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00003169 return ExprError(Diag(TheCall->getLocStart(),
3170 diag::err_shufflevector_incompatible_vector)
3171 << SourceRange(TheCall->getArg(0)->getLocStart(),
3172 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00003173 } else if (numElements != numResElements) {
3174 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00003175 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00003176 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00003177 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003178 }
3179
3180 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00003181 if (TheCall->getArg(i)->isTypeDependent() ||
3182 TheCall->getArg(i)->isValueDependent())
3183 continue;
3184
Nate Begemana0110022010-06-08 00:16:34 +00003185 llvm::APSInt Result(32);
3186 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
3187 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00003188 diag::err_shufflevector_nonconstant_argument)
3189 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003190
Craig Topper50ad5b72013-08-03 17:40:38 +00003191 // Allow -1 which will be translated to undef in the IR.
3192 if (Result.isSigned() && Result.isAllOnesValue())
3193 continue;
3194
Chris Lattner7ab824e2008-08-10 02:05:13 +00003195 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003196 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00003197 diag::err_shufflevector_argument_too_large)
3198 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003199 }
3200
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003201 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003202
Chris Lattner7ab824e2008-08-10 02:05:13 +00003203 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003204 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00003205 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003206 }
3207
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003208 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
3209 TheCall->getCallee()->getLocStart(),
3210 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003211}
Chris Lattner43be2e62007-12-19 23:59:04 +00003212
Hal Finkelc4d7c822013-09-18 03:29:45 +00003213/// SemaConvertVectorExpr - Handle __builtin_convertvector
3214ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
3215 SourceLocation BuiltinLoc,
3216 SourceLocation RParenLoc) {
3217 ExprValueKind VK = VK_RValue;
3218 ExprObjectKind OK = OK_Ordinary;
3219 QualType DstTy = TInfo->getType();
3220 QualType SrcTy = E->getType();
3221
3222 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
3223 return ExprError(Diag(BuiltinLoc,
3224 diag::err_convertvector_non_vector)
3225 << E->getSourceRange());
3226 if (!DstTy->isVectorType() && !DstTy->isDependentType())
3227 return ExprError(Diag(BuiltinLoc,
3228 diag::err_convertvector_non_vector_type));
3229
3230 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
3231 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
3232 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
3233 if (SrcElts != DstElts)
3234 return ExprError(Diag(BuiltinLoc,
3235 diag::err_convertvector_incompatible_vector)
3236 << E->getSourceRange());
3237 }
3238
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003239 return new (Context)
3240 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00003241}
3242
Daniel Dunbarb7257262008-07-21 22:59:13 +00003243/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
3244// This is declared to take (const void*, ...) and can take two
3245// optional constant int args.
3246bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00003247 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003248
Chris Lattner3b054132008-11-19 05:08:23 +00003249 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003250 return Diag(TheCall->getLocEnd(),
3251 diag::err_typecheck_call_too_many_args_at_most)
3252 << 0 /*function call*/ << 3 << NumArgs
3253 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003254
3255 // Argument 0 is checked for us and the remaining arguments must be
3256 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00003257 for (unsigned i = 1; i != NumArgs; ++i)
3258 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00003259 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003260
Warren Hunt20e4a5d2014-02-21 23:08:53 +00003261 return false;
3262}
3263
Hal Finkelf0417332014-07-17 14:25:55 +00003264/// SemaBuiltinAssume - Handle __assume (MS Extension).
3265// __assume does not evaluate its arguments, and should warn if its argument
3266// has side effects.
3267bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
3268 Expr *Arg = TheCall->getArg(0);
3269 if (Arg->isInstantiationDependent()) return false;
3270
3271 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00003272 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00003273 << Arg->getSourceRange()
3274 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
3275
3276 return false;
3277}
3278
3279/// Handle __builtin_assume_aligned. This is declared
3280/// as (const void*, size_t, ...) and can take one optional constant int arg.
3281bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
3282 unsigned NumArgs = TheCall->getNumArgs();
3283
3284 if (NumArgs > 3)
3285 return Diag(TheCall->getLocEnd(),
3286 diag::err_typecheck_call_too_many_args_at_most)
3287 << 0 /*function call*/ << 3 << NumArgs
3288 << TheCall->getSourceRange();
3289
3290 // The alignment must be a constant integer.
3291 Expr *Arg = TheCall->getArg(1);
3292
3293 // We can't check the value of a dependent argument.
3294 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
3295 llvm::APSInt Result;
3296 if (SemaBuiltinConstantArg(TheCall, 1, Result))
3297 return true;
3298
3299 if (!Result.isPowerOf2())
3300 return Diag(TheCall->getLocStart(),
3301 diag::err_alignment_not_power_of_two)
3302 << Arg->getSourceRange();
3303 }
3304
3305 if (NumArgs > 2) {
3306 ExprResult Arg(TheCall->getArg(2));
3307 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3308 Context.getSizeType(), false);
3309 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3310 if (Arg.isInvalid()) return true;
3311 TheCall->setArg(2, Arg.get());
3312 }
Hal Finkelf0417332014-07-17 14:25:55 +00003313
3314 return false;
3315}
3316
Eric Christopher8d0c6212010-04-17 02:26:23 +00003317/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
3318/// TheCall is a constant expression.
3319bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
3320 llvm::APSInt &Result) {
3321 Expr *Arg = TheCall->getArg(ArgNum);
3322 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3323 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3324
3325 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
3326
3327 if (!Arg->isIntegerConstantExpr(Result, Context))
3328 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00003329 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00003330
Chris Lattnerd545ad12009-09-23 06:06:36 +00003331 return false;
3332}
3333
Richard Sandiford28940af2014-04-16 08:47:51 +00003334/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
3335/// TheCall is a constant expression in the range [Low, High].
3336bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
3337 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00003338 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00003339
3340 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00003341 Expr *Arg = TheCall->getArg(ArgNum);
3342 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00003343 return false;
3344
Eric Christopher8d0c6212010-04-17 02:26:23 +00003345 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00003346 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00003347 return true;
3348
Richard Sandiford28940af2014-04-16 08:47:51 +00003349 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00003350 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00003351 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00003352
3353 return false;
3354}
3355
Luke Cheeseman59b2d832015-06-15 17:51:01 +00003356/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
3357/// TheCall is an ARM/AArch64 special register string literal.
3358bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
3359 int ArgNum, unsigned ExpectedFieldNum,
3360 bool AllowName) {
3361 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
3362 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
3363 BuiltinID == ARM::BI__builtin_arm_rsr ||
3364 BuiltinID == ARM::BI__builtin_arm_rsrp ||
3365 BuiltinID == ARM::BI__builtin_arm_wsr ||
3366 BuiltinID == ARM::BI__builtin_arm_wsrp;
3367 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
3368 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
3369 BuiltinID == AArch64::BI__builtin_arm_rsr ||
3370 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
3371 BuiltinID == AArch64::BI__builtin_arm_wsr ||
3372 BuiltinID == AArch64::BI__builtin_arm_wsrp;
3373 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
3374
3375 // We can't check the value of a dependent argument.
3376 Expr *Arg = TheCall->getArg(ArgNum);
3377 if (Arg->isTypeDependent() || Arg->isValueDependent())
3378 return false;
3379
3380 // Check if the argument is a string literal.
3381 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3382 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
3383 << Arg->getSourceRange();
3384
3385 // Check the type of special register given.
3386 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3387 SmallVector<StringRef, 6> Fields;
3388 Reg.split(Fields, ":");
3389
3390 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
3391 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
3392 << Arg->getSourceRange();
3393
3394 // If the string is the name of a register then we cannot check that it is
3395 // valid here but if the string is of one the forms described in ACLE then we
3396 // can check that the supplied fields are integers and within the valid
3397 // ranges.
3398 if (Fields.size() > 1) {
3399 bool FiveFields = Fields.size() == 5;
3400
3401 bool ValidString = true;
3402 if (IsARMBuiltin) {
3403 ValidString &= Fields[0].startswith_lower("cp") ||
3404 Fields[0].startswith_lower("p");
3405 if (ValidString)
3406 Fields[0] =
3407 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
3408
3409 ValidString &= Fields[2].startswith_lower("c");
3410 if (ValidString)
3411 Fields[2] = Fields[2].drop_front(1);
3412
3413 if (FiveFields) {
3414 ValidString &= Fields[3].startswith_lower("c");
3415 if (ValidString)
3416 Fields[3] = Fields[3].drop_front(1);
3417 }
3418 }
3419
3420 SmallVector<int, 5> Ranges;
3421 if (FiveFields)
3422 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15});
3423 else
3424 Ranges.append({15, 7, 15});
3425
3426 for (unsigned i=0; i<Fields.size(); ++i) {
3427 int IntField;
3428 ValidString &= !Fields[i].getAsInteger(10, IntField);
3429 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
3430 }
3431
3432 if (!ValidString)
3433 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
3434 << Arg->getSourceRange();
3435
3436 } else if (IsAArch64Builtin && Fields.size() == 1) {
3437 // If the register name is one of those that appear in the condition below
3438 // and the special register builtin being used is one of the write builtins,
3439 // then we require that the argument provided for writing to the register
3440 // is an integer constant expression. This is because it will be lowered to
3441 // an MSR (immediate) instruction, so we need to know the immediate at
3442 // compile time.
3443 if (TheCall->getNumArgs() != 2)
3444 return false;
3445
3446 std::string RegLower = Reg.lower();
3447 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
3448 RegLower != "pan" && RegLower != "uao")
3449 return false;
3450
3451 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
3452 }
3453
3454 return false;
3455}
3456
Eli Friedmanc97d0142009-05-03 06:04:26 +00003457/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003458/// This checks that the target supports __builtin_longjmp and
3459/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003460bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003461 if (!Context.getTargetInfo().hasSjLjLowering())
3462 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
3463 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
3464
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003465 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00003466 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00003467
Eric Christopher8d0c6212010-04-17 02:26:23 +00003468 // TODO: This is less than ideal. Overload this to take a value.
3469 if (SemaBuiltinConstantArg(TheCall, 1, Result))
3470 return true;
3471
3472 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003473 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
3474 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
3475
3476 return false;
3477}
3478
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003479/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
3480/// This checks that the target supports __builtin_setjmp.
3481bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
3482 if (!Context.getTargetInfo().hasSjLjLowering())
3483 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
3484 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
3485 return false;
3486}
3487
Richard Smithd7293d72013-08-05 18:49:43 +00003488namespace {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003489class UncoveredArgHandler {
3490 enum { Unknown = -1, AllCovered = -2 };
3491 signed FirstUncoveredArg;
3492 SmallVector<const Expr *, 4> DiagnosticExprs;
3493
3494public:
3495 UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
3496
3497 bool hasUncoveredArg() const {
3498 return (FirstUncoveredArg >= 0);
3499 }
3500
3501 unsigned getUncoveredArg() const {
3502 assert(hasUncoveredArg() && "no uncovered argument");
3503 return FirstUncoveredArg;
3504 }
3505
3506 void setAllCovered() {
3507 // A string has been found with all arguments covered, so clear out
3508 // the diagnostics.
3509 DiagnosticExprs.clear();
3510 FirstUncoveredArg = AllCovered;
3511 }
3512
3513 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
3514 assert(NewFirstUncoveredArg >= 0 && "Outside range");
3515
3516 // Don't update if a previous string covers all arguments.
3517 if (FirstUncoveredArg == AllCovered)
3518 return;
3519
3520 // UncoveredArgHandler tracks the highest uncovered argument index
3521 // and with it all the strings that match this index.
3522 if (NewFirstUncoveredArg == FirstUncoveredArg)
3523 DiagnosticExprs.push_back(StrExpr);
3524 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
3525 DiagnosticExprs.clear();
3526 DiagnosticExprs.push_back(StrExpr);
3527 FirstUncoveredArg = NewFirstUncoveredArg;
3528 }
3529 }
3530
3531 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
3532};
3533
Richard Smithd7293d72013-08-05 18:49:43 +00003534enum StringLiteralCheckType {
3535 SLCT_NotALiteral,
3536 SLCT_UncheckedLiteral,
3537 SLCT_CheckedLiteral
3538};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003539} // end anonymous namespace
Richard Smithd7293d72013-08-05 18:49:43 +00003540
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00003541static void CheckFormatString(Sema &S, const StringLiteral *FExpr,
3542 const Expr *OrigFormatExpr,
3543 ArrayRef<const Expr *> Args,
3544 bool HasVAListArg, unsigned format_idx,
3545 unsigned firstDataArg,
3546 Sema::FormatStringType Type,
3547 bool inFunctionCall,
3548 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003549 llvm::SmallBitVector &CheckedVarArgs,
3550 UncoveredArgHandler &UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00003551
Richard Smith55ce3522012-06-25 20:30:08 +00003552// Determine if an expression is a string literal or constant string.
3553// If this function returns false on the arguments to a function expecting a
3554// format string, we will usually need to emit a warning.
3555// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00003556static StringLiteralCheckType
3557checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
3558 bool HasVAListArg, unsigned format_idx,
3559 unsigned firstDataArg, Sema::FormatStringType Type,
3560 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003561 llvm::SmallBitVector &CheckedVarArgs,
3562 UncoveredArgHandler &UncoveredArg) {
Ted Kremenek808829352010-09-09 03:51:39 +00003563 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00003564 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00003565 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003566
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003567 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00003568
Richard Smithd7293d72013-08-05 18:49:43 +00003569 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00003570 // Technically -Wformat-nonliteral does not warn about this case.
3571 // The behavior of printf and friends in this case is implementation
3572 // dependent. Ideally if the format string cannot be null then
3573 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00003574 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00003575
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003576 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00003577 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003578 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00003579 // The expression is a literal if both sub-expressions were, and it was
3580 // completely checked only if both sub-expressions were checked.
3581 const AbstractConditionalOperator *C =
3582 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003583
3584 // Determine whether it is necessary to check both sub-expressions, for
3585 // example, because the condition expression is a constant that can be
3586 // evaluated at compile time.
3587 bool CheckLeft = true, CheckRight = true;
3588
3589 bool Cond;
3590 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
3591 if (Cond)
3592 CheckRight = false;
3593 else
3594 CheckLeft = false;
3595 }
3596
3597 StringLiteralCheckType Left;
3598 if (!CheckLeft)
3599 Left = SLCT_UncheckedLiteral;
3600 else {
3601 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
3602 HasVAListArg, format_idx, firstDataArg,
3603 Type, CallType, InFunctionCall,
3604 CheckedVarArgs, UncoveredArg);
3605 if (Left == SLCT_NotALiteral || !CheckRight)
3606 return Left;
3607 }
3608
Richard Smith55ce3522012-06-25 20:30:08 +00003609 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00003610 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003611 HasVAListArg, format_idx, firstDataArg,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003612 Type, CallType, InFunctionCall, CheckedVarArgs,
3613 UncoveredArg);
3614
3615 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003616 }
3617
3618 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00003619 E = cast<ImplicitCastExpr>(E)->getSubExpr();
3620 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003621 }
3622
John McCallc07a0c72011-02-17 10:25:35 +00003623 case Stmt::OpaqueValueExprClass:
3624 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
3625 E = src;
3626 goto tryAgain;
3627 }
Richard Smith55ce3522012-06-25 20:30:08 +00003628 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00003629
Ted Kremeneka8890832011-02-24 23:03:04 +00003630 case Stmt::PredefinedExprClass:
3631 // While __func__, etc., are technically not string literals, they
3632 // cannot contain format specifiers and thus are not a security
3633 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00003634 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00003635
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003636 case Stmt::DeclRefExprClass: {
3637 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00003638
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003639 // As an exception, do not flag errors for variables binding to
3640 // const string literals.
3641 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
3642 bool isConstant = false;
3643 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003644
Richard Smithd7293d72013-08-05 18:49:43 +00003645 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
3646 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00003647 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00003648 isConstant = T.isConstant(S.Context) &&
3649 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00003650 } else if (T->isObjCObjectPointerType()) {
3651 // In ObjC, there is usually no "const ObjectPointer" type,
3652 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00003653 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003654 }
Mike Stump11289f42009-09-09 15:08:12 +00003655
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003656 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00003657 if (const Expr *Init = VD->getAnyInitializer()) {
3658 // Look through initializers like const char c[] = { "foo" }
3659 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3660 if (InitList->isStringLiteralInit())
3661 Init = InitList->getInit(0)->IgnoreParenImpCasts();
3662 }
Richard Smithd7293d72013-08-05 18:49:43 +00003663 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003664 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003665 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003666 /*InFunctionCall*/false, CheckedVarArgs,
3667 UncoveredArg);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00003668 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003669 }
Mike Stump11289f42009-09-09 15:08:12 +00003670
Anders Carlssonb012ca92009-06-28 19:55:58 +00003671 // For vprintf* functions (i.e., HasVAListArg==true), we add a
3672 // special check to see if the format string is a function parameter
3673 // of the function calling the printf function. If the function
3674 // has an attribute indicating it is a printf-like function, then we
3675 // should suppress warnings concerning non-literals being used in a call
3676 // to a vprintf function. For example:
3677 //
3678 // void
3679 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
3680 // va_list ap;
3681 // va_start(ap, fmt);
3682 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
3683 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00003684 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003685 if (HasVAListArg) {
3686 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
3687 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
3688 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003689 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003690 // adjust for implicit parameter
3691 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
3692 if (MD->isInstance())
3693 ++PVIndex;
3694 // We also check if the formats are compatible.
3695 // We can't pass a 'scanf' string to a 'printf' function.
3696 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00003697 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00003698 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003699 }
3700 }
3701 }
3702 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003703 }
Mike Stump11289f42009-09-09 15:08:12 +00003704
Richard Smith55ce3522012-06-25 20:30:08 +00003705 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003706 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003707
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00003708 case Stmt::CallExprClass:
3709 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003710 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00003711 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
3712 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
3713 unsigned ArgIndex = FA->getFormatIdx();
3714 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
3715 if (MD->isInstance())
3716 --ArgIndex;
3717 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00003718
Richard Smithd7293d72013-08-05 18:49:43 +00003719 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003720 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00003721 Type, CallType, InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003722 CheckedVarArgs, UncoveredArg);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003723 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3724 unsigned BuiltinID = FD->getBuiltinID();
3725 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
3726 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
3727 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00003728 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003729 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003730 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003731 InFunctionCall, CheckedVarArgs,
3732 UncoveredArg);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003733 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003734 }
3735 }
Mike Stump11289f42009-09-09 15:08:12 +00003736
Richard Smith55ce3522012-06-25 20:30:08 +00003737 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003738 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003739 case Stmt::ObjCStringLiteralClass:
3740 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00003741 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003742
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003743 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003744 StrE = ObjCFExpr->getString();
3745 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003746 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00003747
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003748 if (StrE) {
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00003749 CheckFormatString(S, StrE, E, Args, HasVAListArg, format_idx,
3750 firstDataArg, Type, InFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003751 CheckedVarArgs, UncoveredArg);
Richard Smith55ce3522012-06-25 20:30:08 +00003752 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003753 }
Mike Stump11289f42009-09-09 15:08:12 +00003754
Richard Smith55ce3522012-06-25 20:30:08 +00003755 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003756 }
Mike Stump11289f42009-09-09 15:08:12 +00003757
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003758 default:
Richard Smith55ce3522012-06-25 20:30:08 +00003759 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003760 }
3761}
3762
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003763Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00003764 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003765 .Case("scanf", FST_Scanf)
3766 .Cases("printf", "printf0", FST_Printf)
3767 .Cases("NSString", "CFString", FST_NSString)
3768 .Case("strftime", FST_Strftime)
3769 .Case("strfmon", FST_Strfmon)
3770 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
Dimitry Andric6b5ed342015-02-19 22:32:33 +00003771 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00003772 .Case("os_trace", FST_OSTrace)
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003773 .Default(FST_Unknown);
3774}
3775
Jordan Rose3e0ec582012-07-19 18:10:23 +00003776/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00003777/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00003778/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003779bool Sema::CheckFormatArguments(const FormatAttr *Format,
3780 ArrayRef<const Expr *> Args,
3781 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003782 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003783 SourceLocation Loc, SourceRange Range,
3784 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00003785 FormatStringInfo FSI;
3786 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003787 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00003788 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00003789 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003790 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003791}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00003792
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003793bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003794 bool HasVAListArg, unsigned format_idx,
3795 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003796 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003797 SourceLocation Loc, SourceRange Range,
3798 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00003799 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003800 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003801 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00003802 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003803 }
Mike Stump11289f42009-09-09 15:08:12 +00003804
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003805 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00003806
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003807 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00003808 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003809 // Dynamically generated format strings are difficult to
3810 // automatically vet at compile time. Requiring that format strings
3811 // are string literals: (1) permits the checking of format strings by
3812 // the compiler and thereby (2) can practically remove the source of
3813 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00003814
Mike Stump11289f42009-09-09 15:08:12 +00003815 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00003816 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00003817 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00003818 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003819 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00003820 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00003821 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
3822 format_idx, firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003823 /*IsFunctionCall*/true, CheckedVarArgs,
3824 UncoveredArg);
3825
3826 // Generate a diagnostic where an uncovered argument is detected.
3827 if (UncoveredArg.hasUncoveredArg()) {
3828 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
3829 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
3830 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
3831 }
3832
Richard Smith55ce3522012-06-25 20:30:08 +00003833 if (CT != SLCT_NotALiteral)
3834 // Literal format string found, check done!
3835 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00003836
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00003837 // Strftime is particular as it always uses a single 'time' argument,
3838 // so it is safe to pass a non-literal string.
3839 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00003840 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00003841
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00003842 // Do not emit diag when the string param is a macro expansion and the
3843 // format is either NSString or CFString. This is a hack to prevent
3844 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
3845 // which are usually used in place of NS and CF string literals.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00003846 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
3847 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
Richard Smith55ce3522012-06-25 20:30:08 +00003848 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00003849
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003850 // If there are no arguments specified, warn with -Wformat-security, otherwise
3851 // warn only with -Wformat-nonliteral.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00003852 if (Args.size() == firstDataArg) {
Bob Wilson57819fc2016-03-15 20:56:38 +00003853 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
3854 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00003855 switch (Type) {
3856 default:
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00003857 break;
3858 case FST_Kprintf:
3859 case FST_FreeBSDKPrintf:
3860 case FST_Printf:
Bob Wilson57819fc2016-03-15 20:56:38 +00003861 Diag(FormatLoc, diag::note_format_security_fixit)
3862 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00003863 break;
3864 case FST_NSString:
Bob Wilson57819fc2016-03-15 20:56:38 +00003865 Diag(FormatLoc, diag::note_format_security_fixit)
3866 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00003867 break;
3868 }
3869 } else {
3870 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003871 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00003872 }
Richard Smith55ce3522012-06-25 20:30:08 +00003873 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003874}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003875
Ted Kremenekab278de2010-01-28 23:39:18 +00003876namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00003877class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
3878protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00003879 Sema &S;
3880 const StringLiteral *FExpr;
3881 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00003882 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00003883 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00003884 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00003885 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003886 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00003887 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00003888 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00003889 bool usesPositionalArgs;
3890 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00003891 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00003892 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00003893 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003894 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003895
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003896public:
Ted Kremenek02087932010-07-16 02:11:22 +00003897 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00003898 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003899 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003900 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003901 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003902 Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003903 llvm::SmallBitVector &CheckedVarArgs,
3904 UncoveredArgHandler &UncoveredArg)
Ted Kremenekab278de2010-01-28 23:39:18 +00003905 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003906 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
3907 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003908 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00003909 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00003910 inFunctionCall(inFunctionCall), CallType(callType),
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003911 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00003912 CoveredArgs.resize(numDataArgs);
3913 CoveredArgs.reset();
3914 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003915
Ted Kremenek019d2242010-01-29 01:50:07 +00003916 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003917
Ted Kremenek02087932010-07-16 02:11:22 +00003918 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003919 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003920
Jordan Rose92303592012-09-08 04:00:03 +00003921 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003922 const analyze_format_string::FormatSpecifier &FS,
3923 const analyze_format_string::ConversionSpecifier &CS,
3924 const char *startSpecifier, unsigned specifierLen,
3925 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00003926
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003927 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003928 const analyze_format_string::FormatSpecifier &FS,
3929 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003930
3931 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003932 const analyze_format_string::ConversionSpecifier &CS,
3933 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003934
Craig Toppere14c0f82014-03-12 04:55:44 +00003935 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00003936
Craig Toppere14c0f82014-03-12 04:55:44 +00003937 void HandleInvalidPosition(const char *startSpecifier,
3938 unsigned specifierLen,
3939 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00003940
Craig Toppere14c0f82014-03-12 04:55:44 +00003941 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00003942
Craig Toppere14c0f82014-03-12 04:55:44 +00003943 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003944
Richard Trieu03cf7b72011-10-28 00:41:25 +00003945 template <typename Range>
3946 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
3947 const Expr *ArgumentExpr,
3948 PartialDiagnostic PDiag,
3949 SourceLocation StringLoc,
3950 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00003951 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003952
Ted Kremenek02087932010-07-16 02:11:22 +00003953protected:
Ted Kremenekce815422010-07-19 21:25:57 +00003954 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
3955 const char *startSpec,
3956 unsigned specifierLen,
3957 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003958
3959 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
3960 const char *startSpec,
3961 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00003962
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003963 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00003964 CharSourceRange getSpecifierRange(const char *startSpecifier,
3965 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00003966 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003967
Ted Kremenek5739de72010-01-29 01:06:55 +00003968 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003969
3970 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
3971 const analyze_format_string::ConversionSpecifier &CS,
3972 const char *startSpecifier, unsigned specifierLen,
3973 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003974
3975 template <typename Range>
3976 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
3977 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00003978 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00003979};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003980} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00003981
Ted Kremenek02087932010-07-16 02:11:22 +00003982SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00003983 return OrigFormatExpr->getSourceRange();
3984}
3985
Ted Kremenek02087932010-07-16 02:11:22 +00003986CharSourceRange CheckFormatHandler::
3987getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00003988 SourceLocation Start = getLocationOfByte(startSpecifier);
3989 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
3990
3991 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003992 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00003993
3994 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003995}
3996
Ted Kremenek02087932010-07-16 02:11:22 +00003997SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003998 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00003999}
4000
Ted Kremenek02087932010-07-16 02:11:22 +00004001void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
4002 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00004003 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
4004 getLocationOfByte(startSpecifier),
4005 /*IsStringLocation*/true,
4006 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00004007}
4008
Jordan Rose92303592012-09-08 04:00:03 +00004009void CheckFormatHandler::HandleInvalidLengthModifier(
4010 const analyze_format_string::FormatSpecifier &FS,
4011 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00004012 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00004013 using namespace analyze_format_string;
4014
4015 const LengthModifier &LM = FS.getLengthModifier();
4016 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4017
4018 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00004019 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00004020 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004021 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00004022 getLocationOfByte(LM.getStart()),
4023 /*IsStringLocation*/true,
4024 getSpecifierRange(startSpecifier, specifierLen));
4025
4026 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4027 << FixedLM->toString()
4028 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
4029
4030 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004031 FixItHint Hint;
4032 if (DiagID == diag::warn_format_nonsensical_length)
4033 Hint = FixItHint::CreateRemoval(LMRange);
4034
4035 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00004036 getLocationOfByte(LM.getStart()),
4037 /*IsStringLocation*/true,
4038 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00004039 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00004040 }
4041}
4042
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004043void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00004044 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004045 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004046 using namespace analyze_format_string;
4047
4048 const LengthModifier &LM = FS.getLengthModifier();
4049 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4050
4051 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00004052 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00004053 if (FixedLM) {
4054 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4055 << LM.toString() << 0,
4056 getLocationOfByte(LM.getStart()),
4057 /*IsStringLocation*/true,
4058 getSpecifierRange(startSpecifier, specifierLen));
4059
4060 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4061 << FixedLM->toString()
4062 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
4063
4064 } else {
4065 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4066 << LM.toString() << 0,
4067 getLocationOfByte(LM.getStart()),
4068 /*IsStringLocation*/true,
4069 getSpecifierRange(startSpecifier, specifierLen));
4070 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004071}
4072
4073void CheckFormatHandler::HandleNonStandardConversionSpecifier(
4074 const analyze_format_string::ConversionSpecifier &CS,
4075 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00004076 using namespace analyze_format_string;
4077
4078 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00004079 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00004080 if (FixedCS) {
4081 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4082 << CS.toString() << /*conversion specifier*/1,
4083 getLocationOfByte(CS.getStart()),
4084 /*IsStringLocation*/true,
4085 getSpecifierRange(startSpecifier, specifierLen));
4086
4087 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
4088 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
4089 << FixedCS->toString()
4090 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
4091 } else {
4092 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4093 << CS.toString() << /*conversion specifier*/1,
4094 getLocationOfByte(CS.getStart()),
4095 /*IsStringLocation*/true,
4096 getSpecifierRange(startSpecifier, specifierLen));
4097 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004098}
4099
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00004100void CheckFormatHandler::HandlePosition(const char *startPos,
4101 unsigned posLen) {
4102 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
4103 getLocationOfByte(startPos),
4104 /*IsStringLocation*/true,
4105 getSpecifierRange(startPos, posLen));
4106}
4107
Ted Kremenekd1668192010-02-27 01:41:03 +00004108void
Ted Kremenek02087932010-07-16 02:11:22 +00004109CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
4110 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004111 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
4112 << (unsigned) p,
4113 getLocationOfByte(startPos), /*IsStringLocation*/true,
4114 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00004115}
4116
Ted Kremenek02087932010-07-16 02:11:22 +00004117void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00004118 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004119 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
4120 getLocationOfByte(startPos),
4121 /*IsStringLocation*/true,
4122 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00004123}
4124
Ted Kremenek02087932010-07-16 02:11:22 +00004125void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004126 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00004127 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00004128 EmitFormatDiagnostic(
4129 S.PDiag(diag::warn_printf_format_string_contains_null_char),
4130 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
4131 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00004132 }
Ted Kremenek02087932010-07-16 02:11:22 +00004133}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004134
Jordan Rose58bbe422012-07-19 18:10:08 +00004135// Note that this may return NULL if there was an error parsing or building
4136// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00004137const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004138 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00004139}
4140
4141void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004142 // Does the number of data arguments exceed the number of
4143 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00004144 if (!HasVAListArg) {
4145 // Find any arguments that weren't covered.
4146 CoveredArgs.flip();
4147 signed notCoveredArg = CoveredArgs.find_first();
4148 if (notCoveredArg >= 0) {
4149 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004150 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
4151 } else {
4152 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00004153 }
4154 }
4155}
4156
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004157void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
4158 const Expr *ArgExpr) {
4159 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
4160 "Invalid state");
4161
4162 if (!ArgExpr)
4163 return;
4164
4165 SourceLocation Loc = ArgExpr->getLocStart();
4166
4167 if (S.getSourceManager().isInSystemMacro(Loc))
4168 return;
4169
4170 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
4171 for (auto E : DiagnosticExprs)
4172 PDiag << E->getSourceRange();
4173
4174 CheckFormatHandler::EmitFormatDiagnostic(
4175 S, IsFunctionCall, DiagnosticExprs[0],
4176 PDiag, Loc, /*IsStringLocation*/false,
4177 DiagnosticExprs[0]->getSourceRange());
4178}
4179
Ted Kremenekce815422010-07-19 21:25:57 +00004180bool
4181CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
4182 SourceLocation Loc,
4183 const char *startSpec,
4184 unsigned specifierLen,
4185 const char *csStart,
4186 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00004187 bool keepGoing = true;
4188 if (argIndex < NumDataArgs) {
4189 // Consider the argument coverered, even though the specifier doesn't
4190 // make sense.
4191 CoveredArgs.set(argIndex);
4192 }
4193 else {
4194 // If argIndex exceeds the number of data arguments we
4195 // don't issue a warning because that is just a cascade of warnings (and
4196 // they may have intended '%%' anyway). We don't want to continue processing
4197 // the format string after this point, however, as we will like just get
4198 // gibberish when trying to match arguments.
4199 keepGoing = false;
4200 }
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00004201
4202 StringRef Specifier(csStart, csLen);
4203
4204 // If the specifier in non-printable, it could be the first byte of a UTF-8
4205 // sequence. In that case, print the UTF-8 code point. If not, print the byte
4206 // hex value.
4207 std::string CodePointStr;
4208 if (!llvm::sys::locale::isPrint(*csStart)) {
4209 UTF32 CodePoint;
4210 const UTF8 **B = reinterpret_cast<const UTF8 **>(&csStart);
4211 const UTF8 *E =
4212 reinterpret_cast<const UTF8 *>(csStart + csLen);
4213 ConversionResult Result =
4214 llvm::convertUTF8Sequence(B, E, &CodePoint, strictConversion);
4215
4216 if (Result != conversionOK) {
4217 unsigned char FirstChar = *csStart;
4218 CodePoint = (UTF32)FirstChar;
4219 }
4220
4221 llvm::raw_string_ostream OS(CodePointStr);
4222 if (CodePoint < 256)
4223 OS << "\\x" << llvm::format("%02x", CodePoint);
4224 else if (CodePoint <= 0xFFFF)
4225 OS << "\\u" << llvm::format("%04x", CodePoint);
4226 else
4227 OS << "\\U" << llvm::format("%08x", CodePoint);
4228 OS.flush();
4229 Specifier = CodePointStr;
4230 }
4231
4232 EmitFormatDiagnostic(
4233 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
4234 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
4235
Ted Kremenekce815422010-07-19 21:25:57 +00004236 return keepGoing;
4237}
4238
Richard Trieu03cf7b72011-10-28 00:41:25 +00004239void
4240CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
4241 const char *startSpec,
4242 unsigned specifierLen) {
4243 EmitFormatDiagnostic(
4244 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
4245 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
4246}
4247
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004248bool
4249CheckFormatHandler::CheckNumArgs(
4250 const analyze_format_string::FormatSpecifier &FS,
4251 const analyze_format_string::ConversionSpecifier &CS,
4252 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
4253
4254 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004255 PartialDiagnostic PDiag = FS.usesPositionalArg()
4256 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
4257 << (argIndex+1) << NumDataArgs)
4258 : S.PDiag(diag::warn_printf_insufficient_data_args);
4259 EmitFormatDiagnostic(
4260 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
4261 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004262
4263 // Since more arguments than conversion tokens are given, by extension
4264 // all arguments are covered, so mark this as so.
4265 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004266 return false;
4267 }
4268 return true;
4269}
4270
Richard Trieu03cf7b72011-10-28 00:41:25 +00004271template<typename Range>
4272void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
4273 SourceLocation Loc,
4274 bool IsStringLocation,
4275 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00004276 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004277 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00004278 Loc, IsStringLocation, StringRange, FixIt);
4279}
4280
4281/// \brief If the format string is not within the funcion call, emit a note
4282/// so that the function call and string are in diagnostic messages.
4283///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00004284/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00004285/// call and only one diagnostic message will be produced. Otherwise, an
4286/// extra note will be emitted pointing to location of the format string.
4287///
4288/// \param ArgumentExpr the expression that is passed as the format string
4289/// argument in the function call. Used for getting locations when two
4290/// diagnostics are emitted.
4291///
4292/// \param PDiag the callee should already have provided any strings for the
4293/// diagnostic message. This function only adds locations and fixits
4294/// to diagnostics.
4295///
4296/// \param Loc primary location for diagnostic. If two diagnostics are
4297/// required, one will be at Loc and a new SourceLocation will be created for
4298/// the other one.
4299///
4300/// \param IsStringLocation if true, Loc points to the format string should be
4301/// used for the note. Otherwise, Loc points to the argument list and will
4302/// be used with PDiag.
4303///
4304/// \param StringRange some or all of the string to highlight. This is
4305/// templated so it can accept either a CharSourceRange or a SourceRange.
4306///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00004307/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00004308template<typename Range>
4309void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
4310 const Expr *ArgumentExpr,
4311 PartialDiagnostic PDiag,
4312 SourceLocation Loc,
4313 bool IsStringLocation,
4314 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00004315 ArrayRef<FixItHint> FixIt) {
4316 if (InFunctionCall) {
4317 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
4318 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00004319 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00004320 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004321 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
4322 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00004323
4324 const Sema::SemaDiagnosticBuilder &Note =
4325 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
4326 diag::note_format_string_defined);
4327
4328 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00004329 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00004330 }
4331}
4332
Ted Kremenek02087932010-07-16 02:11:22 +00004333//===--- CHECK: Printf format string checking ------------------------------===//
4334
4335namespace {
4336class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004337 bool ObjCContext;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004338
Ted Kremenek02087932010-07-16 02:11:22 +00004339public:
4340 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
4341 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004342 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00004343 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004344 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004345 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00004346 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004347 llvm::SmallBitVector &CheckedVarArgs,
4348 UncoveredArgHandler &UncoveredArg)
Richard Smithd7293d72013-08-05 18:49:43 +00004349 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
4350 numDataArgs, beg, hasVAListArg, Args,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004351 formatIdx, inFunctionCall, CallType, CheckedVarArgs,
4352 UncoveredArg),
Richard Smithd7293d72013-08-05 18:49:43 +00004353 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00004354 {}
4355
Ted Kremenek02087932010-07-16 02:11:22 +00004356 bool HandleInvalidPrintfConversionSpecifier(
4357 const analyze_printf::PrintfSpecifier &FS,
4358 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004359 unsigned specifierLen) override;
4360
Ted Kremenek02087932010-07-16 02:11:22 +00004361 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
4362 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004363 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00004364 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
4365 const char *StartSpecifier,
4366 unsigned SpecifierLen,
4367 const Expr *E);
4368
Ted Kremenek02087932010-07-16 02:11:22 +00004369 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
4370 const char *startSpecifier, unsigned specifierLen);
4371 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
4372 const analyze_printf::OptionalAmount &Amt,
4373 unsigned type,
4374 const char *startSpecifier, unsigned specifierLen);
4375 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
4376 const analyze_printf::OptionalFlag &flag,
4377 const char *startSpecifier, unsigned specifierLen);
4378 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
4379 const analyze_printf::OptionalFlag &ignoredFlag,
4380 const analyze_printf::OptionalFlag &flag,
4381 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004382 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00004383 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00004384
4385 void HandleEmptyObjCModifierFlag(const char *startFlag,
4386 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00004387
Ted Kremenek2b417712015-07-02 05:39:16 +00004388 void HandleInvalidObjCModifierFlag(const char *startFlag,
4389 unsigned flagLen) override;
4390
4391 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
4392 const char *flagsEnd,
4393 const char *conversionPosition)
4394 override;
4395};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004396} // end anonymous namespace
Ted Kremenek02087932010-07-16 02:11:22 +00004397
4398bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
4399 const analyze_printf::PrintfSpecifier &FS,
4400 const char *startSpecifier,
4401 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004402 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00004403 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00004404
Ted Kremenekce815422010-07-19 21:25:57 +00004405 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
4406 getLocationOfByte(CS.getStart()),
4407 startSpecifier, specifierLen,
4408 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00004409}
4410
Ted Kremenek02087932010-07-16 02:11:22 +00004411bool CheckPrintfHandler::HandleAmount(
4412 const analyze_format_string::OptionalAmount &Amt,
4413 unsigned k, const char *startSpecifier,
4414 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004415 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004416 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00004417 unsigned argIndex = Amt.getArgIndex();
4418 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004419 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
4420 << k,
4421 getLocationOfByte(Amt.getStart()),
4422 /*IsStringLocation*/true,
4423 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00004424 // Don't do any more checking. We will just emit
4425 // spurious errors.
4426 return false;
4427 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004428
Ted Kremenek5739de72010-01-29 01:06:55 +00004429 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00004430 // Although not in conformance with C99, we also allow the argument to be
4431 // an 'unsigned int' as that is a reasonably safe case. GCC also
4432 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00004433 CoveredArgs.set(argIndex);
4434 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00004435 if (!Arg)
4436 return false;
4437
Ted Kremenek5739de72010-01-29 01:06:55 +00004438 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004439
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004440 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
4441 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004442
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004443 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004444 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004445 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00004446 << T << Arg->getSourceRange(),
4447 getLocationOfByte(Amt.getStart()),
4448 /*IsStringLocation*/true,
4449 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00004450 // Don't do any more checking. We will just emit
4451 // spurious errors.
4452 return false;
4453 }
4454 }
4455 }
4456 return true;
4457}
Ted Kremenek5739de72010-01-29 01:06:55 +00004458
Tom Careb49ec692010-06-17 19:00:27 +00004459void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00004460 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004461 const analyze_printf::OptionalAmount &Amt,
4462 unsigned type,
4463 const char *startSpecifier,
4464 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004465 const analyze_printf::PrintfConversionSpecifier &CS =
4466 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00004467
Richard Trieu03cf7b72011-10-28 00:41:25 +00004468 FixItHint fixit =
4469 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
4470 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
4471 Amt.getConstantLength()))
4472 : FixItHint();
4473
4474 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
4475 << type << CS.toString(),
4476 getLocationOfByte(Amt.getStart()),
4477 /*IsStringLocation*/true,
4478 getSpecifierRange(startSpecifier, specifierLen),
4479 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00004480}
4481
Ted Kremenek02087932010-07-16 02:11:22 +00004482void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004483 const analyze_printf::OptionalFlag &flag,
4484 const char *startSpecifier,
4485 unsigned specifierLen) {
4486 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004487 const analyze_printf::PrintfConversionSpecifier &CS =
4488 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00004489 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
4490 << flag.toString() << CS.toString(),
4491 getLocationOfByte(flag.getPosition()),
4492 /*IsStringLocation*/true,
4493 getSpecifierRange(startSpecifier, specifierLen),
4494 FixItHint::CreateRemoval(
4495 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00004496}
4497
4498void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00004499 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004500 const analyze_printf::OptionalFlag &ignoredFlag,
4501 const analyze_printf::OptionalFlag &flag,
4502 const char *startSpecifier,
4503 unsigned specifierLen) {
4504 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00004505 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
4506 << ignoredFlag.toString() << flag.toString(),
4507 getLocationOfByte(ignoredFlag.getPosition()),
4508 /*IsStringLocation*/true,
4509 getSpecifierRange(startSpecifier, specifierLen),
4510 FixItHint::CreateRemoval(
4511 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00004512}
4513
Ted Kremenek2b417712015-07-02 05:39:16 +00004514// void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
4515// bool IsStringLocation, Range StringRange,
4516// ArrayRef<FixItHint> Fixit = None);
4517
4518void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
4519 unsigned flagLen) {
4520 // Warn about an empty flag.
4521 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
4522 getLocationOfByte(startFlag),
4523 /*IsStringLocation*/true,
4524 getSpecifierRange(startFlag, flagLen));
4525}
4526
4527void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
4528 unsigned flagLen) {
4529 // Warn about an invalid flag.
4530 auto Range = getSpecifierRange(startFlag, flagLen);
4531 StringRef flag(startFlag, flagLen);
4532 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
4533 getLocationOfByte(startFlag),
4534 /*IsStringLocation*/true,
4535 Range, FixItHint::CreateRemoval(Range));
4536}
4537
4538void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
4539 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
4540 // Warn about using '[...]' without a '@' conversion.
4541 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
4542 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
4543 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
4544 getLocationOfByte(conversionPosition),
4545 /*IsStringLocation*/true,
4546 Range, FixItHint::CreateRemoval(Range));
4547}
4548
Richard Smith55ce3522012-06-25 20:30:08 +00004549// Determines if the specified is a C++ class or struct containing
4550// a member with the specified name and kind (e.g. a CXXMethodDecl named
4551// "c_str()").
4552template<typename MemberKind>
4553static llvm::SmallPtrSet<MemberKind*, 1>
4554CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
4555 const RecordType *RT = Ty->getAs<RecordType>();
4556 llvm::SmallPtrSet<MemberKind*, 1> Results;
4557
4558 if (!RT)
4559 return Results;
4560 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00004561 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00004562 return Results;
4563
Alp Tokerb6cc5922014-05-03 03:45:55 +00004564 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00004565 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00004566 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00004567
4568 // We just need to include all members of the right kind turned up by the
4569 // filter, at this point.
4570 if (S.LookupQualifiedName(R, RT->getDecl()))
4571 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
4572 NamedDecl *decl = (*I)->getUnderlyingDecl();
4573 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
4574 Results.insert(FK);
4575 }
4576 return Results;
4577}
4578
Richard Smith2868a732014-02-28 01:36:39 +00004579/// Check if we could call '.c_str()' on an object.
4580///
4581/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
4582/// allow the call, or if it would be ambiguous).
4583bool Sema::hasCStrMethod(const Expr *E) {
4584 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
4585 MethodSet Results =
4586 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
4587 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
4588 MI != ME; ++MI)
4589 if ((*MI)->getMinRequiredArguments() == 0)
4590 return true;
4591 return false;
4592}
4593
Richard Smith55ce3522012-06-25 20:30:08 +00004594// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004595// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00004596// Returns true when a c_str() conversion method is found.
4597bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00004598 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00004599 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
4600
4601 MethodSet Results =
4602 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
4603
4604 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
4605 MI != ME; ++MI) {
4606 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00004607 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00004608 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00004609 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00004610 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00004611 S.Diag(E->getLocStart(), diag::note_printf_c_str)
4612 << "c_str()"
4613 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
4614 return true;
4615 }
4616 }
4617
4618 return false;
4619}
4620
Ted Kremenekab278de2010-01-28 23:39:18 +00004621bool
Ted Kremenek02087932010-07-16 02:11:22 +00004622CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00004623 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00004624 const char *startSpecifier,
4625 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004626 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00004627 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004628 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00004629
Ted Kremenek6cd69422010-07-19 22:01:06 +00004630 if (FS.consumesDataArgument()) {
4631 if (atFirstArg) {
4632 atFirstArg = false;
4633 usesPositionalArgs = FS.usesPositionalArg();
4634 }
4635 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004636 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
4637 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00004638 return false;
4639 }
Ted Kremenek5739de72010-01-29 01:06:55 +00004640 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004641
Ted Kremenekd1668192010-02-27 01:41:03 +00004642 // First check if the field width, precision, and conversion specifier
4643 // have matching data arguments.
4644 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
4645 startSpecifier, specifierLen)) {
4646 return false;
4647 }
4648
4649 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
4650 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004651 return false;
4652 }
4653
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004654 if (!CS.consumesDataArgument()) {
4655 // FIXME: Technically specifying a precision or field width here
4656 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00004657 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004658 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004659
Ted Kremenek4a49d982010-02-26 19:18:41 +00004660 // Consume the argument.
4661 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00004662 if (argIndex < NumDataArgs) {
4663 // The check to see if the argIndex is valid will come later.
4664 // We set the bit here because we may exit early from this
4665 // function if we encounter some other error.
4666 CoveredArgs.set(argIndex);
4667 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00004668
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004669 // FreeBSD kernel extensions.
4670 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
4671 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
4672 // We need at least two arguments.
4673 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
4674 return false;
4675
4676 // Claim the second argument.
4677 CoveredArgs.set(argIndex + 1);
4678
4679 // Type check the first argument (int for %b, pointer for %D)
4680 const Expr *Ex = getDataArg(argIndex);
4681 const analyze_printf::ArgType &AT =
4682 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
4683 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
4684 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
4685 EmitFormatDiagnostic(
4686 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4687 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
4688 << false << Ex->getSourceRange(),
4689 Ex->getLocStart(), /*IsStringLocation*/false,
4690 getSpecifierRange(startSpecifier, specifierLen));
4691
4692 // Type check the second argument (char * for both %b and %D)
4693 Ex = getDataArg(argIndex + 1);
4694 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
4695 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
4696 EmitFormatDiagnostic(
4697 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4698 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
4699 << false << Ex->getSourceRange(),
4700 Ex->getLocStart(), /*IsStringLocation*/false,
4701 getSpecifierRange(startSpecifier, specifierLen));
4702
4703 return true;
4704 }
4705
Ted Kremenek4a49d982010-02-26 19:18:41 +00004706 // Check for using an Objective-C specific conversion specifier
4707 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004708 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00004709 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
4710 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00004711 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004712
Tom Careb49ec692010-06-17 19:00:27 +00004713 // Check for invalid use of field width
4714 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00004715 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00004716 startSpecifier, specifierLen);
4717 }
4718
4719 // Check for invalid use of precision
4720 if (!FS.hasValidPrecision()) {
4721 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
4722 startSpecifier, specifierLen);
4723 }
4724
4725 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00004726 if (!FS.hasValidThousandsGroupingPrefix())
4727 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004728 if (!FS.hasValidLeadingZeros())
4729 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
4730 if (!FS.hasValidPlusPrefix())
4731 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00004732 if (!FS.hasValidSpacePrefix())
4733 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004734 if (!FS.hasValidAlternativeForm())
4735 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
4736 if (!FS.hasValidLeftJustified())
4737 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
4738
4739 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00004740 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
4741 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
4742 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004743 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
4744 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
4745 startSpecifier, specifierLen);
4746
4747 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00004748 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00004749 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4750 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00004751 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004752 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00004753 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004754 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4755 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00004756
Jordan Rose92303592012-09-08 04:00:03 +00004757 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4758 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4759
Ted Kremenek9fcd8302010-01-29 01:43:31 +00004760 // The remaining checks depend on the data arguments.
4761 if (HasVAListArg)
4762 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004763
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004764 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00004765 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004766
Jordan Rose58bbe422012-07-19 18:10:08 +00004767 const Expr *Arg = getDataArg(argIndex);
4768 if (!Arg)
4769 return true;
4770
4771 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00004772}
4773
Jordan Roseaee34382012-09-05 22:56:26 +00004774static bool requiresParensToAddCast(const Expr *E) {
4775 // FIXME: We should have a general way to reason about operator
4776 // precedence and whether parens are actually needed here.
4777 // Take care of a few common cases where they aren't.
4778 const Expr *Inside = E->IgnoreImpCasts();
4779 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
4780 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
4781
4782 switch (Inside->getStmtClass()) {
4783 case Stmt::ArraySubscriptExprClass:
4784 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004785 case Stmt::CharacterLiteralClass:
4786 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004787 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004788 case Stmt::FloatingLiteralClass:
4789 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004790 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004791 case Stmt::ObjCArrayLiteralClass:
4792 case Stmt::ObjCBoolLiteralExprClass:
4793 case Stmt::ObjCBoxedExprClass:
4794 case Stmt::ObjCDictionaryLiteralClass:
4795 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004796 case Stmt::ObjCIvarRefExprClass:
4797 case Stmt::ObjCMessageExprClass:
4798 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004799 case Stmt::ObjCStringLiteralClass:
4800 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004801 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004802 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004803 case Stmt::UnaryOperatorClass:
4804 return false;
4805 default:
4806 return true;
4807 }
4808}
4809
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004810static std::pair<QualType, StringRef>
4811shouldNotPrintDirectly(const ASTContext &Context,
4812 QualType IntendedTy,
4813 const Expr *E) {
4814 // Use a 'while' to peel off layers of typedefs.
4815 QualType TyTy = IntendedTy;
4816 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
4817 StringRef Name = UserTy->getDecl()->getName();
4818 QualType CastTy = llvm::StringSwitch<QualType>(Name)
4819 .Case("NSInteger", Context.LongTy)
4820 .Case("NSUInteger", Context.UnsignedLongTy)
4821 .Case("SInt32", Context.IntTy)
4822 .Case("UInt32", Context.UnsignedIntTy)
4823 .Default(QualType());
4824
4825 if (!CastTy.isNull())
4826 return std::make_pair(CastTy, Name);
4827
4828 TyTy = UserTy->desugar();
4829 }
4830
4831 // Strip parens if necessary.
4832 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
4833 return shouldNotPrintDirectly(Context,
4834 PE->getSubExpr()->getType(),
4835 PE->getSubExpr());
4836
4837 // If this is a conditional expression, then its result type is constructed
4838 // via usual arithmetic conversions and thus there might be no necessary
4839 // typedef sugar there. Recurse to operands to check for NSInteger &
4840 // Co. usage condition.
4841 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4842 QualType TrueTy, FalseTy;
4843 StringRef TrueName, FalseName;
4844
4845 std::tie(TrueTy, TrueName) =
4846 shouldNotPrintDirectly(Context,
4847 CO->getTrueExpr()->getType(),
4848 CO->getTrueExpr());
4849 std::tie(FalseTy, FalseName) =
4850 shouldNotPrintDirectly(Context,
4851 CO->getFalseExpr()->getType(),
4852 CO->getFalseExpr());
4853
4854 if (TrueTy == FalseTy)
4855 return std::make_pair(TrueTy, TrueName);
4856 else if (TrueTy.isNull())
4857 return std::make_pair(FalseTy, FalseName);
4858 else if (FalseTy.isNull())
4859 return std::make_pair(TrueTy, TrueName);
4860 }
4861
4862 return std::make_pair(QualType(), StringRef());
4863}
4864
Richard Smith55ce3522012-06-25 20:30:08 +00004865bool
4866CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
4867 const char *StartSpecifier,
4868 unsigned SpecifierLen,
4869 const Expr *E) {
4870 using namespace analyze_format_string;
4871 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004872 // Now type check the data expression that matches the
4873 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004874 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
4875 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00004876 if (!AT.isValid())
4877 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00004878
Jordan Rose598ec092012-12-05 18:44:40 +00004879 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00004880 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
4881 ExprTy = TET->getUnderlyingExpr()->getType();
4882 }
4883
Seth Cantrellb4802962015-03-04 03:12:10 +00004884 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
4885
4886 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00004887 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00004888 }
Jordan Rose98709982012-06-04 22:48:57 +00004889
Jordan Rose22b74712012-09-05 22:56:19 +00004890 // Look through argument promotions for our error message's reported type.
4891 // This includes the integral and floating promotions, but excludes array
4892 // and function pointer decay; seeing that an argument intended to be a
4893 // string has type 'char [6]' is probably more confusing than 'char *'.
4894 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
4895 if (ICE->getCastKind() == CK_IntegralCast ||
4896 ICE->getCastKind() == CK_FloatingCast) {
4897 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00004898 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00004899
4900 // Check if we didn't match because of an implicit cast from a 'char'
4901 // or 'short' to an 'int'. This is done because printf is a varargs
4902 // function.
4903 if (ICE->getType() == S.Context.IntTy ||
4904 ICE->getType() == S.Context.UnsignedIntTy) {
4905 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00004906 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00004907 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00004908 }
Jordan Rose98709982012-06-04 22:48:57 +00004909 }
Jordan Rose598ec092012-12-05 18:44:40 +00004910 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
4911 // Special case for 'a', which has type 'int' in C.
4912 // Note, however, that we do /not/ want to treat multibyte constants like
4913 // 'MooV' as characters! This form is deprecated but still exists.
4914 if (ExprTy == S.Context.IntTy)
4915 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
4916 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00004917 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004918
Jordan Rosebc53ed12014-05-31 04:12:14 +00004919 // Look through enums to their underlying type.
4920 bool IsEnum = false;
4921 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
4922 ExprTy = EnumTy->getDecl()->getIntegerType();
4923 IsEnum = true;
4924 }
4925
Jordan Rose0e5badd2012-12-05 18:44:49 +00004926 // %C in an Objective-C context prints a unichar, not a wchar_t.
4927 // If the argument is an integer of some kind, believe the %C and suggest
4928 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00004929 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00004930 if (ObjCContext &&
4931 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
4932 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
4933 !ExprTy->isCharType()) {
4934 // 'unichar' is defined as a typedef of unsigned short, but we should
4935 // prefer using the typedef if it is visible.
4936 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00004937
4938 // While we are here, check if the value is an IntegerLiteral that happens
4939 // to be within the valid range.
4940 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
4941 const llvm::APInt &V = IL->getValue();
4942 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
4943 return true;
4944 }
4945
Jordan Rose0e5badd2012-12-05 18:44:49 +00004946 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
4947 Sema::LookupOrdinaryName);
4948 if (S.LookupName(Result, S.getCurScope())) {
4949 NamedDecl *ND = Result.getFoundDecl();
4950 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
4951 if (TD->getUnderlyingType() == IntendedTy)
4952 IntendedTy = S.Context.getTypedefType(TD);
4953 }
4954 }
4955 }
4956
4957 // Special-case some of Darwin's platform-independence types by suggesting
4958 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004959 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00004960 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004961 QualType CastTy;
4962 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
4963 if (!CastTy.isNull()) {
4964 IntendedTy = CastTy;
4965 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00004966 }
4967 }
4968
Jordan Rose22b74712012-09-05 22:56:19 +00004969 // We may be able to offer a FixItHint if it is a supported type.
4970 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00004971 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00004972 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004973
Jordan Rose22b74712012-09-05 22:56:19 +00004974 if (success) {
4975 // Get the fix string from the fixed format specifier
4976 SmallString<16> buf;
4977 llvm::raw_svector_ostream os(buf);
4978 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004979
Jordan Roseaee34382012-09-05 22:56:26 +00004980 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
4981
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004982 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00004983 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4984 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
4985 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4986 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00004987 // In this case, the specifier is wrong and should be changed to match
4988 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00004989 EmitFormatDiagnostic(S.PDiag(diag)
4990 << AT.getRepresentativeTypeName(S.Context)
4991 << IntendedTy << IsEnum << E->getSourceRange(),
4992 E->getLocStart(),
4993 /*IsStringLocation*/ false, SpecRange,
4994 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00004995 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00004996 // The canonical type for formatting this value is different from the
4997 // actual type of the expression. (This occurs, for example, with Darwin's
4998 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
4999 // should be printed as 'long' for 64-bit compatibility.)
5000 // Rather than emitting a normal format/argument mismatch, we want to
5001 // add a cast to the recommended type (and correct the format string
5002 // if necessary).
5003 SmallString<16> CastBuf;
5004 llvm::raw_svector_ostream CastFix(CastBuf);
5005 CastFix << "(";
5006 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
5007 CastFix << ")";
5008
5009 SmallVector<FixItHint,4> Hints;
5010 if (!AT.matchesType(S.Context, IntendedTy))
5011 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
5012
5013 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
5014 // If there's already a cast present, just replace it.
5015 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
5016 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
5017
5018 } else if (!requiresParensToAddCast(E)) {
5019 // If the expression has high enough precedence,
5020 // just write the C-style cast.
5021 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
5022 CastFix.str()));
5023 } else {
5024 // Otherwise, add parens around the expression as well as the cast.
5025 CastFix << "(";
5026 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
5027 CastFix.str()));
5028
Alp Tokerb6cc5922014-05-03 03:45:55 +00005029 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00005030 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
5031 }
5032
Jordan Rose0e5badd2012-12-05 18:44:49 +00005033 if (ShouldNotPrintDirectly) {
5034 // The expression has a type that should not be printed directly.
5035 // We extract the name from the typedef because we don't want to show
5036 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005037 StringRef Name;
5038 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
5039 Name = TypedefTy->getDecl()->getName();
5040 else
5041 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00005042 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00005043 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00005044 << E->getSourceRange(),
5045 E->getLocStart(), /*IsStringLocation=*/false,
5046 SpecRange, Hints);
5047 } else {
5048 // In this case, the expression could be printed using a different
5049 // specifier, but we've decided that the specifier is probably correct
5050 // and we should cast instead. Just use the normal warning message.
5051 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00005052 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5053 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00005054 << E->getSourceRange(),
5055 E->getLocStart(), /*IsStringLocation*/false,
5056 SpecRange, Hints);
5057 }
Jordan Roseaee34382012-09-05 22:56:26 +00005058 }
Jordan Rose22b74712012-09-05 22:56:19 +00005059 } else {
5060 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
5061 SpecifierLen);
5062 // Since the warning for passing non-POD types to variadic functions
5063 // was deferred until now, we emit a warning for non-POD
5064 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00005065 switch (S.isValidVarArgType(ExprTy)) {
5066 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00005067 case Sema::VAK_ValidInCXX11: {
5068 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5069 if (match == analyze_printf::ArgType::NoMatchPedantic) {
5070 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5071 }
Richard Smithd7293d72013-08-05 18:49:43 +00005072
Seth Cantrellb4802962015-03-04 03:12:10 +00005073 EmitFormatDiagnostic(
5074 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
5075 << IsEnum << CSR << E->getSourceRange(),
5076 E->getLocStart(), /*IsStringLocation*/ false, CSR);
5077 break;
5078 }
Richard Smithd7293d72013-08-05 18:49:43 +00005079 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00005080 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00005081 EmitFormatDiagnostic(
5082 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005083 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00005084 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00005085 << CallType
5086 << AT.getRepresentativeTypeName(S.Context)
5087 << CSR
5088 << E->getSourceRange(),
5089 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00005090 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00005091 break;
5092
5093 case Sema::VAK_Invalid:
5094 if (ExprTy->isObjCObjectType())
5095 EmitFormatDiagnostic(
5096 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
5097 << S.getLangOpts().CPlusPlus11
5098 << ExprTy
5099 << CallType
5100 << AT.getRepresentativeTypeName(S.Context)
5101 << CSR
5102 << E->getSourceRange(),
5103 E->getLocStart(), /*IsStringLocation*/false, CSR);
5104 else
5105 // FIXME: If this is an initializer list, suggest removing the braces
5106 // or inserting a cast to the target type.
5107 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
5108 << isa<InitListExpr>(E) << ExprTy << CallType
5109 << AT.getRepresentativeTypeName(S.Context)
5110 << E->getSourceRange();
5111 break;
5112 }
5113
5114 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
5115 "format string specifier index out of range");
5116 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005117 }
5118
Ted Kremenekab278de2010-01-28 23:39:18 +00005119 return true;
5120}
5121
Ted Kremenek02087932010-07-16 02:11:22 +00005122//===--- CHECK: Scanf format string checking ------------------------------===//
5123
5124namespace {
5125class CheckScanfHandler : public CheckFormatHandler {
5126public:
5127 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
5128 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005129 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005130 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005131 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00005132 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005133 llvm::SmallBitVector &CheckedVarArgs,
5134 UncoveredArgHandler &UncoveredArg)
Richard Smithd7293d72013-08-05 18:49:43 +00005135 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
5136 numDataArgs, beg, hasVAListArg,
5137 Args, formatIdx, inFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005138 CheckedVarArgs, UncoveredArg)
Jordan Rose3e0ec582012-07-19 18:10:23 +00005139 {}
Ted Kremenek02087932010-07-16 02:11:22 +00005140
5141 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
5142 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005143 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00005144
5145 bool HandleInvalidScanfConversionSpecifier(
5146 const analyze_scanf::ScanfSpecifier &FS,
5147 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005148 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00005149
Craig Toppere14c0f82014-03-12 04:55:44 +00005150 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00005151};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005152} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00005153
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00005154void CheckScanfHandler::HandleIncompleteScanList(const char *start,
5155 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005156 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
5157 getLocationOfByte(end), /*IsStringLocation*/true,
5158 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00005159}
5160
Ted Kremenekce815422010-07-19 21:25:57 +00005161bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
5162 const analyze_scanf::ScanfSpecifier &FS,
5163 const char *startSpecifier,
5164 unsigned specifierLen) {
5165
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005166 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00005167 FS.getConversionSpecifier();
5168
5169 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5170 getLocationOfByte(CS.getStart()),
5171 startSpecifier, specifierLen,
5172 CS.getStart(), CS.getLength());
5173}
5174
Ted Kremenek02087932010-07-16 02:11:22 +00005175bool CheckScanfHandler::HandleScanfSpecifier(
5176 const analyze_scanf::ScanfSpecifier &FS,
5177 const char *startSpecifier,
5178 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00005179 using namespace analyze_scanf;
5180 using namespace analyze_format_string;
5181
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005182 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00005183
Ted Kremenek6cd69422010-07-19 22:01:06 +00005184 // Handle case where '%' and '*' don't consume an argument. These shouldn't
5185 // be used to decide if we are using positional arguments consistently.
5186 if (FS.consumesDataArgument()) {
5187 if (atFirstArg) {
5188 atFirstArg = false;
5189 usesPositionalArgs = FS.usesPositionalArg();
5190 }
5191 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005192 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5193 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00005194 return false;
5195 }
Ted Kremenek02087932010-07-16 02:11:22 +00005196 }
5197
5198 // Check if the field with is non-zero.
5199 const OptionalAmount &Amt = FS.getFieldWidth();
5200 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
5201 if (Amt.getConstantAmount() == 0) {
5202 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
5203 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00005204 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
5205 getLocationOfByte(Amt.getStart()),
5206 /*IsStringLocation*/true, R,
5207 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00005208 }
5209 }
Seth Cantrellb4802962015-03-04 03:12:10 +00005210
Ted Kremenek02087932010-07-16 02:11:22 +00005211 if (!FS.consumesDataArgument()) {
5212 // FIXME: Technically specifying a precision or field width here
5213 // makes no sense. Worth issuing a warning at some point.
5214 return true;
5215 }
Seth Cantrellb4802962015-03-04 03:12:10 +00005216
Ted Kremenek02087932010-07-16 02:11:22 +00005217 // Consume the argument.
5218 unsigned argIndex = FS.getArgIndex();
5219 if (argIndex < NumDataArgs) {
5220 // The check to see if the argIndex is valid will come later.
5221 // We set the bit here because we may exit early from this
5222 // function if we encounter some other error.
5223 CoveredArgs.set(argIndex);
5224 }
Seth Cantrellb4802962015-03-04 03:12:10 +00005225
Ted Kremenek4407ea42010-07-20 20:04:47 +00005226 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00005227 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00005228 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5229 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00005230 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005231 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00005232 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005233 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5234 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005235
Jordan Rose92303592012-09-08 04:00:03 +00005236 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
5237 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5238
Ted Kremenek02087932010-07-16 02:11:22 +00005239 // The remaining checks depend on the data arguments.
5240 if (HasVAListArg)
5241 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00005242
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005243 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00005244 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00005245
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005246 // Check that the argument type matches the format specifier.
5247 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00005248 if (!Ex)
5249 return true;
5250
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00005251 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00005252
5253 if (!AT.isValid()) {
5254 return true;
5255 }
5256
Seth Cantrellb4802962015-03-04 03:12:10 +00005257 analyze_format_string::ArgType::MatchKind match =
5258 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00005259 if (match == analyze_format_string::ArgType::Match) {
5260 return true;
5261 }
Seth Cantrellb4802962015-03-04 03:12:10 +00005262
Seth Cantrell79340072015-03-04 05:58:08 +00005263 ScanfSpecifier fixedFS = FS;
5264 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
5265 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005266
Seth Cantrell79340072015-03-04 05:58:08 +00005267 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5268 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
5269 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5270 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005271
Seth Cantrell79340072015-03-04 05:58:08 +00005272 if (success) {
5273 // Get the fix string from the fixed format specifier.
5274 SmallString<128> buf;
5275 llvm::raw_svector_ostream os(buf);
5276 fixedFS.toString(os);
5277
5278 EmitFormatDiagnostic(
5279 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
5280 << Ex->getType() << false << Ex->getSourceRange(),
5281 Ex->getLocStart(),
5282 /*IsStringLocation*/ false,
5283 getSpecifierRange(startSpecifier, specifierLen),
5284 FixItHint::CreateReplacement(
5285 getSpecifierRange(startSpecifier, specifierLen), os.str()));
5286 } else {
5287 EmitFormatDiagnostic(S.PDiag(diag)
5288 << AT.getRepresentativeTypeName(S.Context)
5289 << Ex->getType() << false << Ex->getSourceRange(),
5290 Ex->getLocStart(),
5291 /*IsStringLocation*/ false,
5292 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005293 }
5294
Ted Kremenek02087932010-07-16 02:11:22 +00005295 return true;
5296}
5297
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005298static void CheckFormatString(Sema &S, const StringLiteral *FExpr,
5299 const Expr *OrigFormatExpr,
5300 ArrayRef<const Expr *> Args,
5301 bool HasVAListArg, unsigned format_idx,
5302 unsigned firstDataArg,
5303 Sema::FormatStringType Type,
5304 bool inFunctionCall,
5305 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005306 llvm::SmallBitVector &CheckedVarArgs,
5307 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00005308 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00005309 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005310 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005311 S, inFunctionCall, Args[format_idx],
5312 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00005313 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00005314 return;
5315 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005316
Ted Kremenekab278de2010-01-28 23:39:18 +00005317 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005318 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00005319 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005320 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005321 const ConstantArrayType *T =
5322 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005323 assert(T && "String literal not of constant array type!");
5324 size_t TypeSize = T->getSize().getZExtValue();
5325 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005326 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005327
5328 // Emit a warning if the string literal is truncated and does not contain an
5329 // embedded null character.
5330 if (TypeSize <= StrRef.size() &&
5331 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
5332 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005333 S, inFunctionCall, Args[format_idx],
5334 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005335 FExpr->getLocStart(),
5336 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
5337 return;
5338 }
5339
Ted Kremenekab278de2010-01-28 23:39:18 +00005340 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00005341 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005342 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005343 S, inFunctionCall, Args[format_idx],
5344 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00005345 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00005346 return;
5347 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005348
5349 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
5350 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSTrace) {
5351 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, firstDataArg,
5352 numDataArgs, (Type == Sema::FST_NSString ||
5353 Type == Sema::FST_OSTrace),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005354 Str, HasVAListArg, Args, format_idx,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005355 inFunctionCall, CallType, CheckedVarArgs,
5356 UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005357
Hans Wennborg23926bd2011-12-15 10:25:47 +00005358 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005359 S.getLangOpts(),
5360 S.Context.getTargetInfo(),
5361 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00005362 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005363 } else if (Type == Sema::FST_Scanf) {
5364 CheckScanfHandler H(S, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005365 Str, HasVAListArg, Args, format_idx,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005366 inFunctionCall, CallType, CheckedVarArgs,
5367 UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005368
Hans Wennborg23926bd2011-12-15 10:25:47 +00005369 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005370 S.getLangOpts(),
5371 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00005372 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005373 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00005374}
5375
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00005376bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
5377 // Str - The format string. NOTE: this is NOT null-terminated!
5378 StringRef StrRef = FExpr->getString();
5379 const char *Str = StrRef.data();
5380 // Account for cases where the string literal is truncated in a declaration.
5381 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
5382 assert(T && "String literal not of constant array type!");
5383 size_t TypeSize = T->getSize().getZExtValue();
5384 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
5385 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
5386 getLangOpts(),
5387 Context.getTargetInfo());
5388}
5389
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005390//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
5391
5392// Returns the related absolute value function that is larger, of 0 if one
5393// does not exist.
5394static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
5395 switch (AbsFunction) {
5396 default:
5397 return 0;
5398
5399 case Builtin::BI__builtin_abs:
5400 return Builtin::BI__builtin_labs;
5401 case Builtin::BI__builtin_labs:
5402 return Builtin::BI__builtin_llabs;
5403 case Builtin::BI__builtin_llabs:
5404 return 0;
5405
5406 case Builtin::BI__builtin_fabsf:
5407 return Builtin::BI__builtin_fabs;
5408 case Builtin::BI__builtin_fabs:
5409 return Builtin::BI__builtin_fabsl;
5410 case Builtin::BI__builtin_fabsl:
5411 return 0;
5412
5413 case Builtin::BI__builtin_cabsf:
5414 return Builtin::BI__builtin_cabs;
5415 case Builtin::BI__builtin_cabs:
5416 return Builtin::BI__builtin_cabsl;
5417 case Builtin::BI__builtin_cabsl:
5418 return 0;
5419
5420 case Builtin::BIabs:
5421 return Builtin::BIlabs;
5422 case Builtin::BIlabs:
5423 return Builtin::BIllabs;
5424 case Builtin::BIllabs:
5425 return 0;
5426
5427 case Builtin::BIfabsf:
5428 return Builtin::BIfabs;
5429 case Builtin::BIfabs:
5430 return Builtin::BIfabsl;
5431 case Builtin::BIfabsl:
5432 return 0;
5433
5434 case Builtin::BIcabsf:
5435 return Builtin::BIcabs;
5436 case Builtin::BIcabs:
5437 return Builtin::BIcabsl;
5438 case Builtin::BIcabsl:
5439 return 0;
5440 }
5441}
5442
5443// Returns the argument type of the absolute value function.
5444static QualType getAbsoluteValueArgumentType(ASTContext &Context,
5445 unsigned AbsType) {
5446 if (AbsType == 0)
5447 return QualType();
5448
5449 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
5450 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
5451 if (Error != ASTContext::GE_None)
5452 return QualType();
5453
5454 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
5455 if (!FT)
5456 return QualType();
5457
5458 if (FT->getNumParams() != 1)
5459 return QualType();
5460
5461 return FT->getParamType(0);
5462}
5463
5464// Returns the best absolute value function, or zero, based on type and
5465// current absolute value function.
5466static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
5467 unsigned AbsFunctionKind) {
5468 unsigned BestKind = 0;
5469 uint64_t ArgSize = Context.getTypeSize(ArgType);
5470 for (unsigned Kind = AbsFunctionKind; Kind != 0;
5471 Kind = getLargerAbsoluteValueFunction(Kind)) {
5472 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
5473 if (Context.getTypeSize(ParamType) >= ArgSize) {
5474 if (BestKind == 0)
5475 BestKind = Kind;
5476 else if (Context.hasSameType(ParamType, ArgType)) {
5477 BestKind = Kind;
5478 break;
5479 }
5480 }
5481 }
5482 return BestKind;
5483}
5484
5485enum AbsoluteValueKind {
5486 AVK_Integer,
5487 AVK_Floating,
5488 AVK_Complex
5489};
5490
5491static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
5492 if (T->isIntegralOrEnumerationType())
5493 return AVK_Integer;
5494 if (T->isRealFloatingType())
5495 return AVK_Floating;
5496 if (T->isAnyComplexType())
5497 return AVK_Complex;
5498
5499 llvm_unreachable("Type not integer, floating, or complex");
5500}
5501
5502// Changes the absolute value function to a different type. Preserves whether
5503// the function is a builtin.
5504static unsigned changeAbsFunction(unsigned AbsKind,
5505 AbsoluteValueKind ValueKind) {
5506 switch (ValueKind) {
5507 case AVK_Integer:
5508 switch (AbsKind) {
5509 default:
5510 return 0;
5511 case Builtin::BI__builtin_fabsf:
5512 case Builtin::BI__builtin_fabs:
5513 case Builtin::BI__builtin_fabsl:
5514 case Builtin::BI__builtin_cabsf:
5515 case Builtin::BI__builtin_cabs:
5516 case Builtin::BI__builtin_cabsl:
5517 return Builtin::BI__builtin_abs;
5518 case Builtin::BIfabsf:
5519 case Builtin::BIfabs:
5520 case Builtin::BIfabsl:
5521 case Builtin::BIcabsf:
5522 case Builtin::BIcabs:
5523 case Builtin::BIcabsl:
5524 return Builtin::BIabs;
5525 }
5526 case AVK_Floating:
5527 switch (AbsKind) {
5528 default:
5529 return 0;
5530 case Builtin::BI__builtin_abs:
5531 case Builtin::BI__builtin_labs:
5532 case Builtin::BI__builtin_llabs:
5533 case Builtin::BI__builtin_cabsf:
5534 case Builtin::BI__builtin_cabs:
5535 case Builtin::BI__builtin_cabsl:
5536 return Builtin::BI__builtin_fabsf;
5537 case Builtin::BIabs:
5538 case Builtin::BIlabs:
5539 case Builtin::BIllabs:
5540 case Builtin::BIcabsf:
5541 case Builtin::BIcabs:
5542 case Builtin::BIcabsl:
5543 return Builtin::BIfabsf;
5544 }
5545 case AVK_Complex:
5546 switch (AbsKind) {
5547 default:
5548 return 0;
5549 case Builtin::BI__builtin_abs:
5550 case Builtin::BI__builtin_labs:
5551 case Builtin::BI__builtin_llabs:
5552 case Builtin::BI__builtin_fabsf:
5553 case Builtin::BI__builtin_fabs:
5554 case Builtin::BI__builtin_fabsl:
5555 return Builtin::BI__builtin_cabsf;
5556 case Builtin::BIabs:
5557 case Builtin::BIlabs:
5558 case Builtin::BIllabs:
5559 case Builtin::BIfabsf:
5560 case Builtin::BIfabs:
5561 case Builtin::BIfabsl:
5562 return Builtin::BIcabsf;
5563 }
5564 }
5565 llvm_unreachable("Unable to convert function");
5566}
5567
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00005568static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005569 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
5570 if (!FnInfo)
5571 return 0;
5572
5573 switch (FDecl->getBuiltinID()) {
5574 default:
5575 return 0;
5576 case Builtin::BI__builtin_abs:
5577 case Builtin::BI__builtin_fabs:
5578 case Builtin::BI__builtin_fabsf:
5579 case Builtin::BI__builtin_fabsl:
5580 case Builtin::BI__builtin_labs:
5581 case Builtin::BI__builtin_llabs:
5582 case Builtin::BI__builtin_cabs:
5583 case Builtin::BI__builtin_cabsf:
5584 case Builtin::BI__builtin_cabsl:
5585 case Builtin::BIabs:
5586 case Builtin::BIlabs:
5587 case Builtin::BIllabs:
5588 case Builtin::BIfabs:
5589 case Builtin::BIfabsf:
5590 case Builtin::BIfabsl:
5591 case Builtin::BIcabs:
5592 case Builtin::BIcabsf:
5593 case Builtin::BIcabsl:
5594 return FDecl->getBuiltinID();
5595 }
5596 llvm_unreachable("Unknown Builtin type");
5597}
5598
5599// If the replacement is valid, emit a note with replacement function.
5600// Additionally, suggest including the proper header if not already included.
5601static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00005602 unsigned AbsKind, QualType ArgType) {
5603 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00005604 const char *HeaderName = nullptr;
5605 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00005606 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
5607 FunctionName = "std::abs";
5608 if (ArgType->isIntegralOrEnumerationType()) {
5609 HeaderName = "cstdlib";
5610 } else if (ArgType->isRealFloatingType()) {
5611 HeaderName = "cmath";
5612 } else {
5613 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005614 }
Richard Trieubeffb832014-04-15 23:47:53 +00005615
5616 // Lookup all std::abs
5617 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00005618 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00005619 R.suppressDiagnostics();
5620 S.LookupQualifiedName(R, Std);
5621
5622 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005623 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00005624 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
5625 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
5626 } else {
5627 FDecl = dyn_cast<FunctionDecl>(I);
5628 }
5629 if (!FDecl)
5630 continue;
5631
5632 // Found std::abs(), check that they are the right ones.
5633 if (FDecl->getNumParams() != 1)
5634 continue;
5635
5636 // Check that the parameter type can handle the argument.
5637 QualType ParamType = FDecl->getParamDecl(0)->getType();
5638 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
5639 S.Context.getTypeSize(ArgType) <=
5640 S.Context.getTypeSize(ParamType)) {
5641 // Found a function, don't need the header hint.
5642 EmitHeaderHint = false;
5643 break;
5644 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005645 }
Richard Trieubeffb832014-04-15 23:47:53 +00005646 }
5647 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00005648 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00005649 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
5650
5651 if (HeaderName) {
5652 DeclarationName DN(&S.Context.Idents.get(FunctionName));
5653 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
5654 R.suppressDiagnostics();
5655 S.LookupName(R, S.getCurScope());
5656
5657 if (R.isSingleResult()) {
5658 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
5659 if (FD && FD->getBuiltinID() == AbsKind) {
5660 EmitHeaderHint = false;
5661 } else {
5662 return;
5663 }
5664 } else if (!R.empty()) {
5665 return;
5666 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005667 }
5668 }
5669
5670 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00005671 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005672
Richard Trieubeffb832014-04-15 23:47:53 +00005673 if (!HeaderName)
5674 return;
5675
5676 if (!EmitHeaderHint)
5677 return;
5678
Alp Toker5d96e0a2014-07-11 20:53:51 +00005679 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
5680 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00005681}
5682
5683static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
5684 if (!FDecl)
5685 return false;
5686
5687 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
5688 return false;
5689
5690 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
5691
5692 while (ND && ND->isInlineNamespace()) {
5693 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005694 }
Richard Trieubeffb832014-04-15 23:47:53 +00005695
5696 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
5697 return false;
5698
5699 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
5700 return false;
5701
5702 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005703}
5704
5705// Warn when using the wrong abs() function.
5706void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
5707 const FunctionDecl *FDecl,
5708 IdentifierInfo *FnInfo) {
5709 if (Call->getNumArgs() != 1)
5710 return;
5711
5712 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00005713 bool IsStdAbs = IsFunctionStdAbs(FDecl);
5714 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005715 return;
5716
5717 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
5718 QualType ParamType = Call->getArg(0)->getType();
5719
Alp Toker5d96e0a2014-07-11 20:53:51 +00005720 // Unsigned types cannot be negative. Suggest removing the absolute value
5721 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005722 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00005723 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00005724 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005725 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
5726 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00005727 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005728 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
5729 return;
5730 }
5731
David Majnemer7f77eb92015-11-15 03:04:34 +00005732 // Taking the absolute value of a pointer is very suspicious, they probably
5733 // wanted to index into an array, dereference a pointer, call a function, etc.
5734 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
5735 unsigned DiagType = 0;
5736 if (ArgType->isFunctionType())
5737 DiagType = 1;
5738 else if (ArgType->isArrayType())
5739 DiagType = 2;
5740
5741 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
5742 return;
5743 }
5744
Richard Trieubeffb832014-04-15 23:47:53 +00005745 // std::abs has overloads which prevent most of the absolute value problems
5746 // from occurring.
5747 if (IsStdAbs)
5748 return;
5749
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005750 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
5751 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
5752
5753 // The argument and parameter are the same kind. Check if they are the right
5754 // size.
5755 if (ArgValueKind == ParamValueKind) {
5756 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
5757 return;
5758
5759 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
5760 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
5761 << FDecl << ArgType << ParamType;
5762
5763 if (NewAbsKind == 0)
5764 return;
5765
5766 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00005767 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005768 return;
5769 }
5770
5771 // ArgValueKind != ParamValueKind
5772 // The wrong type of absolute value function was used. Attempt to find the
5773 // proper one.
5774 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
5775 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
5776 if (NewAbsKind == 0)
5777 return;
5778
5779 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
5780 << FDecl << ParamValueKind << ArgValueKind;
5781
5782 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00005783 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005784}
5785
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005786//===--- CHECK: Standard memory functions ---------------------------------===//
5787
Nico Weber0e6daef2013-12-26 23:38:39 +00005788/// \brief Takes the expression passed to the size_t parameter of functions
5789/// such as memcmp, strncat, etc and warns if it's a comparison.
5790///
5791/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
5792static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
5793 IdentifierInfo *FnName,
5794 SourceLocation FnLoc,
5795 SourceLocation RParenLoc) {
5796 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
5797 if (!Size)
5798 return false;
5799
5800 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
5801 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
5802 return false;
5803
Nico Weber0e6daef2013-12-26 23:38:39 +00005804 SourceRange SizeRange = Size->getSourceRange();
5805 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
5806 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00005807 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00005808 << FnName << FixItHint::CreateInsertion(
5809 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00005810 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00005811 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00005812 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00005813 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
5814 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00005815
5816 return true;
5817}
5818
Reid Kleckner5fb5b122014-06-27 23:58:21 +00005819/// \brief Determine whether the given type is or contains a dynamic class type
5820/// (e.g., whether it has a vtable).
5821static const CXXRecordDecl *getContainedDynamicClass(QualType T,
5822 bool &IsContained) {
5823 // Look through array types while ignoring qualifiers.
5824 const Type *Ty = T->getBaseElementTypeUnsafe();
5825 IsContained = false;
5826
5827 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
5828 RD = RD ? RD->getDefinition() : nullptr;
Richard Trieu1c7237a2016-03-31 04:18:07 +00005829 if (!RD || RD->isInvalidDecl())
Reid Kleckner5fb5b122014-06-27 23:58:21 +00005830 return nullptr;
5831
5832 if (RD->isDynamicClass())
5833 return RD;
5834
5835 // Check all the fields. If any bases were dynamic, the class is dynamic.
5836 // It's impossible for a class to transitively contain itself by value, so
5837 // infinite recursion is impossible.
5838 for (auto *FD : RD->fields()) {
5839 bool SubContained;
5840 if (const CXXRecordDecl *ContainedRD =
5841 getContainedDynamicClass(FD->getType(), SubContained)) {
5842 IsContained = true;
5843 return ContainedRD;
5844 }
5845 }
5846
5847 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00005848}
5849
Chandler Carruth889ed862011-06-21 23:04:20 +00005850/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005851/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00005852static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00005853 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005854 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
5855 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
5856 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00005857
Craig Topperc3ec1492014-05-26 06:22:03 +00005858 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005859}
5860
Chandler Carruth889ed862011-06-21 23:04:20 +00005861/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00005862static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005863 if (const UnaryExprOrTypeTraitExpr *SizeOf =
5864 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
5865 if (SizeOf->getKind() == clang::UETT_SizeOf)
5866 return SizeOf->getTypeOfArgument();
5867
5868 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00005869}
5870
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005871/// \brief Check for dangerous or invalid arguments to memset().
5872///
Chandler Carruthac687262011-06-03 06:23:57 +00005873/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005874/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
5875/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005876///
5877/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005878void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00005879 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005880 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00005881 assert(BId != 0);
5882
Ted Kremenekb5fabb22011-04-28 01:38:02 +00005883 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00005884 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00005885 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00005886 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00005887 return;
5888
Anna Zaks22122702012-01-17 00:37:07 +00005889 unsigned LastArg = (BId == Builtin::BImemset ||
5890 BId == Builtin::BIstrndup ? 1 : 2);
5891 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00005892 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005893
Nico Weber0e6daef2013-12-26 23:38:39 +00005894 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
5895 Call->getLocStart(), Call->getRParenLoc()))
5896 return;
5897
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005898 // We have special checking when the length is a sizeof expression.
5899 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
5900 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
5901 llvm::FoldingSetNodeID SizeOfArgID;
5902
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005903 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
5904 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00005905 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005906
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005907 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00005908 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005909 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00005910 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00005911
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005912 // Never warn about void type pointers. This can be used to suppress
5913 // false positives.
5914 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005915 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005916
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005917 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
5918 // actually comparing the expressions for equality. Because computing the
5919 // expression IDs can be expensive, we only do this if the diagnostic is
5920 // enabled.
5921 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00005922 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
5923 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005924 // We only compute IDs for expressions if the warning is enabled, and
5925 // cache the sizeof arg's ID.
5926 if (SizeOfArgID == llvm::FoldingSetNodeID())
5927 SizeOfArg->Profile(SizeOfArgID, Context, true);
5928 llvm::FoldingSetNodeID DestID;
5929 Dest->Profile(DestID, Context, true);
5930 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00005931 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
5932 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005933 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00005934 StringRef ReadableName = FnName->getName();
5935
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005936 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00005937 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005938 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00005939 if (!PointeeTy->isIncompleteType() &&
5940 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005941 ActionIdx = 2; // If the pointee's size is sizeof(char),
5942 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00005943
5944 // If the function is defined as a builtin macro, do not show macro
5945 // expansion.
5946 SourceLocation SL = SizeOfArg->getExprLoc();
5947 SourceRange DSR = Dest->getSourceRange();
5948 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00005949 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00005950
5951 if (SM.isMacroArgExpansion(SL)) {
5952 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
5953 SL = SM.getSpellingLoc(SL);
5954 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
5955 SM.getSpellingLoc(DSR.getEnd()));
5956 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
5957 SM.getSpellingLoc(SSR.getEnd()));
5958 }
5959
Anna Zaksd08d9152012-05-30 23:14:52 +00005960 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005961 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00005962 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00005963 << PointeeTy
5964 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00005965 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00005966 << SSR);
5967 DiagRuntimeBehavior(SL, SizeOfArg,
5968 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
5969 << ActionIdx
5970 << SSR);
5971
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005972 break;
5973 }
5974 }
5975
5976 // Also check for cases where the sizeof argument is the exact same
5977 // type as the memory argument, and where it points to a user-defined
5978 // record type.
5979 if (SizeOfArgTy != QualType()) {
5980 if (PointeeTy->isRecordType() &&
5981 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
5982 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
5983 PDiag(diag::warn_sizeof_pointer_type_memaccess)
5984 << FnName << SizeOfArgTy << ArgIdx
5985 << PointeeTy << Dest->getSourceRange()
5986 << LenExpr->getSourceRange());
5987 break;
5988 }
Nico Weberc5e73862011-06-14 16:14:58 +00005989 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00005990 } else if (DestTy->isArrayType()) {
5991 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00005992 }
Nico Weberc5e73862011-06-14 16:14:58 +00005993
Nico Weberc44b35e2015-03-21 17:37:46 +00005994 if (PointeeTy == QualType())
5995 continue;
Anna Zaks22122702012-01-17 00:37:07 +00005996
Nico Weberc44b35e2015-03-21 17:37:46 +00005997 // Always complain about dynamic classes.
5998 bool IsContained;
5999 if (const CXXRecordDecl *ContainedRD =
6000 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00006001
Nico Weberc44b35e2015-03-21 17:37:46 +00006002 unsigned OperationType = 0;
6003 // "overwritten" if we're warning about the destination for any call
6004 // but memcmp; otherwise a verb appropriate to the call.
6005 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
6006 if (BId == Builtin::BImemcpy)
6007 OperationType = 1;
6008 else if(BId == Builtin::BImemmove)
6009 OperationType = 2;
6010 else if (BId == Builtin::BImemcmp)
6011 OperationType = 3;
6012 }
6013
John McCall31168b02011-06-15 23:02:42 +00006014 DiagRuntimeBehavior(
6015 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00006016 PDiag(diag::warn_dyn_class_memaccess)
6017 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
6018 << FnName << IsContained << ContainedRD << OperationType
6019 << Call->getCallee()->getSourceRange());
6020 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
6021 BId != Builtin::BImemset)
6022 DiagRuntimeBehavior(
6023 Dest->getExprLoc(), Dest,
6024 PDiag(diag::warn_arc_object_memaccess)
6025 << ArgIdx << FnName << PointeeTy
6026 << Call->getCallee()->getSourceRange());
6027 else
6028 continue;
6029
6030 DiagRuntimeBehavior(
6031 Dest->getExprLoc(), Dest,
6032 PDiag(diag::note_bad_memaccess_silence)
6033 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
6034 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006035 }
6036}
6037
Ted Kremenek6865f772011-08-18 20:55:45 +00006038// A little helper routine: ignore addition and subtraction of integer literals.
6039// This intentionally does not ignore all integer constant expressions because
6040// we don't want to remove sizeof().
6041static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
6042 Ex = Ex->IgnoreParenCasts();
6043
6044 for (;;) {
6045 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
6046 if (!BO || !BO->isAdditiveOp())
6047 break;
6048
6049 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
6050 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
6051
6052 if (isa<IntegerLiteral>(RHS))
6053 Ex = LHS;
6054 else if (isa<IntegerLiteral>(LHS))
6055 Ex = RHS;
6056 else
6057 break;
6058 }
6059
6060 return Ex;
6061}
6062
Anna Zaks13b08572012-08-08 21:42:23 +00006063static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
6064 ASTContext &Context) {
6065 // Only handle constant-sized or VLAs, but not flexible members.
6066 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
6067 // Only issue the FIXIT for arrays of size > 1.
6068 if (CAT->getSize().getSExtValue() <= 1)
6069 return false;
6070 } else if (!Ty->isVariableArrayType()) {
6071 return false;
6072 }
6073 return true;
6074}
6075
Ted Kremenek6865f772011-08-18 20:55:45 +00006076// Warn if the user has made the 'size' argument to strlcpy or strlcat
6077// be the size of the source, instead of the destination.
6078void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
6079 IdentifierInfo *FnName) {
6080
6081 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00006082 unsigned NumArgs = Call->getNumArgs();
6083 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00006084 return;
6085
6086 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
6087 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00006088 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00006089
6090 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
6091 Call->getLocStart(), Call->getRParenLoc()))
6092 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00006093
6094 // Look for 'strlcpy(dst, x, sizeof(x))'
6095 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
6096 CompareWithSrc = Ex;
6097 else {
6098 // Look for 'strlcpy(dst, x, strlen(x))'
6099 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00006100 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
6101 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00006102 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
6103 }
6104 }
6105
6106 if (!CompareWithSrc)
6107 return;
6108
6109 // Determine if the argument to sizeof/strlen is equal to the source
6110 // argument. In principle there's all kinds of things you could do
6111 // here, for instance creating an == expression and evaluating it with
6112 // EvaluateAsBooleanCondition, but this uses a more direct technique:
6113 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
6114 if (!SrcArgDRE)
6115 return;
6116
6117 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
6118 if (!CompareWithSrcDRE ||
6119 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
6120 return;
6121
6122 const Expr *OriginalSizeArg = Call->getArg(2);
6123 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
6124 << OriginalSizeArg->getSourceRange() << FnName;
6125
6126 // Output a FIXIT hint if the destination is an array (rather than a
6127 // pointer to an array). This could be enhanced to handle some
6128 // pointers if we know the actual size, like if DstArg is 'array+2'
6129 // we could say 'sizeof(array)-2'.
6130 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00006131 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00006132 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00006133
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00006134 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00006135 llvm::raw_svector_ostream OS(sizeString);
6136 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00006137 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00006138 OS << ")";
6139
6140 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
6141 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
6142 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00006143}
6144
Anna Zaks314cd092012-02-01 19:08:57 +00006145/// Check if two expressions refer to the same declaration.
6146static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
6147 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
6148 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
6149 return D1->getDecl() == D2->getDecl();
6150 return false;
6151}
6152
6153static const Expr *getStrlenExprArg(const Expr *E) {
6154 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6155 const FunctionDecl *FD = CE->getDirectCallee();
6156 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00006157 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00006158 return CE->getArg(0)->IgnoreParenCasts();
6159 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006160 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00006161}
6162
6163// Warn on anti-patterns as the 'size' argument to strncat.
6164// The correct size argument should look like following:
6165// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
6166void Sema::CheckStrncatArguments(const CallExpr *CE,
6167 IdentifierInfo *FnName) {
6168 // Don't crash if the user has the wrong number of arguments.
6169 if (CE->getNumArgs() < 3)
6170 return;
6171 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
6172 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
6173 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
6174
Nico Weber0e6daef2013-12-26 23:38:39 +00006175 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
6176 CE->getRParenLoc()))
6177 return;
6178
Anna Zaks314cd092012-02-01 19:08:57 +00006179 // Identify common expressions, which are wrongly used as the size argument
6180 // to strncat and may lead to buffer overflows.
6181 unsigned PatternType = 0;
6182 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
6183 // - sizeof(dst)
6184 if (referToTheSameDecl(SizeOfArg, DstArg))
6185 PatternType = 1;
6186 // - sizeof(src)
6187 else if (referToTheSameDecl(SizeOfArg, SrcArg))
6188 PatternType = 2;
6189 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
6190 if (BE->getOpcode() == BO_Sub) {
6191 const Expr *L = BE->getLHS()->IgnoreParenCasts();
6192 const Expr *R = BE->getRHS()->IgnoreParenCasts();
6193 // - sizeof(dst) - strlen(dst)
6194 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
6195 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
6196 PatternType = 1;
6197 // - sizeof(src) - (anything)
6198 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
6199 PatternType = 2;
6200 }
6201 }
6202
6203 if (PatternType == 0)
6204 return;
6205
Anna Zaks5069aa32012-02-03 01:27:37 +00006206 // Generate the diagnostic.
6207 SourceLocation SL = LenArg->getLocStart();
6208 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00006209 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00006210
6211 // If the function is defined as a builtin macro, do not show macro expansion.
6212 if (SM.isMacroArgExpansion(SL)) {
6213 SL = SM.getSpellingLoc(SL);
6214 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
6215 SM.getSpellingLoc(SR.getEnd()));
6216 }
6217
Anna Zaks13b08572012-08-08 21:42:23 +00006218 // Check if the destination is an array (rather than a pointer to an array).
6219 QualType DstTy = DstArg->getType();
6220 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
6221 Context);
6222 if (!isKnownSizeArray) {
6223 if (PatternType == 1)
6224 Diag(SL, diag::warn_strncat_wrong_size) << SR;
6225 else
6226 Diag(SL, diag::warn_strncat_src_size) << SR;
6227 return;
6228 }
6229
Anna Zaks314cd092012-02-01 19:08:57 +00006230 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00006231 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00006232 else
Anna Zaks5069aa32012-02-03 01:27:37 +00006233 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00006234
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00006235 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00006236 llvm::raw_svector_ostream OS(sizeString);
6237 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00006238 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00006239 OS << ") - ";
6240 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00006241 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00006242 OS << ") - 1";
6243
Anna Zaks5069aa32012-02-03 01:27:37 +00006244 Diag(SL, diag::note_strncat_wrong_size)
6245 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00006246}
6247
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006248//===--- CHECK: Return Address of Stack Variable --------------------------===//
6249
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006250static const Expr *EvalVal(const Expr *E,
6251 SmallVectorImpl<const DeclRefExpr *> &refVars,
6252 const Decl *ParentDecl);
6253static const Expr *EvalAddr(const Expr *E,
6254 SmallVectorImpl<const DeclRefExpr *> &refVars,
6255 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006256
6257/// CheckReturnStackAddr - Check if a return statement returns the address
6258/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006259static void
6260CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
6261 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00006262
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006263 const Expr *stackE = nullptr;
6264 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006265
6266 // Perform checking for returned stack addresses, local blocks,
6267 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00006268 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006269 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006270 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00006271 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006272 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006273 }
6274
Craig Topperc3ec1492014-05-26 06:22:03 +00006275 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006276 return; // Nothing suspicious was found.
6277
6278 SourceLocation diagLoc;
6279 SourceRange diagRange;
6280 if (refVars.empty()) {
6281 diagLoc = stackE->getLocStart();
6282 diagRange = stackE->getSourceRange();
6283 } else {
6284 // We followed through a reference variable. 'stackE' contains the
6285 // problematic expression but we will warn at the return statement pointing
6286 // at the reference variable. We will later display the "trail" of
6287 // reference variables using notes.
6288 diagLoc = refVars[0]->getLocStart();
6289 diagRange = refVars[0]->getSourceRange();
6290 }
6291
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006292 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
6293 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00006294 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006295 << DR->getDecl()->getDeclName() << diagRange;
6296 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006297 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006298 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006299 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006300 } else { // local temporary.
Craig Topperda7b27f2015-11-17 05:40:09 +00006301 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
6302 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006303 }
6304
6305 // Display the "trail" of reference variables that we followed until we
6306 // found the problematic expression using notes.
6307 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006308 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006309 // If this var binds to another reference var, show the range of the next
6310 // var, otherwise the var binds to the problematic expression, in which case
6311 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006312 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
6313 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006314 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
6315 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006316 }
6317}
6318
6319/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
6320/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006321/// to a location on the stack, a local block, an address of a label, or a
6322/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006323/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006324/// encounter a subexpression that (1) clearly does not lead to one of the
6325/// above problematic expressions (2) is something we cannot determine leads to
6326/// a problematic expression based on such local checking.
6327///
6328/// Both EvalAddr and EvalVal follow through reference variables to evaluate
6329/// the expression that they point to. Such variables are added to the
6330/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006331///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00006332/// EvalAddr processes expressions that are pointers that are used as
6333/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006334/// At the base case of the recursion is a check for the above problematic
6335/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006336///
6337/// This implementation handles:
6338///
6339/// * pointer-to-pointer casts
6340/// * implicit conversions from array references to pointers
6341/// * taking the address of fields
6342/// * arbitrary interplay between "&" and "*" operators
6343/// * pointer arithmetic from an address of a stack variable
6344/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006345static const Expr *EvalAddr(const Expr *E,
6346 SmallVectorImpl<const DeclRefExpr *> &refVars,
6347 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006348 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00006349 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006350
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006351 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00006352 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00006353 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006354 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00006355 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00006356
Peter Collingbourne91147592011-04-15 00:35:48 +00006357 E = E->IgnoreParens();
6358
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006359 // Our "symbolic interpreter" is just a dispatch off the currently
6360 // viewed AST node. We then recursively traverse the AST by calling
6361 // EvalAddr and EvalVal appropriately.
6362 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006363 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006364 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006365
Richard Smith40f08eb2014-01-30 22:05:38 +00006366 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00006367 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00006368 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00006369
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006370 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006371 // If this is a reference variable, follow through to the expression that
6372 // it points to.
6373 if (V->hasLocalStorage() &&
6374 V->getType()->isReferenceType() && V->hasInit()) {
6375 // Add the reference variable to the "trail".
6376 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006377 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006378 }
6379
Craig Topperc3ec1492014-05-26 06:22:03 +00006380 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006381 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006382
Chris Lattner934edb22007-12-28 05:31:15 +00006383 case Stmt::UnaryOperatorClass: {
6384 // The only unary operator that make sense to handle here
6385 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006386 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006387
John McCalle3027922010-08-25 11:45:40 +00006388 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006389 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006390 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006391 }
Mike Stump11289f42009-09-09 15:08:12 +00006392
Chris Lattner934edb22007-12-28 05:31:15 +00006393 case Stmt::BinaryOperatorClass: {
6394 // Handle pointer arithmetic. All other binary operators are not valid
6395 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006396 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00006397 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00006398
John McCalle3027922010-08-25 11:45:40 +00006399 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00006400 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006401
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006402 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00006403
6404 // Determine which argument is the real pointer base. It could be
6405 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006406 if (!Base->getType()->isPointerType())
6407 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00006408
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006409 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006410 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00006411 }
Steve Naroff2752a172008-09-10 19:17:48 +00006412
Chris Lattner934edb22007-12-28 05:31:15 +00006413 // For conditional operators we need to see if either the LHS or RHS are
6414 // valid DeclRefExpr*s. If one of them is valid, we return it.
6415 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006416 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006417
Chris Lattner934edb22007-12-28 05:31:15 +00006418 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006419 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006420 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006421 // In C++, we can have a throw-expression, which has 'void' type.
6422 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006423 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006424 return LHS;
6425 }
Chris Lattner934edb22007-12-28 05:31:15 +00006426
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006427 // In C++, we can have a throw-expression, which has 'void' type.
6428 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00006429 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006430
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006431 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00006432 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006433
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006434 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00006435 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006436 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00006437 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006438
6439 case Stmt::AddrLabelExprClass:
6440 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00006441
John McCall28fc7092011-11-10 05:35:25 +00006442 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006443 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
6444 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00006445
Ted Kremenekc3b4c522008-08-07 00:49:01 +00006446 // For casts, we need to handle conversions from arrays to
6447 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00006448 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00006449 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00006450 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00006451 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00006452 case Stmt::CXXStaticCastExprClass:
6453 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00006454 case Stmt::CXXConstCastExprClass:
6455 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006456 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00006457 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00006458 case CK_LValueToRValue:
6459 case CK_NoOp:
6460 case CK_BaseToDerived:
6461 case CK_DerivedToBase:
6462 case CK_UncheckedDerivedToBase:
6463 case CK_Dynamic:
6464 case CK_CPointerToObjCPointerCast:
6465 case CK_BlockPointerToObjCPointerCast:
6466 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006467 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00006468
6469 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006470 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00006471
Richard Trieudadefde2014-07-02 04:39:38 +00006472 case CK_BitCast:
6473 if (SubExpr->getType()->isAnyPointerType() ||
6474 SubExpr->getType()->isBlockPointerType() ||
6475 SubExpr->getType()->isObjCQualifiedIdType())
6476 return EvalAddr(SubExpr, refVars, ParentDecl);
6477 else
6478 return nullptr;
6479
Eli Friedman8195ad72012-02-23 23:04:32 +00006480 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00006481 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00006482 }
Chris Lattner934edb22007-12-28 05:31:15 +00006483 }
Mike Stump11289f42009-09-09 15:08:12 +00006484
Douglas Gregorfe314812011-06-21 17:03:29 +00006485 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006486 if (const Expr *Result =
6487 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
6488 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00006489 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00006490 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006491
Chris Lattner934edb22007-12-28 05:31:15 +00006492 // Everything else: we simply don't reason about them.
6493 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00006494 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00006495 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006496}
Mike Stump11289f42009-09-09 15:08:12 +00006497
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006498/// EvalVal - This function is complements EvalAddr in the mutual recursion.
6499/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006500static const Expr *EvalVal(const Expr *E,
6501 SmallVectorImpl<const DeclRefExpr *> &refVars,
6502 const Decl *ParentDecl) {
6503 do {
6504 // We should only be called for evaluating non-pointer expressions, or
6505 // expressions with a pointer type that are not used as references but
6506 // instead
6507 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00006508
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006509 // Our "symbolic interpreter" is just a dispatch off the currently
6510 // viewed AST node. We then recursively traverse the AST by calling
6511 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00006512
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006513 E = E->IgnoreParens();
6514 switch (E->getStmtClass()) {
6515 case Stmt::ImplicitCastExprClass: {
6516 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
6517 if (IE->getValueKind() == VK_LValue) {
6518 E = IE->getSubExpr();
6519 continue;
6520 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006521 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006522 }
Richard Smith40f08eb2014-01-30 22:05:38 +00006523
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006524 case Stmt::ExprWithCleanupsClass:
6525 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
6526 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006527
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006528 case Stmt::DeclRefExprClass: {
6529 // When we hit a DeclRefExpr we are looking at code that refers to a
6530 // variable's name. If it's not a reference variable we check if it has
6531 // local storage within the function, and if so, return the expression.
6532 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6533
6534 // If we leave the immediate function, the lifetime isn't about to end.
6535 if (DR->refersToEnclosingVariableOrCapture())
6536 return nullptr;
6537
6538 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
6539 // Check if it refers to itself, e.g. "int& i = i;".
6540 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006541 return DR;
6542
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006543 if (V->hasLocalStorage()) {
6544 if (!V->getType()->isReferenceType())
6545 return DR;
6546
6547 // Reference variable, follow through to the expression that
6548 // it points to.
6549 if (V->hasInit()) {
6550 // Add the reference variable to the "trail".
6551 refVars.push_back(DR);
6552 return EvalVal(V->getInit(), refVars, V);
6553 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006554 }
6555 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006556
6557 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006558 }
Mike Stump11289f42009-09-09 15:08:12 +00006559
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006560 case Stmt::UnaryOperatorClass: {
6561 // The only unary operator that make sense to handle here
6562 // is Deref. All others don't resolve to a "name." This includes
6563 // handling all sorts of rvalues passed to a unary operator.
6564 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006565
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006566 if (U->getOpcode() == UO_Deref)
6567 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00006568
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006569 return nullptr;
6570 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006571
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006572 case Stmt::ArraySubscriptExprClass: {
6573 // Array subscripts are potential references to data on the stack. We
6574 // retrieve the DeclRefExpr* for the array variable if it indeed
6575 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00006576 const auto *ASE = cast<ArraySubscriptExpr>(E);
6577 if (ASE->isTypeDependent())
6578 return nullptr;
6579 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006580 }
Mike Stump11289f42009-09-09 15:08:12 +00006581
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006582 case Stmt::OMPArraySectionExprClass: {
6583 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
6584 ParentDecl);
6585 }
Mike Stump11289f42009-09-09 15:08:12 +00006586
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006587 case Stmt::ConditionalOperatorClass: {
6588 // For conditional operators we need to see if either the LHS or RHS are
6589 // non-NULL Expr's. If one is non-NULL, we return it.
6590 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00006591
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006592 // Handle the GNU extension for missing LHS.
6593 if (const Expr *LHSExpr = C->getLHS()) {
6594 // In C++, we can have a throw-expression, which has 'void' type.
6595 if (!LHSExpr->getType()->isVoidType())
6596 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
6597 return LHS;
6598 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006599
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006600 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006601 if (C->getRHS()->getType()->isVoidType())
6602 return nullptr;
6603
6604 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006605 }
6606
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006607 // Accesses to members are potential references to data on the stack.
6608 case Stmt::MemberExprClass: {
6609 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00006610
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006611 // Check for indirect access. We only want direct field accesses.
6612 if (M->isArrow())
6613 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006614
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006615 // Check whether the member type is itself a reference, in which case
6616 // we're not going to refer to the member, but to what the member refers
6617 // to.
6618 if (M->getMemberDecl()->getType()->isReferenceType())
6619 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006620
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006621 return EvalVal(M->getBase(), refVars, ParentDecl);
6622 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00006623
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006624 case Stmt::MaterializeTemporaryExprClass:
6625 if (const Expr *Result =
6626 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
6627 refVars, ParentDecl))
6628 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006629 return E;
6630
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006631 default:
6632 // Check that we don't return or take the address of a reference to a
6633 // temporary. This is only useful in C++.
6634 if (!E->isTypeDependent() && E->isRValue())
6635 return E;
6636
6637 // Everything else: we simply don't reason about them.
6638 return nullptr;
6639 }
6640 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006641}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006642
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006643void
6644Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
6645 SourceLocation ReturnLoc,
6646 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00006647 const AttrVec *Attrs,
6648 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006649 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
6650
6651 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00006652 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
6653 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00006654 CheckNonNullExpr(*this, RetValExp))
6655 Diag(ReturnLoc, diag::warn_null_ret)
6656 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00006657
6658 // C++11 [basic.stc.dynamic.allocation]p4:
6659 // If an allocation function declared with a non-throwing
6660 // exception-specification fails to allocate storage, it shall return
6661 // a null pointer. Any other allocation function that fails to allocate
6662 // storage shall indicate failure only by throwing an exception [...]
6663 if (FD) {
6664 OverloadedOperatorKind Op = FD->getOverloadedOperator();
6665 if (Op == OO_New || Op == OO_Array_New) {
6666 const FunctionProtoType *Proto
6667 = FD->getType()->castAs<FunctionProtoType>();
6668 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
6669 CheckNonNullExpr(*this, RetValExp))
6670 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
6671 << FD << getLangOpts().CPlusPlus11;
6672 }
6673 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006674}
6675
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006676//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
6677
6678/// Check for comparisons of floating point operands using != and ==.
6679/// Issue a warning if these are no self-comparisons, as they are not likely
6680/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00006681void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00006682 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
6683 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006684
6685 // Special case: check for x == x (which is OK).
6686 // Do not emit warnings for such cases.
6687 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
6688 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
6689 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00006690 return;
Mike Stump11289f42009-09-09 15:08:12 +00006691
Ted Kremenekeda40e22007-11-29 00:59:04 +00006692 // Special case: check for comparisons against literals that can be exactly
6693 // represented by APFloat. In such cases, do not emit a warning. This
6694 // is a heuristic: often comparison against such literals are used to
6695 // detect if a value in a variable has not changed. This clearly can
6696 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00006697 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
6698 if (FLL->isExact())
6699 return;
6700 } else
6701 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
6702 if (FLR->isExact())
6703 return;
Mike Stump11289f42009-09-09 15:08:12 +00006704
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006705 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00006706 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00006707 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00006708 return;
Mike Stump11289f42009-09-09 15:08:12 +00006709
David Blaikie1f4ff152012-07-16 20:47:22 +00006710 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00006711 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00006712 return;
Mike Stump11289f42009-09-09 15:08:12 +00006713
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006714 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00006715 Diag(Loc, diag::warn_floatingpoint_eq)
6716 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006717}
John McCallca01b222010-01-04 23:21:16 +00006718
John McCall70aa5392010-01-06 05:24:50 +00006719//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
6720//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00006721
John McCall70aa5392010-01-06 05:24:50 +00006722namespace {
John McCallca01b222010-01-04 23:21:16 +00006723
John McCall70aa5392010-01-06 05:24:50 +00006724/// Structure recording the 'active' range of an integer-valued
6725/// expression.
6726struct IntRange {
6727 /// The number of bits active in the int.
6728 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00006729
John McCall70aa5392010-01-06 05:24:50 +00006730 /// True if the int is known not to have negative values.
6731 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00006732
John McCall70aa5392010-01-06 05:24:50 +00006733 IntRange(unsigned Width, bool NonNegative)
6734 : Width(Width), NonNegative(NonNegative)
6735 {}
John McCallca01b222010-01-04 23:21:16 +00006736
John McCall817d4af2010-11-10 23:38:19 +00006737 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00006738 static IntRange forBoolType() {
6739 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00006740 }
6741
John McCall817d4af2010-11-10 23:38:19 +00006742 /// Returns the range of an opaque value of the given integral type.
6743 static IntRange forValueOfType(ASTContext &C, QualType T) {
6744 return forValueOfCanonicalType(C,
6745 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00006746 }
6747
John McCall817d4af2010-11-10 23:38:19 +00006748 /// Returns the range of an opaque value of a canonical integral type.
6749 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00006750 assert(T->isCanonicalUnqualified());
6751
6752 if (const VectorType *VT = dyn_cast<VectorType>(T))
6753 T = VT->getElementType().getTypePtr();
6754 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
6755 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00006756 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
6757 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00006758
David Majnemer6a426652013-06-07 22:07:20 +00006759 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00006760 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00006761 EnumDecl *Enum = ET->getDecl();
6762 if (!Enum->isCompleteDefinition())
6763 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00006764
David Majnemer6a426652013-06-07 22:07:20 +00006765 unsigned NumPositive = Enum->getNumPositiveBits();
6766 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00006767
David Majnemer6a426652013-06-07 22:07:20 +00006768 if (NumNegative == 0)
6769 return IntRange(NumPositive, true/*NonNegative*/);
6770 else
6771 return IntRange(std::max(NumPositive + 1, NumNegative),
6772 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00006773 }
John McCall70aa5392010-01-06 05:24:50 +00006774
6775 const BuiltinType *BT = cast<BuiltinType>(T);
6776 assert(BT->isInteger());
6777
6778 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
6779 }
6780
John McCall817d4af2010-11-10 23:38:19 +00006781 /// Returns the "target" range of a canonical integral type, i.e.
6782 /// the range of values expressible in the type.
6783 ///
6784 /// This matches forValueOfCanonicalType except that enums have the
6785 /// full range of their type, not the range of their enumerators.
6786 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
6787 assert(T->isCanonicalUnqualified());
6788
6789 if (const VectorType *VT = dyn_cast<VectorType>(T))
6790 T = VT->getElementType().getTypePtr();
6791 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
6792 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00006793 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
6794 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00006795 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00006796 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00006797
6798 const BuiltinType *BT = cast<BuiltinType>(T);
6799 assert(BT->isInteger());
6800
6801 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
6802 }
6803
6804 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00006805 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00006806 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00006807 L.NonNegative && R.NonNegative);
6808 }
6809
John McCall817d4af2010-11-10 23:38:19 +00006810 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00006811 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00006812 return IntRange(std::min(L.Width, R.Width),
6813 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00006814 }
6815};
6816
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006817IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006818 if (value.isSigned() && value.isNegative())
6819 return IntRange(value.getMinSignedBits(), false);
6820
6821 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00006822 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00006823
6824 // isNonNegative() just checks the sign bit without considering
6825 // signedness.
6826 return IntRange(value.getActiveBits(), true);
6827}
6828
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006829IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
6830 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006831 if (result.isInt())
6832 return GetValueRange(C, result.getInt(), MaxWidth);
6833
6834 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00006835 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
6836 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
6837 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
6838 R = IntRange::join(R, El);
6839 }
John McCall70aa5392010-01-06 05:24:50 +00006840 return R;
6841 }
6842
6843 if (result.isComplexInt()) {
6844 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
6845 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
6846 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00006847 }
6848
6849 // This can happen with lossless casts to intptr_t of "based" lvalues.
6850 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00006851 // FIXME: The only reason we need to pass the type in here is to get
6852 // the sign right on this one case. It would be nice if APValue
6853 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006854 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00006855 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00006856}
John McCall70aa5392010-01-06 05:24:50 +00006857
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006858QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00006859 QualType Ty = E->getType();
6860 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
6861 Ty = AtomicRHS->getValueType();
6862 return Ty;
6863}
6864
John McCall70aa5392010-01-06 05:24:50 +00006865/// Pseudo-evaluate the given integer expression, estimating the
6866/// range of values it might take.
6867///
6868/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006869IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006870 E = E->IgnoreParens();
6871
6872 // Try a full evaluation first.
6873 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00006874 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00006875 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00006876
6877 // I think we only want to look through implicit casts here; if the
6878 // user has an explicit widening cast, we should treat the value as
6879 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006880 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00006881 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00006882 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
6883
Eli Friedmane6d33952013-07-08 20:20:06 +00006884 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00006885
George Burgess IVdf1ed002016-01-13 01:52:39 +00006886 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
6887 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00006888
John McCall70aa5392010-01-06 05:24:50 +00006889 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00006890 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00006891 return OutputTypeRange;
6892
6893 IntRange SubRange
6894 = GetExprRange(C, CE->getSubExpr(),
6895 std::min(MaxWidth, OutputTypeRange.Width));
6896
6897 // Bail out if the subexpr's range is as wide as the cast type.
6898 if (SubRange.Width >= OutputTypeRange.Width)
6899 return OutputTypeRange;
6900
6901 // Otherwise, we take the smaller width, and we're non-negative if
6902 // either the output type or the subexpr is.
6903 return IntRange(SubRange.Width,
6904 SubRange.NonNegative || OutputTypeRange.NonNegative);
6905 }
6906
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006907 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00006908 // If we can fold the condition, just take that operand.
6909 bool CondResult;
6910 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
6911 return GetExprRange(C, CondResult ? CO->getTrueExpr()
6912 : CO->getFalseExpr(),
6913 MaxWidth);
6914
6915 // Otherwise, conservatively merge.
6916 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
6917 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
6918 return IntRange::join(L, R);
6919 }
6920
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006921 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00006922 switch (BO->getOpcode()) {
6923
6924 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00006925 case BO_LAnd:
6926 case BO_LOr:
6927 case BO_LT:
6928 case BO_GT:
6929 case BO_LE:
6930 case BO_GE:
6931 case BO_EQ:
6932 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00006933 return IntRange::forBoolType();
6934
John McCallc3688382011-07-13 06:35:24 +00006935 // The type of the assignments is the type of the LHS, so the RHS
6936 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00006937 case BO_MulAssign:
6938 case BO_DivAssign:
6939 case BO_RemAssign:
6940 case BO_AddAssign:
6941 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00006942 case BO_XorAssign:
6943 case BO_OrAssign:
6944 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00006945 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00006946
John McCallc3688382011-07-13 06:35:24 +00006947 // Simple assignments just pass through the RHS, which will have
6948 // been coerced to the LHS type.
6949 case BO_Assign:
6950 // TODO: bitfields?
6951 return GetExprRange(C, BO->getRHS(), MaxWidth);
6952
John McCall70aa5392010-01-06 05:24:50 +00006953 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00006954 case BO_PtrMemD:
6955 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00006956 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006957
John McCall2ce81ad2010-01-06 22:07:33 +00006958 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00006959 case BO_And:
6960 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00006961 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
6962 GetExprRange(C, BO->getRHS(), MaxWidth));
6963
John McCall70aa5392010-01-06 05:24:50 +00006964 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00006965 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00006966 // ...except that we want to treat '1 << (blah)' as logically
6967 // positive. It's an important idiom.
6968 if (IntegerLiteral *I
6969 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
6970 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00006971 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00006972 return IntRange(R.Width, /*NonNegative*/ true);
6973 }
6974 }
6975 // fallthrough
6976
John McCalle3027922010-08-25 11:45:40 +00006977 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00006978 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006979
John McCall2ce81ad2010-01-06 22:07:33 +00006980 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00006981 case BO_Shr:
6982 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00006983 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
6984
6985 // If the shift amount is a positive constant, drop the width by
6986 // that much.
6987 llvm::APSInt shift;
6988 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
6989 shift.isNonNegative()) {
6990 unsigned zext = shift.getZExtValue();
6991 if (zext >= L.Width)
6992 L.Width = (L.NonNegative ? 0 : 1);
6993 else
6994 L.Width -= zext;
6995 }
6996
6997 return L;
6998 }
6999
7000 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00007001 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00007002 return GetExprRange(C, BO->getRHS(), MaxWidth);
7003
John McCall2ce81ad2010-01-06 22:07:33 +00007004 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00007005 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00007006 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00007007 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00007008 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007009
John McCall51431812011-07-14 22:39:48 +00007010 // The width of a division result is mostly determined by the size
7011 // of the LHS.
7012 case BO_Div: {
7013 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00007014 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00007015 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
7016
7017 // If the divisor is constant, use that.
7018 llvm::APSInt divisor;
7019 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
7020 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
7021 if (log2 >= L.Width)
7022 L.Width = (L.NonNegative ? 0 : 1);
7023 else
7024 L.Width = std::min(L.Width - log2, MaxWidth);
7025 return L;
7026 }
7027
7028 // Otherwise, just use the LHS's width.
7029 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
7030 return IntRange(L.Width, L.NonNegative && R.NonNegative);
7031 }
7032
7033 // The result of a remainder can't be larger than the result of
7034 // either side.
7035 case BO_Rem: {
7036 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00007037 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00007038 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
7039 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
7040
7041 IntRange meet = IntRange::meet(L, R);
7042 meet.Width = std::min(meet.Width, MaxWidth);
7043 return meet;
7044 }
7045
7046 // The default behavior is okay for these.
7047 case BO_Mul:
7048 case BO_Add:
7049 case BO_Xor:
7050 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00007051 break;
7052 }
7053
John McCall51431812011-07-14 22:39:48 +00007054 // The default case is to treat the operation as if it were closed
7055 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00007056 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
7057 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
7058 return IntRange::join(L, R);
7059 }
7060
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007061 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00007062 switch (UO->getOpcode()) {
7063 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00007064 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00007065 return IntRange::forBoolType();
7066
7067 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00007068 case UO_Deref:
7069 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00007070 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00007071
7072 default:
7073 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
7074 }
7075 }
7076
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007077 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00007078 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
7079
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007080 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00007081 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00007082 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00007083
Eli Friedmane6d33952013-07-08 20:20:06 +00007084 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00007085}
John McCall263a48b2010-01-04 23:31:57 +00007086
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007087IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00007088 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00007089}
7090
John McCall263a48b2010-01-04 23:31:57 +00007091/// Checks whether the given value, which currently has the given
7092/// source semantics, has the same value when coerced through the
7093/// target semantics.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007094bool IsSameFloatAfterCast(const llvm::APFloat &value,
7095 const llvm::fltSemantics &Src,
7096 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00007097 llvm::APFloat truncated = value;
7098
7099 bool ignored;
7100 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
7101 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
7102
7103 return truncated.bitwiseIsEqual(value);
7104}
7105
7106/// Checks whether the given value, which currently has the given
7107/// source semantics, has the same value when coerced through the
7108/// target semantics.
7109///
7110/// The value might be a vector of floats (or a complex number).
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007111bool IsSameFloatAfterCast(const APValue &value,
7112 const llvm::fltSemantics &Src,
7113 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00007114 if (value.isFloat())
7115 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
7116
7117 if (value.isVector()) {
7118 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
7119 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
7120 return false;
7121 return true;
7122 }
7123
7124 assert(value.isComplexFloat());
7125 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
7126 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
7127}
7128
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007129void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007130
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007131bool IsZero(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00007132 // Suppress cases where we are comparing against an enum constant.
7133 if (const DeclRefExpr *DR =
7134 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
7135 if (isa<EnumConstantDecl>(DR->getDecl()))
7136 return false;
7137
7138 // Suppress cases where the '0' value is expanded from a macro.
7139 if (E->getLocStart().isMacroID())
7140 return false;
7141
John McCallcc7e5bf2010-05-06 08:58:33 +00007142 llvm::APSInt Value;
7143 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
7144}
7145
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007146bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00007147 // Strip off implicit integral promotions.
7148 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00007149 if (ICE->getCastKind() != CK_IntegralCast &&
7150 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00007151 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00007152 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00007153 }
7154
7155 return E->getType()->isEnumeralType();
7156}
7157
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007158void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00007159 // Disable warning in template instantiations.
7160 if (!S.ActiveTemplateInstantiations.empty())
7161 return;
7162
John McCalle3027922010-08-25 11:45:40 +00007163 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00007164 if (E->isValueDependent())
7165 return;
7166
John McCalle3027922010-08-25 11:45:40 +00007167 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007168 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00007169 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00007170 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00007171 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007172 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00007173 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00007174 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00007175 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007176 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00007177 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00007178 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00007179 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007180 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00007181 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00007182 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
7183 }
7184}
7185
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007186void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
7187 Expr *Constant, Expr *Other,
7188 llvm::APSInt Value,
7189 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00007190 // Disable warning in template instantiations.
7191 if (!S.ActiveTemplateInstantiations.empty())
7192 return;
7193
Richard Trieu0f097742014-04-04 04:13:47 +00007194 // TODO: Investigate using GetExprRange() to get tighter bounds
7195 // on the bit ranges.
7196 QualType OtherT = Other->getType();
David Majnemer7800f1f2015-05-23 01:32:17 +00007197 if (const auto *AT = OtherT->getAs<AtomicType>())
Justin Bogner4f42fc42014-07-21 18:01:53 +00007198 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00007199 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
7200 unsigned OtherWidth = OtherRange.Width;
7201
7202 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
7203
Richard Trieu560910c2012-11-14 22:50:24 +00007204 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00007205 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00007206 return;
7207
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007208 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00007209 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00007210
Richard Trieu0f097742014-04-04 04:13:47 +00007211 // Used for diagnostic printout.
7212 enum {
7213 LiteralConstant = 0,
7214 CXXBoolLiteralTrue,
7215 CXXBoolLiteralFalse
7216 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00007217
Richard Trieu0f097742014-04-04 04:13:47 +00007218 if (!OtherIsBooleanType) {
7219 QualType ConstantT = Constant->getType();
7220 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00007221
Richard Trieu0f097742014-04-04 04:13:47 +00007222 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
7223 return;
7224 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
7225 "comparison with non-integer type");
7226
7227 bool ConstantSigned = ConstantT->isSignedIntegerType();
7228 bool CommonSigned = CommonT->isSignedIntegerType();
7229
7230 bool EqualityOnly = false;
7231
7232 if (CommonSigned) {
7233 // The common type is signed, therefore no signed to unsigned conversion.
7234 if (!OtherRange.NonNegative) {
7235 // Check that the constant is representable in type OtherT.
7236 if (ConstantSigned) {
7237 if (OtherWidth >= Value.getMinSignedBits())
7238 return;
7239 } else { // !ConstantSigned
7240 if (OtherWidth >= Value.getActiveBits() + 1)
7241 return;
7242 }
7243 } else { // !OtherSigned
7244 // Check that the constant is representable in type OtherT.
7245 // Negative values are out of range.
7246 if (ConstantSigned) {
7247 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
7248 return;
7249 } else { // !ConstantSigned
7250 if (OtherWidth >= Value.getActiveBits())
7251 return;
7252 }
Richard Trieu560910c2012-11-14 22:50:24 +00007253 }
Richard Trieu0f097742014-04-04 04:13:47 +00007254 } else { // !CommonSigned
7255 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00007256 if (OtherWidth >= Value.getActiveBits())
7257 return;
Craig Toppercf360162014-06-18 05:13:11 +00007258 } else { // OtherSigned
7259 assert(!ConstantSigned &&
7260 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00007261 // Check to see if the constant is representable in OtherT.
7262 if (OtherWidth > Value.getActiveBits())
7263 return;
7264 // Check to see if the constant is equivalent to a negative value
7265 // cast to CommonT.
7266 if (S.Context.getIntWidth(ConstantT) ==
7267 S.Context.getIntWidth(CommonT) &&
7268 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
7269 return;
7270 // The constant value rests between values that OtherT can represent
7271 // after conversion. Relational comparison still works, but equality
7272 // comparisons will be tautological.
7273 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00007274 }
7275 }
Richard Trieu0f097742014-04-04 04:13:47 +00007276
7277 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
7278
7279 if (op == BO_EQ || op == BO_NE) {
7280 IsTrue = op == BO_NE;
7281 } else if (EqualityOnly) {
7282 return;
7283 } else if (RhsConstant) {
7284 if (op == BO_GT || op == BO_GE)
7285 IsTrue = !PositiveConstant;
7286 else // op == BO_LT || op == BO_LE
7287 IsTrue = PositiveConstant;
7288 } else {
7289 if (op == BO_LT || op == BO_LE)
7290 IsTrue = !PositiveConstant;
7291 else // op == BO_GT || op == BO_GE
7292 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00007293 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007294 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00007295 // Other isKnownToHaveBooleanValue
7296 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
7297 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
7298 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
7299
7300 static const struct LinkedConditions {
7301 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
7302 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
7303 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
7304 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
7305 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
7306 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
7307
7308 } TruthTable = {
7309 // Constant on LHS. | Constant on RHS. |
7310 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
7311 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
7312 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
7313 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
7314 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
7315 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
7316 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
7317 };
7318
7319 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
7320
7321 enum ConstantValue ConstVal = Zero;
7322 if (Value.isUnsigned() || Value.isNonNegative()) {
7323 if (Value == 0) {
7324 LiteralOrBoolConstant =
7325 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
7326 ConstVal = Zero;
7327 } else if (Value == 1) {
7328 LiteralOrBoolConstant =
7329 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
7330 ConstVal = One;
7331 } else {
7332 LiteralOrBoolConstant = LiteralConstant;
7333 ConstVal = GT_One;
7334 }
7335 } else {
7336 ConstVal = LT_Zero;
7337 }
7338
7339 CompareBoolWithConstantResult CmpRes;
7340
7341 switch (op) {
7342 case BO_LT:
7343 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
7344 break;
7345 case BO_GT:
7346 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
7347 break;
7348 case BO_LE:
7349 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
7350 break;
7351 case BO_GE:
7352 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
7353 break;
7354 case BO_EQ:
7355 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
7356 break;
7357 case BO_NE:
7358 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
7359 break;
7360 default:
7361 CmpRes = Unkwn;
7362 break;
7363 }
7364
7365 if (CmpRes == AFals) {
7366 IsTrue = false;
7367 } else if (CmpRes == ATrue) {
7368 IsTrue = true;
7369 } else {
7370 return;
7371 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007372 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00007373
7374 // If this is a comparison to an enum constant, include that
7375 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00007376 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00007377 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
7378 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
7379
7380 SmallString<64> PrettySourceValue;
7381 llvm::raw_svector_ostream OS(PrettySourceValue);
7382 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00007383 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00007384 else
7385 OS << Value;
7386
Richard Trieu0f097742014-04-04 04:13:47 +00007387 S.DiagRuntimeBehavior(
7388 E->getOperatorLoc(), E,
7389 S.PDiag(diag::warn_out_of_range_compare)
7390 << OS.str() << LiteralOrBoolConstant
7391 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
7392 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007393}
7394
John McCallcc7e5bf2010-05-06 08:58:33 +00007395/// Analyze the operands of the given comparison. Implements the
7396/// fallback case from AnalyzeComparison.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007397void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00007398 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
7399 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00007400}
John McCall263a48b2010-01-04 23:31:57 +00007401
John McCallca01b222010-01-04 23:21:16 +00007402/// \brief Implements -Wsign-compare.
7403///
Richard Trieu82402a02011-09-15 21:56:47 +00007404/// \param E the binary operator to check for warnings
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007405void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007406 // The type the comparison is being performed in.
7407 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00007408
7409 // Only analyze comparison operators where both sides have been converted to
7410 // the same type.
7411 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
7412 return AnalyzeImpConvsInComparison(S, E);
7413
7414 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00007415 if (E->isValueDependent())
7416 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007417
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007418 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
7419 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007420
7421 bool IsComparisonConstant = false;
7422
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007423 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007424 // of 'true' or 'false'.
7425 if (T->isIntegralType(S.Context)) {
7426 llvm::APSInt RHSValue;
7427 bool IsRHSIntegralLiteral =
7428 RHS->isIntegerConstantExpr(RHSValue, S.Context);
7429 llvm::APSInt LHSValue;
7430 bool IsLHSIntegralLiteral =
7431 LHS->isIntegerConstantExpr(LHSValue, S.Context);
7432 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
7433 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
7434 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
7435 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
7436 else
7437 IsComparisonConstant =
7438 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007439 } else if (!T->hasUnsignedIntegerRepresentation())
7440 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007441
John McCallcc7e5bf2010-05-06 08:58:33 +00007442 // We don't do anything special if this isn't an unsigned integral
7443 // comparison: we're only interested in integral comparisons, and
7444 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00007445 //
7446 // We also don't care about value-dependent expressions or expressions
7447 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007448 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00007449 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007450
John McCallcc7e5bf2010-05-06 08:58:33 +00007451 // Check to see if one of the (unmodified) operands is of different
7452 // signedness.
7453 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00007454 if (LHS->getType()->hasSignedIntegerRepresentation()) {
7455 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00007456 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00007457 signedOperand = LHS;
7458 unsignedOperand = RHS;
7459 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
7460 signedOperand = RHS;
7461 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00007462 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00007463 CheckTrivialUnsignedComparison(S, E);
7464 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007465 }
7466
John McCallcc7e5bf2010-05-06 08:58:33 +00007467 // Otherwise, calculate the effective range of the signed operand.
7468 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00007469
John McCallcc7e5bf2010-05-06 08:58:33 +00007470 // Go ahead and analyze implicit conversions in the operands. Note
7471 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00007472 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
7473 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00007474
John McCallcc7e5bf2010-05-06 08:58:33 +00007475 // If the signed range is non-negative, -Wsign-compare won't fire,
7476 // but we should still check for comparisons which are always true
7477 // or false.
7478 if (signedRange.NonNegative)
7479 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007480
7481 // For (in)equality comparisons, if the unsigned operand is a
7482 // constant which cannot collide with a overflowed signed operand,
7483 // then reinterpreting the signed operand as unsigned will not
7484 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00007485 if (E->isEqualityOp()) {
7486 unsigned comparisonWidth = S.Context.getIntWidth(T);
7487 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00007488
John McCallcc7e5bf2010-05-06 08:58:33 +00007489 // We should never be unable to prove that the unsigned operand is
7490 // non-negative.
7491 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
7492
7493 if (unsignedRange.Width < comparisonWidth)
7494 return;
7495 }
7496
Douglas Gregorbfb4a212012-05-01 01:53:49 +00007497 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
7498 S.PDiag(diag::warn_mixed_sign_comparison)
7499 << LHS->getType() << RHS->getType()
7500 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00007501}
7502
John McCall1f425642010-11-11 03:21:53 +00007503/// Analyzes an attempt to assign the given value to a bitfield.
7504///
7505/// Returns true if there was something fishy about the attempt.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007506bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
7507 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00007508 assert(Bitfield->isBitField());
7509 if (Bitfield->isInvalidDecl())
7510 return false;
7511
John McCalldeebbcf2010-11-11 05:33:51 +00007512 // White-list bool bitfields.
7513 if (Bitfield->getType()->isBooleanType())
7514 return false;
7515
Douglas Gregor789adec2011-02-04 13:09:01 +00007516 // Ignore value- or type-dependent expressions.
7517 if (Bitfield->getBitWidth()->isValueDependent() ||
7518 Bitfield->getBitWidth()->isTypeDependent() ||
7519 Init->isValueDependent() ||
7520 Init->isTypeDependent())
7521 return false;
7522
John McCall1f425642010-11-11 03:21:53 +00007523 Expr *OriginalInit = Init->IgnoreParenImpCasts();
7524
Richard Smith5fab0c92011-12-28 19:48:30 +00007525 llvm::APSInt Value;
7526 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00007527 return false;
7528
John McCall1f425642010-11-11 03:21:53 +00007529 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00007530 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00007531
7532 if (OriginalWidth <= FieldWidth)
7533 return false;
7534
Eli Friedmanc267a322012-01-26 23:11:39 +00007535 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00007536 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00007537 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00007538
Eli Friedmanc267a322012-01-26 23:11:39 +00007539 // Check whether the stored value is equal to the original value.
7540 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00007541 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00007542 return false;
7543
Eli Friedmanc267a322012-01-26 23:11:39 +00007544 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00007545 // therefore don't strictly fit into a signed bitfield of width 1.
7546 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00007547 return false;
7548
John McCall1f425642010-11-11 03:21:53 +00007549 std::string PrettyValue = Value.toString(10);
7550 std::string PrettyTrunc = TruncatedValue.toString(10);
7551
7552 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
7553 << PrettyValue << PrettyTrunc << OriginalInit->getType()
7554 << Init->getSourceRange();
7555
7556 return true;
7557}
7558
John McCalld2a53122010-11-09 23:24:47 +00007559/// Analyze the given simple or compound assignment for warning-worthy
7560/// operations.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007561void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00007562 // Just recurse on the LHS.
7563 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
7564
7565 // We want to recurse on the RHS as normal unless we're assigning to
7566 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00007567 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007568 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00007569 E->getOperatorLoc())) {
7570 // Recurse, ignoring any implicit conversions on the RHS.
7571 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
7572 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00007573 }
7574 }
7575
7576 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
7577}
7578
John McCall263a48b2010-01-04 23:31:57 +00007579/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007580void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
7581 SourceLocation CContext, unsigned diag,
7582 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00007583 if (pruneControlFlow) {
7584 S.DiagRuntimeBehavior(E->getExprLoc(), E,
7585 S.PDiag(diag)
7586 << SourceType << T << E->getSourceRange()
7587 << SourceRange(CContext));
7588 return;
7589 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00007590 S.Diag(E->getExprLoc(), diag)
7591 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
7592}
7593
Chandler Carruth7f3654f2011-04-05 06:47:57 +00007594/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007595void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
7596 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00007597 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00007598}
7599
Richard Trieube234c32016-04-21 21:04:55 +00007600
7601/// Diagnose an implicit cast from a floating point value to an integer value.
7602void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
7603
7604 SourceLocation CContext) {
7605 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
7606 const bool PruneWarnings = !S.ActiveTemplateInstantiations.empty();
7607
7608 Expr *InnerE = E->IgnoreParenImpCasts();
7609 // We also want to warn on, e.g., "int i = -1.234"
7610 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
7611 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
7612 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
7613
7614 const bool IsLiteral =
7615 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
7616
7617 llvm::APFloat Value(0.0);
7618 bool IsConstant =
7619 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
7620 if (!IsConstant) {
Richard Trieu891f0f12016-04-22 22:14:32 +00007621 return DiagnoseImpCast(S, E, T, CContext,
7622 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +00007623 }
7624
Chandler Carruth016ef402011-04-10 08:36:24 +00007625 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +00007626
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00007627 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
7628 T->hasUnsignedIntegerRepresentation());
Richard Trieube234c32016-04-21 21:04:55 +00007629 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
7630 &isExact) == llvm::APFloat::opOK &&
Richard Trieu891f0f12016-04-22 22:14:32 +00007631 isExact) {
Richard Trieube234c32016-04-21 21:04:55 +00007632 if (IsLiteral) return;
7633 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
7634 PruneWarnings);
7635 }
7636
7637 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +00007638 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +00007639 // Warn on floating point literal to integer.
7640 DiagID = diag::warn_impcast_literal_float_to_integer;
7641 } else if (IntegerValue == 0) {
7642 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
7643 return DiagnoseImpCast(S, E, T, CContext,
7644 diag::warn_impcast_float_integer, PruneWarnings);
7645 }
7646 // Warn on non-zero to zero conversion.
7647 DiagID = diag::warn_impcast_float_to_integer_zero;
7648 } else {
7649 if (IntegerValue.isUnsigned()) {
7650 if (!IntegerValue.isMaxValue()) {
7651 return DiagnoseImpCast(S, E, T, CContext,
7652 diag::warn_impcast_float_integer, PruneWarnings);
7653 }
7654 } else { // IntegerValue.isSigned()
7655 if (!IntegerValue.isMaxSignedValue() &&
7656 !IntegerValue.isMinSignedValue()) {
7657 return DiagnoseImpCast(S, E, T, CContext,
7658 diag::warn_impcast_float_integer, PruneWarnings);
7659 }
7660 }
7661 // Warn on evaluatable floating point expression to integer conversion.
7662 DiagID = diag::warn_impcast_float_to_integer;
7663 }
Chandler Carruth016ef402011-04-10 08:36:24 +00007664
Eli Friedman07185912013-08-29 23:44:43 +00007665 // FIXME: Force the precision of the source value down so we don't print
7666 // digits which are usually useless (we don't really care here if we
7667 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
7668 // would automatically print the shortest representation, but it's a bit
7669 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00007670 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00007671 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
7672 precision = (precision * 59 + 195) / 196;
7673 Value.toString(PrettySourceValue, precision);
7674
David Blaikie9b88cc02012-05-15 17:18:27 +00007675 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +00007676 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +00007677 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00007678 else
David Blaikie9b88cc02012-05-15 17:18:27 +00007679 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00007680
Richard Trieube234c32016-04-21 21:04:55 +00007681 if (PruneWarnings) {
7682 S.DiagRuntimeBehavior(E->getExprLoc(), E,
7683 S.PDiag(DiagID)
7684 << E->getType() << T.getUnqualifiedType()
7685 << PrettySourceValue << PrettyTargetValue
7686 << E->getSourceRange() << SourceRange(CContext));
7687 } else {
7688 S.Diag(E->getExprLoc(), DiagID)
7689 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
7690 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
7691 }
Chandler Carruth016ef402011-04-10 08:36:24 +00007692}
7693
John McCall18a2c2c2010-11-09 22:22:12 +00007694std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
7695 if (!Range.Width) return "0";
7696
7697 llvm::APSInt ValueInRange = Value;
7698 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00007699 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00007700 return ValueInRange.toString(10);
7701}
7702
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007703bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007704 if (!isa<ImplicitCastExpr>(Ex))
7705 return false;
7706
7707 Expr *InnerE = Ex->IgnoreParenImpCasts();
7708 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
7709 const Type *Source =
7710 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
7711 if (Target->isDependentType())
7712 return false;
7713
7714 const BuiltinType *FloatCandidateBT =
7715 dyn_cast<BuiltinType>(ToBool ? Source : Target);
7716 const Type *BoolCandidateType = ToBool ? Target : Source;
7717
7718 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
7719 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
7720}
7721
7722void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
7723 SourceLocation CC) {
7724 unsigned NumArgs = TheCall->getNumArgs();
7725 for (unsigned i = 0; i < NumArgs; ++i) {
7726 Expr *CurrA = TheCall->getArg(i);
7727 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
7728 continue;
7729
7730 bool IsSwapped = ((i > 0) &&
7731 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
7732 IsSwapped |= ((i < (NumArgs - 1)) &&
7733 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
7734 if (IsSwapped) {
7735 // Warn on this floating-point to bool conversion.
7736 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
7737 CurrA->getType(), CC,
7738 diag::warn_impcast_floating_point_to_bool);
7739 }
7740 }
7741}
7742
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007743void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00007744 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
7745 E->getExprLoc()))
7746 return;
7747
Richard Trieu09d6b802016-01-08 23:35:06 +00007748 // Don't warn on functions which have return type nullptr_t.
7749 if (isa<CallExpr>(E))
7750 return;
7751
Richard Trieu5b993502014-10-15 03:42:06 +00007752 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
7753 const Expr::NullPointerConstantKind NullKind =
7754 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
7755 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
7756 return;
7757
7758 // Return if target type is a safe conversion.
7759 if (T->isAnyPointerType() || T->isBlockPointerType() ||
7760 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
7761 return;
7762
7763 SourceLocation Loc = E->getSourceRange().getBegin();
7764
Richard Trieu0a5e1662016-02-13 00:58:53 +00007765 // Venture through the macro stacks to get to the source of macro arguments.
7766 // The new location is a better location than the complete location that was
7767 // passed in.
7768 while (S.SourceMgr.isMacroArgExpansion(Loc))
7769 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
7770
7771 while (S.SourceMgr.isMacroArgExpansion(CC))
7772 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
7773
Richard Trieu5b993502014-10-15 03:42:06 +00007774 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +00007775 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
7776 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
7777 Loc, S.SourceMgr, S.getLangOpts());
7778 if (MacroName == "NULL")
7779 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
Richard Trieu5b993502014-10-15 03:42:06 +00007780 }
7781
7782 // Only warn if the null and context location are in the same macro expansion.
7783 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
7784 return;
7785
7786 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
7787 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
7788 << FixItHint::CreateReplacement(Loc,
7789 S.getFixItZeroLiteralForType(T, Loc));
7790}
7791
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007792void checkObjCArrayLiteral(Sema &S, QualType TargetType,
7793 ObjCArrayLiteral *ArrayLiteral);
7794void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
7795 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +00007796
7797/// Check a single element within a collection literal against the
7798/// target element type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007799void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
7800 Expr *Element, unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00007801 // Skip a bitcast to 'id' or qualified 'id'.
7802 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
7803 if (ICE->getCastKind() == CK_BitCast &&
7804 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
7805 Element = ICE->getSubExpr();
7806 }
7807
7808 QualType ElementType = Element->getType();
7809 ExprResult ElementResult(Element);
7810 if (ElementType->getAs<ObjCObjectPointerType>() &&
7811 S.CheckSingleAssignmentConstraints(TargetElementType,
7812 ElementResult,
7813 false, false)
7814 != Sema::Compatible) {
7815 S.Diag(Element->getLocStart(),
7816 diag::warn_objc_collection_literal_element)
7817 << ElementType << ElementKind << TargetElementType
7818 << Element->getSourceRange();
7819 }
7820
7821 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
7822 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
7823 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
7824 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
7825}
7826
7827/// Check an Objective-C array literal being converted to the given
7828/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007829void checkObjCArrayLiteral(Sema &S, QualType TargetType,
7830 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00007831 if (!S.NSArrayDecl)
7832 return;
7833
7834 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
7835 if (!TargetObjCPtr)
7836 return;
7837
7838 if (TargetObjCPtr->isUnspecialized() ||
7839 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
7840 != S.NSArrayDecl->getCanonicalDecl())
7841 return;
7842
7843 auto TypeArgs = TargetObjCPtr->getTypeArgs();
7844 if (TypeArgs.size() != 1)
7845 return;
7846
7847 QualType TargetElementType = TypeArgs[0];
7848 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
7849 checkObjCCollectionLiteralElement(S, TargetElementType,
7850 ArrayLiteral->getElement(I),
7851 0);
7852 }
7853}
7854
7855/// Check an Objective-C dictionary literal being converted to the given
7856/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007857void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
7858 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00007859 if (!S.NSDictionaryDecl)
7860 return;
7861
7862 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
7863 if (!TargetObjCPtr)
7864 return;
7865
7866 if (TargetObjCPtr->isUnspecialized() ||
7867 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
7868 != S.NSDictionaryDecl->getCanonicalDecl())
7869 return;
7870
7871 auto TypeArgs = TargetObjCPtr->getTypeArgs();
7872 if (TypeArgs.size() != 2)
7873 return;
7874
7875 QualType TargetKeyType = TypeArgs[0];
7876 QualType TargetObjectType = TypeArgs[1];
7877 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
7878 auto Element = DictionaryLiteral->getKeyValueElement(I);
7879 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
7880 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
7881 }
7882}
7883
Richard Trieufc404c72016-02-05 23:02:38 +00007884// Helper function to filter out cases for constant width constant conversion.
7885// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007886bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
7887 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +00007888 // If initializing from a constant, and the constant starts with '0',
7889 // then it is a binary, octal, or hexadecimal. Allow these constants
7890 // to fill all the bits, even if there is a sign change.
7891 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
7892 const char FirstLiteralCharacter =
7893 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
7894 if (FirstLiteralCharacter == '0')
7895 return false;
7896 }
7897
7898 // If the CC location points to a '{', and the type is char, then assume
7899 // assume it is an array initialization.
7900 if (CC.isValid() && T->isCharType()) {
7901 const char FirstContextCharacter =
7902 S.getSourceManager().getCharacterData(CC)[0];
7903 if (FirstContextCharacter == '{')
7904 return false;
7905 }
7906
7907 return true;
7908}
7909
John McCallcc7e5bf2010-05-06 08:58:33 +00007910void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00007911 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007912 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00007913
John McCallcc7e5bf2010-05-06 08:58:33 +00007914 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
7915 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
7916 if (Source == Target) return;
7917 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00007918
Chandler Carruthc22845a2011-07-26 05:40:03 +00007919 // If the conversion context location is invalid don't complain. We also
7920 // don't want to emit a warning if the issue occurs from the expansion of
7921 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
7922 // delay this check as long as possible. Once we detect we are in that
7923 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007924 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00007925 return;
7926
Richard Trieu021baa32011-09-23 20:10:00 +00007927 // Diagnose implicit casts to bool.
7928 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
7929 if (isa<StringLiteral>(E))
7930 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00007931 // and expressions, for instance, assert(0 && "error here"), are
7932 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00007933 return DiagnoseImpCast(S, E, T, CC,
7934 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00007935 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
7936 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
7937 // This covers the literal expressions that evaluate to Objective-C
7938 // objects.
7939 return DiagnoseImpCast(S, E, T, CC,
7940 diag::warn_impcast_objective_c_literal_to_bool);
7941 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00007942 if (Source->isPointerType() || Source->canDecayToPointerType()) {
7943 // Warn on pointer to bool conversion that is always true.
7944 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
7945 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00007946 }
Richard Trieu021baa32011-09-23 20:10:00 +00007947 }
John McCall263a48b2010-01-04 23:31:57 +00007948
Douglas Gregor5054cb02015-07-07 03:58:22 +00007949 // Check implicit casts from Objective-C collection literals to specialized
7950 // collection types, e.g., NSArray<NSString *> *.
7951 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
7952 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
7953 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
7954 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
7955
John McCall263a48b2010-01-04 23:31:57 +00007956 // Strip vector types.
7957 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007958 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007959 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007960 return;
John McCallacf0ee52010-10-08 02:01:28 +00007961 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007962 }
Chris Lattneree7286f2011-06-14 04:51:15 +00007963
7964 // If the vector cast is cast between two vectors of the same size, it is
7965 // a bitcast, not a conversion.
7966 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
7967 return;
John McCall263a48b2010-01-04 23:31:57 +00007968
7969 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
7970 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
7971 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00007972 if (auto VecTy = dyn_cast<VectorType>(Target))
7973 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00007974
7975 // Strip complex types.
7976 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007977 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007978 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007979 return;
7980
John McCallacf0ee52010-10-08 02:01:28 +00007981 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007982 }
John McCall263a48b2010-01-04 23:31:57 +00007983
7984 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
7985 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
7986 }
7987
7988 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
7989 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
7990
7991 // If the source is floating point...
7992 if (SourceBT && SourceBT->isFloatingPoint()) {
7993 // ...and the target is floating point...
7994 if (TargetBT && TargetBT->isFloatingPoint()) {
7995 // ...then warn if we're dropping FP rank.
7996
7997 // Builtin FP kinds are ordered by increasing FP rank.
7998 if (SourceBT->getKind() > TargetBT->getKind()) {
7999 // Don't warn about float constants that are precisely
8000 // representable in the target type.
8001 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00008002 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00008003 // Value might be a float, a float vector, or a float complex.
8004 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00008005 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
8006 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00008007 return;
8008 }
8009
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008010 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008011 return;
8012
John McCallacf0ee52010-10-08 02:01:28 +00008013 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +00008014 }
8015 // ... or possibly if we're increasing rank, too
8016 else if (TargetBT->getKind() > SourceBT->getKind()) {
8017 if (S.SourceMgr.isInSystemMacro(CC))
8018 return;
8019
8020 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +00008021 }
8022 return;
8023 }
8024
Richard Trieube234c32016-04-21 21:04:55 +00008025 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00008026 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008027 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008028 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00008029
Richard Trieube234c32016-04-21 21:04:55 +00008030 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00008031 }
John McCall263a48b2010-01-04 23:31:57 +00008032
Richard Smith54894fd2015-12-30 01:06:52 +00008033 // Detect the case where a call result is converted from floating-point to
8034 // to bool, and the final argument to the call is converted from bool, to
8035 // discover this typo:
8036 //
8037 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
8038 //
8039 // FIXME: This is an incredibly special case; is there some more general
8040 // way to detect this class of misplaced-parentheses bug?
8041 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008042 // Check last argument of function call to see if it is an
8043 // implicit cast from a type matching the type the result
8044 // is being cast to.
8045 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +00008046 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008047 Expr *LastA = CEx->getArg(NumArgs - 1);
8048 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +00008049 if (isa<ImplicitCastExpr>(LastA) &&
8050 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008051 // Warn on this floating-point to bool conversion
8052 DiagnoseImpCast(S, E, T, CC,
8053 diag::warn_impcast_floating_point_to_bool);
8054 }
8055 }
8056 }
John McCall263a48b2010-01-04 23:31:57 +00008057 return;
8058 }
8059
Richard Trieu5b993502014-10-15 03:42:06 +00008060 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00008061
David Blaikie9366d2b2012-06-19 21:19:06 +00008062 if (!Source->isIntegerType() || !Target->isIntegerType())
8063 return;
8064
David Blaikie7555b6a2012-05-15 16:56:36 +00008065 // TODO: remove this early return once the false positives for constant->bool
8066 // in templates, macros, etc, are reduced or removed.
8067 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
8068 return;
8069
John McCallcc7e5bf2010-05-06 08:58:33 +00008070 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00008071 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00008072
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008073 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00008074 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008075 // TODO: this should happen for bitfield stores, too.
8076 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +00008077 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008078 if (S.SourceMgr.isInSystemMacro(CC))
8079 return;
8080
John McCall18a2c2c2010-11-09 22:22:12 +00008081 std::string PrettySourceValue = Value.toString(10);
8082 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008083
Ted Kremenek33ba9952011-10-22 02:37:33 +00008084 S.DiagRuntimeBehavior(E->getExprLoc(), E,
8085 S.PDiag(diag::warn_impcast_integer_precision_constant)
8086 << PrettySourceValue << PrettyTargetValue
8087 << E->getType() << T << E->getSourceRange()
8088 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00008089 return;
8090 }
8091
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008092 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
8093 if (S.SourceMgr.isInSystemMacro(CC))
8094 return;
8095
David Blaikie9455da02012-04-12 22:40:54 +00008096 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00008097 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
8098 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00008099 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00008100 }
8101
Richard Trieudcb55572016-01-29 23:51:16 +00008102 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
8103 SourceRange.NonNegative && Source->isSignedIntegerType()) {
8104 // Warn when doing a signed to signed conversion, warn if the positive
8105 // source value is exactly the width of the target type, which will
8106 // cause a negative value to be stored.
8107
8108 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +00008109 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
8110 !S.SourceMgr.isInSystemMacro(CC)) {
8111 if (isSameWidthConstantConversion(S, E, T, CC)) {
8112 std::string PrettySourceValue = Value.toString(10);
8113 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +00008114
Richard Trieufc404c72016-02-05 23:02:38 +00008115 S.DiagRuntimeBehavior(
8116 E->getExprLoc(), E,
8117 S.PDiag(diag::warn_impcast_integer_precision_constant)
8118 << PrettySourceValue << PrettyTargetValue << E->getType() << T
8119 << E->getSourceRange() << clang::SourceRange(CC));
8120 return;
Richard Trieudcb55572016-01-29 23:51:16 +00008121 }
8122 }
Richard Trieufc404c72016-02-05 23:02:38 +00008123
Richard Trieudcb55572016-01-29 23:51:16 +00008124 // Fall through for non-constants to give a sign conversion warning.
8125 }
8126
John McCallcc7e5bf2010-05-06 08:58:33 +00008127 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
8128 (!TargetRange.NonNegative && SourceRange.NonNegative &&
8129 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008130 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008131 return;
8132
John McCallcc7e5bf2010-05-06 08:58:33 +00008133 unsigned DiagID = diag::warn_impcast_integer_sign;
8134
8135 // Traditionally, gcc has warned about this under -Wsign-compare.
8136 // We also want to warn about it in -Wconversion.
8137 // So if -Wconversion is off, use a completely identical diagnostic
8138 // in the sign-compare group.
8139 // The conditional-checking code will
8140 if (ICContext) {
8141 DiagID = diag::warn_impcast_integer_sign_conditional;
8142 *ICContext = true;
8143 }
8144
John McCallacf0ee52010-10-08 02:01:28 +00008145 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00008146 }
8147
Douglas Gregora78f1932011-02-22 02:45:07 +00008148 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00008149 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
8150 // type, to give us better diagnostics.
8151 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00008152 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00008153 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8154 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
8155 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
8156 SourceType = S.Context.getTypeDeclType(Enum);
8157 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
8158 }
8159 }
8160
Douglas Gregora78f1932011-02-22 02:45:07 +00008161 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
8162 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00008163 if (SourceEnum->getDecl()->hasNameForLinkage() &&
8164 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008165 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008166 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008167 return;
8168
Douglas Gregor364f7db2011-03-12 00:14:31 +00008169 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00008170 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008171 }
John McCall263a48b2010-01-04 23:31:57 +00008172}
8173
David Blaikie18e9ac72012-05-15 21:57:38 +00008174void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
8175 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00008176
8177void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00008178 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008179 E = E->IgnoreParenImpCasts();
8180
8181 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00008182 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00008183
John McCallacf0ee52010-10-08 02:01:28 +00008184 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008185 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00008186 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00008187}
8188
David Blaikie18e9ac72012-05-15 21:57:38 +00008189void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
8190 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00008191 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00008192
8193 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00008194 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
8195 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00008196
8197 // If -Wconversion would have warned about either of the candidates
8198 // for a signedness conversion to the context type...
8199 if (!Suspicious) return;
8200
8201 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008202 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00008203 return;
8204
John McCallcc7e5bf2010-05-06 08:58:33 +00008205 // ...then check whether it would have warned about either of the
8206 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00008207 if (E->getType() == T) return;
8208
8209 Suspicious = false;
8210 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
8211 E->getType(), CC, &Suspicious);
8212 if (!Suspicious)
8213 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00008214 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00008215}
8216
Richard Trieu65724892014-11-15 06:37:39 +00008217/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
8218/// Input argument E is a logical expression.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008219void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +00008220 if (S.getLangOpts().Bool)
8221 return;
8222 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
8223}
8224
John McCallcc7e5bf2010-05-06 08:58:33 +00008225/// AnalyzeImplicitConversions - Find and report any interesting
8226/// implicit conversions in the given expression. There are a couple
8227/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00008228void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00008229 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00008230 Expr *E = OrigE->IgnoreParenImpCasts();
8231
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00008232 if (E->isTypeDependent() || E->isValueDependent())
8233 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00008234
John McCallcc7e5bf2010-05-06 08:58:33 +00008235 // For conditional operators, we analyze the arguments as if they
8236 // were being fed directly into the output.
8237 if (isa<ConditionalOperator>(E)) {
8238 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00008239 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00008240 return;
8241 }
8242
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008243 // Check implicit argument conversions for function calls.
8244 if (CallExpr *Call = dyn_cast<CallExpr>(E))
8245 CheckImplicitArgumentConversions(S, Call, CC);
8246
John McCallcc7e5bf2010-05-06 08:58:33 +00008247 // Go ahead and check any implicit conversions we might have skipped.
8248 // The non-canonical typecheck is just an optimization;
8249 // CheckImplicitConversion will filter out dead implicit conversions.
8250 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00008251 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008252
8253 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +00008254
8255 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
8256 // The bound subexpressions in a PseudoObjectExpr are not reachable
8257 // as transitive children.
8258 // FIXME: Use a more uniform representation for this.
8259 for (auto *SE : POE->semantics())
8260 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
8261 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00008262 }
Richard Smithd7bed4d2015-11-22 02:57:17 +00008263
John McCallcc7e5bf2010-05-06 08:58:33 +00008264 // Skip past explicit casts.
8265 if (isa<ExplicitCastExpr>(E)) {
8266 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00008267 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008268 }
8269
John McCalld2a53122010-11-09 23:24:47 +00008270 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8271 // Do a somewhat different check with comparison operators.
8272 if (BO->isComparisonOp())
8273 return AnalyzeComparison(S, BO);
8274
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008275 // And with simple assignments.
8276 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00008277 return AnalyzeAssignment(S, BO);
8278 }
John McCallcc7e5bf2010-05-06 08:58:33 +00008279
8280 // These break the otherwise-useful invariant below. Fortunately,
8281 // we don't really need to recurse into them, because any internal
8282 // expressions should have been analyzed already when they were
8283 // built into statements.
8284 if (isa<StmtExpr>(E)) return;
8285
8286 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00008287 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00008288
8289 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00008290 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00008291 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00008292 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +00008293 for (Stmt *SubStmt : E->children()) {
8294 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00008295 if (!ChildExpr)
8296 continue;
8297
Richard Trieu955231d2014-01-25 01:10:35 +00008298 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00008299 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00008300 // Ignore checking string literals that are in logical and operators.
8301 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00008302 continue;
8303 AnalyzeImplicitConversions(S, ChildExpr, CC);
8304 }
Richard Trieu791b86e2014-11-19 06:08:18 +00008305
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00008306 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00008307 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
8308 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00008309 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00008310
8311 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
8312 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00008313 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00008314 }
Richard Trieu791b86e2014-11-19 06:08:18 +00008315
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00008316 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
8317 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00008318 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008319}
8320
8321} // end anonymous namespace
8322
Richard Trieuc1888e02014-06-28 23:25:37 +00008323// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
8324// Returns true when emitting a warning about taking the address of a reference.
8325static bool CheckForReference(Sema &SemaRef, const Expr *E,
8326 PartialDiagnostic PD) {
8327 E = E->IgnoreParenImpCasts();
8328
8329 const FunctionDecl *FD = nullptr;
8330
8331 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8332 if (!DRE->getDecl()->getType()->isReferenceType())
8333 return false;
8334 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
8335 if (!M->getMemberDecl()->getType()->isReferenceType())
8336 return false;
8337 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00008338 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00008339 return false;
8340 FD = Call->getDirectCallee();
8341 } else {
8342 return false;
8343 }
8344
8345 SemaRef.Diag(E->getExprLoc(), PD);
8346
8347 // If possible, point to location of function.
8348 if (FD) {
8349 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
8350 }
8351
8352 return true;
8353}
8354
Richard Trieu4cbff5c2014-08-08 22:41:43 +00008355// Returns true if the SourceLocation is expanded from any macro body.
8356// Returns false if the SourceLocation is invalid, is from not in a macro
8357// expansion, or is from expanded from a top-level macro argument.
8358static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
8359 if (Loc.isInvalid())
8360 return false;
8361
8362 while (Loc.isMacroID()) {
8363 if (SM.isMacroBodyExpansion(Loc))
8364 return true;
8365 Loc = SM.getImmediateMacroCallerLoc(Loc);
8366 }
8367
8368 return false;
8369}
8370
Richard Trieu3bb8b562014-02-26 02:36:06 +00008371/// \brief Diagnose pointers that are always non-null.
8372/// \param E the expression containing the pointer
8373/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
8374/// compared to a null pointer
8375/// \param IsEqual True when the comparison is equal to a null pointer
8376/// \param Range Extra SourceRange to highlight in the diagnostic
8377void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
8378 Expr::NullPointerConstantKind NullKind,
8379 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00008380 if (!E)
8381 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008382
8383 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00008384 if (E->getExprLoc().isMacroID()) {
8385 const SourceManager &SM = getSourceManager();
8386 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
8387 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00008388 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00008389 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00008390 E = E->IgnoreImpCasts();
8391
8392 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
8393
Richard Trieuf7432752014-06-06 21:39:26 +00008394 if (isa<CXXThisExpr>(E)) {
8395 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
8396 : diag::warn_this_bool_conversion;
8397 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
8398 return;
8399 }
8400
Richard Trieu3bb8b562014-02-26 02:36:06 +00008401 bool IsAddressOf = false;
8402
8403 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
8404 if (UO->getOpcode() != UO_AddrOf)
8405 return;
8406 IsAddressOf = true;
8407 E = UO->getSubExpr();
8408 }
8409
Richard Trieuc1888e02014-06-28 23:25:37 +00008410 if (IsAddressOf) {
8411 unsigned DiagID = IsCompare
8412 ? diag::warn_address_of_reference_null_compare
8413 : diag::warn_address_of_reference_bool_conversion;
8414 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
8415 << IsEqual;
8416 if (CheckForReference(*this, E, PD)) {
8417 return;
8418 }
8419 }
8420
George Burgess IV850269a2015-12-08 22:02:00 +00008421 auto ComplainAboutNonnullParamOrCall = [&](bool IsParam) {
8422 std::string Str;
8423 llvm::raw_string_ostream S(Str);
8424 E->printPretty(S, nullptr, getPrintingPolicy());
8425 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
8426 : diag::warn_cast_nonnull_to_bool;
8427 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
8428 << E->getSourceRange() << Range << IsEqual;
8429 };
8430
8431 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
8432 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
8433 if (auto *Callee = Call->getDirectCallee()) {
8434 if (Callee->hasAttr<ReturnsNonNullAttr>()) {
8435 ComplainAboutNonnullParamOrCall(false);
8436 return;
8437 }
8438 }
8439 }
8440
Richard Trieu3bb8b562014-02-26 02:36:06 +00008441 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00008442 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008443 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
8444 D = R->getDecl();
8445 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
8446 D = M->getMemberDecl();
8447 }
8448
8449 // Weak Decls can be null.
8450 if (!D || D->isWeak())
8451 return;
George Burgess IV850269a2015-12-08 22:02:00 +00008452
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008453 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +00008454 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
8455 if (getCurFunction() &&
8456 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
8457 if (PV->hasAttr<NonNullAttr>()) {
8458 ComplainAboutNonnullParamOrCall(true);
8459 return;
8460 }
8461
8462 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
8463 auto ParamIter = std::find(FD->param_begin(), FD->param_end(), PV);
8464 assert(ParamIter != FD->param_end());
8465 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
8466
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008467 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
8468 if (!NonNull->args_size()) {
George Burgess IV850269a2015-12-08 22:02:00 +00008469 ComplainAboutNonnullParamOrCall(true);
8470 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008471 }
George Burgess IV850269a2015-12-08 22:02:00 +00008472
8473 for (unsigned ArgNo : NonNull->args()) {
8474 if (ArgNo == ParamNo) {
8475 ComplainAboutNonnullParamOrCall(true);
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008476 return;
8477 }
George Burgess IV850269a2015-12-08 22:02:00 +00008478 }
8479 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008480 }
8481 }
George Burgess IV850269a2015-12-08 22:02:00 +00008482 }
8483
Richard Trieu3bb8b562014-02-26 02:36:06 +00008484 QualType T = D->getType();
8485 const bool IsArray = T->isArrayType();
8486 const bool IsFunction = T->isFunctionType();
8487
Richard Trieuc1888e02014-06-28 23:25:37 +00008488 // Address of function is used to silence the function warning.
8489 if (IsAddressOf && IsFunction) {
8490 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008491 }
8492
8493 // Found nothing.
8494 if (!IsAddressOf && !IsFunction && !IsArray)
8495 return;
8496
8497 // Pretty print the expression for the diagnostic.
8498 std::string Str;
8499 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00008500 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00008501
8502 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
8503 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +00008504 enum {
8505 AddressOf,
8506 FunctionPointer,
8507 ArrayPointer
8508 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008509 if (IsAddressOf)
8510 DiagType = AddressOf;
8511 else if (IsFunction)
8512 DiagType = FunctionPointer;
8513 else if (IsArray)
8514 DiagType = ArrayPointer;
8515 else
8516 llvm_unreachable("Could not determine diagnostic.");
8517 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
8518 << Range << IsEqual;
8519
8520 if (!IsFunction)
8521 return;
8522
8523 // Suggest '&' to silence the function warning.
8524 Diag(E->getExprLoc(), diag::note_function_warning_silence)
8525 << FixItHint::CreateInsertion(E->getLocStart(), "&");
8526
8527 // Check to see if '()' fixit should be emitted.
8528 QualType ReturnType;
8529 UnresolvedSet<4> NonTemplateOverloads;
8530 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
8531 if (ReturnType.isNull())
8532 return;
8533
8534 if (IsCompare) {
8535 // There are two cases here. If there is null constant, the only suggest
8536 // for a pointer return type. If the null is 0, then suggest if the return
8537 // type is a pointer or an integer type.
8538 if (!ReturnType->isPointerType()) {
8539 if (NullKind == Expr::NPCK_ZeroExpression ||
8540 NullKind == Expr::NPCK_ZeroLiteral) {
8541 if (!ReturnType->isIntegerType())
8542 return;
8543 } else {
8544 return;
8545 }
8546 }
8547 } else { // !IsCompare
8548 // For function to bool, only suggest if the function pointer has bool
8549 // return type.
8550 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
8551 return;
8552 }
8553 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00008554 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00008555}
8556
John McCallcc7e5bf2010-05-06 08:58:33 +00008557/// Diagnoses "dangerous" implicit conversions within the given
8558/// expression (which is a full expression). Implements -Wconversion
8559/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00008560///
8561/// \param CC the "context" location of the implicit conversion, i.e.
8562/// the most location of the syntactic entity requiring the implicit
8563/// conversion
8564void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008565 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00008566 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00008567 return;
8568
8569 // Don't diagnose for value- or type-dependent expressions.
8570 if (E->isTypeDependent() || E->isValueDependent())
8571 return;
8572
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008573 // Check for array bounds violations in cases where the check isn't triggered
8574 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
8575 // ArraySubscriptExpr is on the RHS of a variable initialization.
8576 CheckArrayAccess(E);
8577
John McCallacf0ee52010-10-08 02:01:28 +00008578 // This is not the right CC for (e.g.) a variable initialization.
8579 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008580}
8581
Richard Trieu65724892014-11-15 06:37:39 +00008582/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
8583/// Input argument E is a logical expression.
8584void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
8585 ::CheckBoolLikeConversion(*this, E, CC);
8586}
8587
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008588/// Diagnose when expression is an integer constant expression and its evaluation
8589/// results in integer overflow
8590void Sema::CheckForIntOverflow (Expr *E) {
Akira Hatanakadfe2156f2016-02-10 06:06:06 +00008591 // Use a work list to deal with nested struct initializers.
8592 SmallVector<Expr *, 2> Exprs(1, E);
8593
8594 do {
8595 Expr *E = Exprs.pop_back_val();
8596
8597 if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
8598 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
8599 continue;
8600 }
8601
8602 if (auto InitList = dyn_cast<InitListExpr>(E))
8603 Exprs.append(InitList->inits().begin(), InitList->inits().end());
8604 } while (!Exprs.empty());
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008605}
8606
Richard Smithc406cb72013-01-17 01:17:56 +00008607namespace {
8608/// \brief Visitor for expressions which looks for unsequenced operations on the
8609/// same object.
8610class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00008611 typedef EvaluatedExprVisitor<SequenceChecker> Base;
8612
Richard Smithc406cb72013-01-17 01:17:56 +00008613 /// \brief A tree of sequenced regions within an expression. Two regions are
8614 /// unsequenced if one is an ancestor or a descendent of the other. When we
8615 /// finish processing an expression with sequencing, such as a comma
8616 /// expression, we fold its tree nodes into its parent, since they are
8617 /// unsequenced with respect to nodes we will visit later.
8618 class SequenceTree {
8619 struct Value {
8620 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
8621 unsigned Parent : 31;
8622 bool Merged : 1;
8623 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008624 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00008625
8626 public:
8627 /// \brief A region within an expression which may be sequenced with respect
8628 /// to some other region.
8629 class Seq {
8630 explicit Seq(unsigned N) : Index(N) {}
8631 unsigned Index;
8632 friend class SequenceTree;
8633 public:
8634 Seq() : Index(0) {}
8635 };
8636
8637 SequenceTree() { Values.push_back(Value(0)); }
8638 Seq root() const { return Seq(0); }
8639
8640 /// \brief Create a new sequence of operations, which is an unsequenced
8641 /// subset of \p Parent. This sequence of operations is sequenced with
8642 /// respect to other children of \p Parent.
8643 Seq allocate(Seq Parent) {
8644 Values.push_back(Value(Parent.Index));
8645 return Seq(Values.size() - 1);
8646 }
8647
8648 /// \brief Merge a sequence of operations into its parent.
8649 void merge(Seq S) {
8650 Values[S.Index].Merged = true;
8651 }
8652
8653 /// \brief Determine whether two operations are unsequenced. This operation
8654 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
8655 /// should have been merged into its parent as appropriate.
8656 bool isUnsequenced(Seq Cur, Seq Old) {
8657 unsigned C = representative(Cur.Index);
8658 unsigned Target = representative(Old.Index);
8659 while (C >= Target) {
8660 if (C == Target)
8661 return true;
8662 C = Values[C].Parent;
8663 }
8664 return false;
8665 }
8666
8667 private:
8668 /// \brief Pick a representative for a sequence.
8669 unsigned representative(unsigned K) {
8670 if (Values[K].Merged)
8671 // Perform path compression as we go.
8672 return Values[K].Parent = representative(Values[K].Parent);
8673 return K;
8674 }
8675 };
8676
8677 /// An object for which we can track unsequenced uses.
8678 typedef NamedDecl *Object;
8679
8680 /// Different flavors of object usage which we track. We only track the
8681 /// least-sequenced usage of each kind.
8682 enum UsageKind {
8683 /// A read of an object. Multiple unsequenced reads are OK.
8684 UK_Use,
8685 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00008686 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00008687 UK_ModAsValue,
8688 /// A modification of an object which is not sequenced before the value
8689 /// computation of the expression, such as n++.
8690 UK_ModAsSideEffect,
8691
8692 UK_Count = UK_ModAsSideEffect + 1
8693 };
8694
8695 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00008696 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00008697 Expr *Use;
8698 SequenceTree::Seq Seq;
8699 };
8700
8701 struct UsageInfo {
8702 UsageInfo() : Diagnosed(false) {}
8703 Usage Uses[UK_Count];
8704 /// Have we issued a diagnostic for this variable already?
8705 bool Diagnosed;
8706 };
8707 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
8708
8709 Sema &SemaRef;
8710 /// Sequenced regions within the expression.
8711 SequenceTree Tree;
8712 /// Declaration modifications and references which we have seen.
8713 UsageInfoMap UsageMap;
8714 /// The region we are currently within.
8715 SequenceTree::Seq Region;
8716 /// Filled in with declarations which were modified as a side-effect
8717 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008718 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00008719 /// Expressions to check later. We defer checking these to reduce
8720 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008721 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00008722
8723 /// RAII object wrapping the visitation of a sequenced subexpression of an
8724 /// expression. At the end of this process, the side-effects of the evaluation
8725 /// become sequenced with respect to the value computation of the result, so
8726 /// we downgrade any UK_ModAsSideEffect within the evaluation to
8727 /// UK_ModAsValue.
8728 struct SequencedSubexpression {
8729 SequencedSubexpression(SequenceChecker &Self)
8730 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
8731 Self.ModAsSideEffect = &ModAsSideEffect;
8732 }
8733 ~SequencedSubexpression() {
Richard Smithe8efd992014-12-03 01:05:50 +00008734 for (auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend();
8735 MI != ME; ++MI) {
8736 UsageInfo &U = Self.UsageMap[MI->first];
8737 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
8738 Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue);
8739 SideEffectUsage = MI->second;
Richard Smithc406cb72013-01-17 01:17:56 +00008740 }
8741 Self.ModAsSideEffect = OldModAsSideEffect;
8742 }
8743
8744 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008745 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
8746 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00008747 };
8748
Richard Smith40238f02013-06-20 22:21:56 +00008749 /// RAII object wrapping the visitation of a subexpression which we might
8750 /// choose to evaluate as a constant. If any subexpression is evaluated and
8751 /// found to be non-constant, this allows us to suppress the evaluation of
8752 /// the outer expression.
8753 class EvaluationTracker {
8754 public:
8755 EvaluationTracker(SequenceChecker &Self)
8756 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
8757 Self.EvalTracker = this;
8758 }
8759 ~EvaluationTracker() {
8760 Self.EvalTracker = Prev;
8761 if (Prev)
8762 Prev->EvalOK &= EvalOK;
8763 }
8764
8765 bool evaluate(const Expr *E, bool &Result) {
8766 if (!EvalOK || E->isValueDependent())
8767 return false;
8768 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
8769 return EvalOK;
8770 }
8771
8772 private:
8773 SequenceChecker &Self;
8774 EvaluationTracker *Prev;
8775 bool EvalOK;
8776 } *EvalTracker;
8777
Richard Smithc406cb72013-01-17 01:17:56 +00008778 /// \brief Find the object which is produced by the specified expression,
8779 /// if any.
8780 Object getObject(Expr *E, bool Mod) const {
8781 E = E->IgnoreParenCasts();
8782 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
8783 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
8784 return getObject(UO->getSubExpr(), Mod);
8785 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8786 if (BO->getOpcode() == BO_Comma)
8787 return getObject(BO->getRHS(), Mod);
8788 if (Mod && BO->isAssignmentOp())
8789 return getObject(BO->getLHS(), Mod);
8790 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
8791 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
8792 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
8793 return ME->getMemberDecl();
8794 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8795 // FIXME: If this is a reference, map through to its value.
8796 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00008797 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00008798 }
8799
8800 /// \brief Note that an object was modified or used by an expression.
8801 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
8802 Usage &U = UI.Uses[UK];
8803 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
8804 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
8805 ModAsSideEffect->push_back(std::make_pair(O, U));
8806 U.Use = Ref;
8807 U.Seq = Region;
8808 }
8809 }
8810 /// \brief Check whether a modification or use conflicts with a prior usage.
8811 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
8812 bool IsModMod) {
8813 if (UI.Diagnosed)
8814 return;
8815
8816 const Usage &U = UI.Uses[OtherKind];
8817 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
8818 return;
8819
8820 Expr *Mod = U.Use;
8821 Expr *ModOrUse = Ref;
8822 if (OtherKind == UK_Use)
8823 std::swap(Mod, ModOrUse);
8824
8825 SemaRef.Diag(Mod->getExprLoc(),
8826 IsModMod ? diag::warn_unsequenced_mod_mod
8827 : diag::warn_unsequenced_mod_use)
8828 << O << SourceRange(ModOrUse->getExprLoc());
8829 UI.Diagnosed = true;
8830 }
8831
8832 void notePreUse(Object O, Expr *Use) {
8833 UsageInfo &U = UsageMap[O];
8834 // Uses conflict with other modifications.
8835 checkUsage(O, U, Use, UK_ModAsValue, false);
8836 }
8837 void notePostUse(Object O, Expr *Use) {
8838 UsageInfo &U = UsageMap[O];
8839 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
8840 addUsage(U, O, Use, UK_Use);
8841 }
8842
8843 void notePreMod(Object O, Expr *Mod) {
8844 UsageInfo &U = UsageMap[O];
8845 // Modifications conflict with other modifications and with uses.
8846 checkUsage(O, U, Mod, UK_ModAsValue, true);
8847 checkUsage(O, U, Mod, UK_Use, false);
8848 }
8849 void notePostMod(Object O, Expr *Use, UsageKind UK) {
8850 UsageInfo &U = UsageMap[O];
8851 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
8852 addUsage(U, O, Use, UK);
8853 }
8854
8855public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008856 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00008857 : Base(S.Context), SemaRef(S), Region(Tree.root()),
8858 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00008859 Visit(E);
8860 }
8861
8862 void VisitStmt(Stmt *S) {
8863 // Skip all statements which aren't expressions for now.
8864 }
8865
8866 void VisitExpr(Expr *E) {
8867 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00008868 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00008869 }
8870
8871 void VisitCastExpr(CastExpr *E) {
8872 Object O = Object();
8873 if (E->getCastKind() == CK_LValueToRValue)
8874 O = getObject(E->getSubExpr(), false);
8875
8876 if (O)
8877 notePreUse(O, E);
8878 VisitExpr(E);
8879 if (O)
8880 notePostUse(O, E);
8881 }
8882
8883 void VisitBinComma(BinaryOperator *BO) {
8884 // C++11 [expr.comma]p1:
8885 // Every value computation and side effect associated with the left
8886 // expression is sequenced before every value computation and side
8887 // effect associated with the right expression.
8888 SequenceTree::Seq LHS = Tree.allocate(Region);
8889 SequenceTree::Seq RHS = Tree.allocate(Region);
8890 SequenceTree::Seq OldRegion = Region;
8891
8892 {
8893 SequencedSubexpression SeqLHS(*this);
8894 Region = LHS;
8895 Visit(BO->getLHS());
8896 }
8897
8898 Region = RHS;
8899 Visit(BO->getRHS());
8900
8901 Region = OldRegion;
8902
8903 // Forget that LHS and RHS are sequenced. They are both unsequenced
8904 // with respect to other stuff.
8905 Tree.merge(LHS);
8906 Tree.merge(RHS);
8907 }
8908
8909 void VisitBinAssign(BinaryOperator *BO) {
8910 // The modification is sequenced after the value computation of the LHS
8911 // and RHS, so check it before inspecting the operands and update the
8912 // map afterwards.
8913 Object O = getObject(BO->getLHS(), true);
8914 if (!O)
8915 return VisitExpr(BO);
8916
8917 notePreMod(O, BO);
8918
8919 // C++11 [expr.ass]p7:
8920 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
8921 // only once.
8922 //
8923 // Therefore, for a compound assignment operator, O is considered used
8924 // everywhere except within the evaluation of E1 itself.
8925 if (isa<CompoundAssignOperator>(BO))
8926 notePreUse(O, BO);
8927
8928 Visit(BO->getLHS());
8929
8930 if (isa<CompoundAssignOperator>(BO))
8931 notePostUse(O, BO);
8932
8933 Visit(BO->getRHS());
8934
Richard Smith83e37bee2013-06-26 23:16:51 +00008935 // C++11 [expr.ass]p1:
8936 // the assignment is sequenced [...] before the value computation of the
8937 // assignment expression.
8938 // C11 6.5.16/3 has no such rule.
8939 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
8940 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00008941 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008942
Richard Smithc406cb72013-01-17 01:17:56 +00008943 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
8944 VisitBinAssign(CAO);
8945 }
8946
8947 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
8948 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
8949 void VisitUnaryPreIncDec(UnaryOperator *UO) {
8950 Object O = getObject(UO->getSubExpr(), true);
8951 if (!O)
8952 return VisitExpr(UO);
8953
8954 notePreMod(O, UO);
8955 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00008956 // C++11 [expr.pre.incr]p1:
8957 // the expression ++x is equivalent to x+=1
8958 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
8959 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00008960 }
8961
8962 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
8963 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
8964 void VisitUnaryPostIncDec(UnaryOperator *UO) {
8965 Object O = getObject(UO->getSubExpr(), true);
8966 if (!O)
8967 return VisitExpr(UO);
8968
8969 notePreMod(O, UO);
8970 Visit(UO->getSubExpr());
8971 notePostMod(O, UO, UK_ModAsSideEffect);
8972 }
8973
8974 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
8975 void VisitBinLOr(BinaryOperator *BO) {
8976 // The side-effects of the LHS of an '&&' are sequenced before the
8977 // value computation of the RHS, and hence before the value computation
8978 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
8979 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00008980 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00008981 {
8982 SequencedSubexpression Sequenced(*this);
8983 Visit(BO->getLHS());
8984 }
8985
8986 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00008987 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00008988 if (!Result)
8989 Visit(BO->getRHS());
8990 } else {
8991 // Check for unsequenced operations in the RHS, treating it as an
8992 // entirely separate evaluation.
8993 //
8994 // FIXME: If there are operations in the RHS which are unsequenced
8995 // with respect to operations outside the RHS, and those operations
8996 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00008997 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00008998 }
Richard Smithc406cb72013-01-17 01:17:56 +00008999 }
9000 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00009001 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00009002 {
9003 SequencedSubexpression Sequenced(*this);
9004 Visit(BO->getLHS());
9005 }
9006
9007 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00009008 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00009009 if (Result)
9010 Visit(BO->getRHS());
9011 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00009012 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00009013 }
Richard Smithc406cb72013-01-17 01:17:56 +00009014 }
9015
9016 // Only visit the condition, unless we can be sure which subexpression will
9017 // be chosen.
9018 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00009019 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00009020 {
9021 SequencedSubexpression Sequenced(*this);
9022 Visit(CO->getCond());
9023 }
Richard Smithc406cb72013-01-17 01:17:56 +00009024
9025 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00009026 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00009027 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00009028 else {
Richard Smithd33f5202013-01-17 23:18:09 +00009029 WorkList.push_back(CO->getTrueExpr());
9030 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00009031 }
Richard Smithc406cb72013-01-17 01:17:56 +00009032 }
9033
Richard Smithe3dbfe02013-06-30 10:40:20 +00009034 void VisitCallExpr(CallExpr *CE) {
9035 // C++11 [intro.execution]p15:
9036 // When calling a function [...], every value computation and side effect
9037 // associated with any argument expression, or with the postfix expression
9038 // designating the called function, is sequenced before execution of every
9039 // expression or statement in the body of the function [and thus before
9040 // the value computation of its result].
9041 SequencedSubexpression Sequenced(*this);
9042 Base::VisitCallExpr(CE);
9043
9044 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
9045 }
9046
Richard Smithc406cb72013-01-17 01:17:56 +00009047 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00009048 // This is a call, so all subexpressions are sequenced before the result.
9049 SequencedSubexpression Sequenced(*this);
9050
Richard Smithc406cb72013-01-17 01:17:56 +00009051 if (!CCE->isListInitialization())
9052 return VisitExpr(CCE);
9053
9054 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009055 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00009056 SequenceTree::Seq Parent = Region;
9057 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
9058 E = CCE->arg_end();
9059 I != E; ++I) {
9060 Region = Tree.allocate(Parent);
9061 Elts.push_back(Region);
9062 Visit(*I);
9063 }
9064
9065 // Forget that the initializers are sequenced.
9066 Region = Parent;
9067 for (unsigned I = 0; I < Elts.size(); ++I)
9068 Tree.merge(Elts[I]);
9069 }
9070
9071 void VisitInitListExpr(InitListExpr *ILE) {
9072 if (!SemaRef.getLangOpts().CPlusPlus11)
9073 return VisitExpr(ILE);
9074
9075 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009076 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00009077 SequenceTree::Seq Parent = Region;
9078 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
9079 Expr *E = ILE->getInit(I);
9080 if (!E) continue;
9081 Region = Tree.allocate(Parent);
9082 Elts.push_back(Region);
9083 Visit(E);
9084 }
9085
9086 // Forget that the initializers are sequenced.
9087 Region = Parent;
9088 for (unsigned I = 0; I < Elts.size(); ++I)
9089 Tree.merge(Elts[I]);
9090 }
9091};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009092} // end anonymous namespace
Richard Smithc406cb72013-01-17 01:17:56 +00009093
9094void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009095 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00009096 WorkList.push_back(E);
9097 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00009098 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00009099 SequenceChecker(*this, Item, WorkList);
9100 }
Richard Smithc406cb72013-01-17 01:17:56 +00009101}
9102
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009103void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
9104 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00009105 CheckImplicitConversions(E, CheckLoc);
9106 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009107 if (!IsConstexpr && !E->isValueDependent())
9108 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00009109}
9110
John McCall1f425642010-11-11 03:21:53 +00009111void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
9112 FieldDecl *BitField,
9113 Expr *Init) {
9114 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
9115}
9116
David Majnemer61a5bbf2015-04-07 22:08:51 +00009117static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
9118 SourceLocation Loc) {
9119 if (!PType->isVariablyModifiedType())
9120 return;
9121 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
9122 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
9123 return;
9124 }
David Majnemerdf8f73f2015-04-09 19:53:25 +00009125 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
9126 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
9127 return;
9128 }
David Majnemer61a5bbf2015-04-07 22:08:51 +00009129 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
9130 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
9131 return;
9132 }
9133
9134 const ArrayType *AT = S.Context.getAsArrayType(PType);
9135 if (!AT)
9136 return;
9137
9138 if (AT->getSizeModifier() != ArrayType::Star) {
9139 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
9140 return;
9141 }
9142
9143 S.Diag(Loc, diag::err_array_star_in_function_definition);
9144}
9145
Mike Stump0c2ec772010-01-21 03:59:47 +00009146/// CheckParmsForFunctionDef - Check that the parameters of the given
9147/// function are appropriate for the definition of a function. This
9148/// takes care of any checks that cannot be performed on the
9149/// declaration itself, e.g., that the types of each of the function
9150/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00009151bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
9152 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00009153 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00009154 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00009155 for (; P != PEnd; ++P) {
9156 ParmVarDecl *Param = *P;
9157
Mike Stump0c2ec772010-01-21 03:59:47 +00009158 // C99 6.7.5.3p4: the parameters in a parameter type list in a
9159 // function declarator that is part of a function definition of
9160 // that function shall not have incomplete type.
9161 //
9162 // This is also C++ [dcl.fct]p6.
9163 if (!Param->isInvalidDecl() &&
9164 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00009165 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00009166 Param->setInvalidDecl();
9167 HasInvalidParm = true;
9168 }
9169
9170 // C99 6.9.1p5: If the declarator includes a parameter type list, the
9171 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00009172 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00009173 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00009174 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00009175 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00009176 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00009177
9178 // C99 6.7.5.3p12:
9179 // If the function declarator is not part of a definition of that
9180 // function, parameters may have incomplete type and may use the [*]
9181 // notation in their sequences of declarator specifiers to specify
9182 // variable length array types.
9183 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +00009184 // FIXME: This diagnostic should point the '[*]' if source-location
9185 // information is added for it.
9186 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00009187
9188 // MSVC destroys objects passed by value in the callee. Therefore a
9189 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00009190 // object's destructor. However, we don't perform any direct access check
9191 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00009192 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
9193 .getCXXABI()
9194 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00009195 if (!Param->isInvalidDecl()) {
9196 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
9197 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
9198 if (!ClassDecl->isInvalidDecl() &&
9199 !ClassDecl->hasIrrelevantDestructor() &&
9200 !ClassDecl->isDependentContext()) {
9201 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
9202 MarkFunctionReferenced(Param->getLocation(), Destructor);
9203 DiagnoseUseOfDecl(Destructor, Param->getLocation());
9204 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00009205 }
9206 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00009207 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009208
9209 // Parameters with the pass_object_size attribute only need to be marked
9210 // constant at function definitions. Because we lack information about
9211 // whether we're on a declaration or definition when we're instantiating the
9212 // attribute, we need to check for constness here.
9213 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
9214 if (!Param->getType().isConstQualified())
9215 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
9216 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +00009217 }
9218
9219 return HasInvalidParm;
9220}
John McCall2b5c1b22010-08-12 21:44:57 +00009221
9222/// CheckCastAlign - Implements -Wcast-align, which warns when a
9223/// pointer cast increases the alignment requirements.
9224void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
9225 // This is actually a lot of work to potentially be doing on every
9226 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009227 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00009228 return;
9229
9230 // Ignore dependent types.
9231 if (T->isDependentType() || Op->getType()->isDependentType())
9232 return;
9233
9234 // Require that the destination be a pointer type.
9235 const PointerType *DestPtr = T->getAs<PointerType>();
9236 if (!DestPtr) return;
9237
9238 // If the destination has alignment 1, we're done.
9239 QualType DestPointee = DestPtr->getPointeeType();
9240 if (DestPointee->isIncompleteType()) return;
9241 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
9242 if (DestAlign.isOne()) return;
9243
9244 // Require that the source be a pointer type.
9245 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
9246 if (!SrcPtr) return;
9247 QualType SrcPointee = SrcPtr->getPointeeType();
9248
9249 // Whitelist casts from cv void*. We already implicitly
9250 // whitelisted casts to cv void*, since they have alignment 1.
9251 // Also whitelist casts involving incomplete types, which implicitly
9252 // includes 'void'.
9253 if (SrcPointee->isIncompleteType()) return;
9254
9255 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
9256 if (SrcAlign >= DestAlign) return;
9257
9258 Diag(TRange.getBegin(), diag::warn_cast_align)
9259 << Op->getType() << T
9260 << static_cast<unsigned>(SrcAlign.getQuantity())
9261 << static_cast<unsigned>(DestAlign.getQuantity())
9262 << TRange << Op->getSourceRange();
9263}
9264
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009265static const Type* getElementType(const Expr *BaseExpr) {
9266 const Type* EltType = BaseExpr->getType().getTypePtr();
9267 if (EltType->isAnyPointerType())
9268 return EltType->getPointeeType().getTypePtr();
9269 else if (EltType->isArrayType())
9270 return EltType->getBaseElementTypeUnsafe();
9271 return EltType;
9272}
9273
Chandler Carruth28389f02011-08-05 09:10:50 +00009274/// \brief Check whether this array fits the idiom of a size-one tail padded
9275/// array member of a struct.
9276///
9277/// We avoid emitting out-of-bounds access warnings for such arrays as they are
9278/// commonly used to emulate flexible arrays in C89 code.
9279static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
9280 const NamedDecl *ND) {
9281 if (Size != 1 || !ND) return false;
9282
9283 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
9284 if (!FD) return false;
9285
9286 // Don't consider sizes resulting from macro expansions or template argument
9287 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00009288
9289 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00009290 while (TInfo) {
9291 TypeLoc TL = TInfo->getTypeLoc();
9292 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00009293 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
9294 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00009295 TInfo = TDL->getTypeSourceInfo();
9296 continue;
9297 }
David Blaikie6adc78e2013-02-18 22:06:02 +00009298 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
9299 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00009300 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
9301 return false;
9302 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00009303 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00009304 }
Chandler Carruth28389f02011-08-05 09:10:50 +00009305
9306 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00009307 if (!RD) return false;
9308 if (RD->isUnion()) return false;
9309 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
9310 if (!CRD->isStandardLayout()) return false;
9311 }
Chandler Carruth28389f02011-08-05 09:10:50 +00009312
Benjamin Kramer8c543672011-08-06 03:04:42 +00009313 // See if this is the last field decl in the record.
9314 const Decl *D = FD;
9315 while ((D = D->getNextDeclInContext()))
9316 if (isa<FieldDecl>(D))
9317 return false;
9318 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00009319}
9320
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009321void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009322 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00009323 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009324 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009325 if (IndexExpr->isValueDependent())
9326 return;
9327
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00009328 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009329 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009330 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009331 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009332 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00009333 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00009334
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009335 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +00009336 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +00009337 return;
Richard Smith13f67182011-12-16 19:31:14 +00009338 if (IndexNegated)
9339 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00009340
Craig Topperc3ec1492014-05-26 06:22:03 +00009341 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00009342 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
9343 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00009344 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00009345 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00009346
Ted Kremeneke4b316c2011-02-23 23:06:04 +00009347 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00009348 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00009349 if (!size.isStrictlyPositive())
9350 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009351
9352 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00009353 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009354 // Make sure we're comparing apples to apples when comparing index to size
9355 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
9356 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00009357 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00009358 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009359 if (ptrarith_typesize != array_typesize) {
9360 // There's a cast to a different size type involved
9361 uint64_t ratio = array_typesize / ptrarith_typesize;
9362 // TODO: Be smarter about handling cases where array_typesize is not a
9363 // multiple of ptrarith_typesize
9364 if (ptrarith_typesize * ratio == array_typesize)
9365 size *= llvm::APInt(size.getBitWidth(), ratio);
9366 }
9367 }
9368
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009369 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009370 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00009371 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009372 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00009373
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009374 // For array subscripting the index must be less than size, but for pointer
9375 // arithmetic also allow the index (offset) to be equal to size since
9376 // computing the next address after the end of the array is legal and
9377 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009378 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00009379 return;
9380
9381 // Also don't warn for arrays of size 1 which are members of some
9382 // structure. These are often used to approximate flexible arrays in C89
9383 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009384 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00009385 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009386
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009387 // Suppress the warning if the subscript expression (as identified by the
9388 // ']' location) and the index expression are both from macro expansions
9389 // within a system header.
9390 if (ASE) {
9391 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
9392 ASE->getRBracketLoc());
9393 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
9394 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
9395 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00009396 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009397 return;
9398 }
9399 }
9400
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009401 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009402 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009403 DiagID = diag::warn_array_index_exceeds_bounds;
9404
9405 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
9406 PDiag(DiagID) << index.toString(10, true)
9407 << size.toString(10, true)
9408 << (unsigned)size.getLimitedValue(~0U)
9409 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009410 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009411 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009412 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009413 DiagID = diag::warn_ptr_arith_precedes_bounds;
9414 if (index.isNegative()) index = -index;
9415 }
9416
9417 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
9418 PDiag(DiagID) << index.toString(10, true)
9419 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00009420 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00009421
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00009422 if (!ND) {
9423 // Try harder to find a NamedDecl to point at in the note.
9424 while (const ArraySubscriptExpr *ASE =
9425 dyn_cast<ArraySubscriptExpr>(BaseExpr))
9426 BaseExpr = ASE->getBase()->IgnoreParenCasts();
9427 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
9428 ND = dyn_cast<NamedDecl>(DRE->getDecl());
9429 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
9430 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
9431 }
9432
Chandler Carruth1af88f12011-02-17 21:10:52 +00009433 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009434 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
9435 PDiag(diag::note_array_index_out_of_bounds)
9436 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00009437}
9438
Ted Kremenekdf26df72011-03-01 18:41:00 +00009439void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009440 int AllowOnePastEnd = 0;
9441 while (expr) {
9442 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00009443 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009444 case Stmt::ArraySubscriptExprClass: {
9445 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009446 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009447 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00009448 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009449 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +00009450 case Stmt::OMPArraySectionExprClass: {
9451 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
9452 if (ASE->getLowerBound())
9453 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
9454 /*ASE=*/nullptr, AllowOnePastEnd > 0);
9455 return;
9456 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009457 case Stmt::UnaryOperatorClass: {
9458 // Only unwrap the * and & unary operators
9459 const UnaryOperator *UO = cast<UnaryOperator>(expr);
9460 expr = UO->getSubExpr();
9461 switch (UO->getOpcode()) {
9462 case UO_AddrOf:
9463 AllowOnePastEnd++;
9464 break;
9465 case UO_Deref:
9466 AllowOnePastEnd--;
9467 break;
9468 default:
9469 return;
9470 }
9471 break;
9472 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00009473 case Stmt::ConditionalOperatorClass: {
9474 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
9475 if (const Expr *lhs = cond->getLHS())
9476 CheckArrayAccess(lhs);
9477 if (const Expr *rhs = cond->getRHS())
9478 CheckArrayAccess(rhs);
9479 return;
9480 }
9481 default:
9482 return;
9483 }
Peter Collingbourne91147592011-04-15 00:35:48 +00009484 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00009485}
John McCall31168b02011-06-15 23:02:42 +00009486
9487//===--- CHECK: Objective-C retain cycles ----------------------------------//
9488
9489namespace {
9490 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00009491 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00009492 VarDecl *Variable;
9493 SourceRange Range;
9494 SourceLocation Loc;
9495 bool Indirect;
9496
9497 void setLocsFrom(Expr *e) {
9498 Loc = e->getExprLoc();
9499 Range = e->getSourceRange();
9500 }
9501 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009502} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +00009503
9504/// Consider whether capturing the given variable can possibly lead to
9505/// a retain cycle.
9506static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00009507 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00009508 // lifetime. In MRR, it's captured strongly if the variable is
9509 // __block and has an appropriate type.
9510 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
9511 return false;
9512
9513 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009514 if (ref)
9515 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00009516 return true;
9517}
9518
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009519static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00009520 while (true) {
9521 e = e->IgnoreParens();
9522 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
9523 switch (cast->getCastKind()) {
9524 case CK_BitCast:
9525 case CK_LValueBitCast:
9526 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00009527 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00009528 e = cast->getSubExpr();
9529 continue;
9530
John McCall31168b02011-06-15 23:02:42 +00009531 default:
9532 return false;
9533 }
9534 }
9535
9536 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
9537 ObjCIvarDecl *ivar = ref->getDecl();
9538 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
9539 return false;
9540
9541 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009542 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00009543 return false;
9544
9545 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
9546 owner.Indirect = true;
9547 return true;
9548 }
9549
9550 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
9551 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
9552 if (!var) return false;
9553 return considerVariable(var, ref, owner);
9554 }
9555
John McCall31168b02011-06-15 23:02:42 +00009556 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
9557 if (member->isArrow()) return false;
9558
9559 // Don't count this as an indirect ownership.
9560 e = member->getBase();
9561 continue;
9562 }
9563
John McCallfe96e0b2011-11-06 09:01:30 +00009564 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
9565 // Only pay attention to pseudo-objects on property references.
9566 ObjCPropertyRefExpr *pre
9567 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
9568 ->IgnoreParens());
9569 if (!pre) return false;
9570 if (pre->isImplicitProperty()) return false;
9571 ObjCPropertyDecl *property = pre->getExplicitProperty();
9572 if (!property->isRetaining() &&
9573 !(property->getPropertyIvarDecl() &&
9574 property->getPropertyIvarDecl()->getType()
9575 .getObjCLifetime() == Qualifiers::OCL_Strong))
9576 return false;
9577
9578 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009579 if (pre->isSuperReceiver()) {
9580 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
9581 if (!owner.Variable)
9582 return false;
9583 owner.Loc = pre->getLocation();
9584 owner.Range = pre->getSourceRange();
9585 return true;
9586 }
John McCallfe96e0b2011-11-06 09:01:30 +00009587 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
9588 ->getSourceExpr());
9589 continue;
9590 }
9591
John McCall31168b02011-06-15 23:02:42 +00009592 // Array ivars?
9593
9594 return false;
9595 }
9596}
9597
9598namespace {
9599 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
9600 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
9601 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009602 Context(Context), Variable(variable), Capturer(nullptr),
9603 VarWillBeReased(false) {}
9604 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +00009605 VarDecl *Variable;
9606 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009607 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +00009608
9609 void VisitDeclRefExpr(DeclRefExpr *ref) {
9610 if (ref->getDecl() == Variable && !Capturer)
9611 Capturer = ref;
9612 }
9613
John McCall31168b02011-06-15 23:02:42 +00009614 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
9615 if (Capturer) return;
9616 Visit(ref->getBase());
9617 if (Capturer && ref->isFreeIvar())
9618 Capturer = ref;
9619 }
9620
9621 void VisitBlockExpr(BlockExpr *block) {
9622 // Look inside nested blocks
9623 if (block->getBlockDecl()->capturesVariable(Variable))
9624 Visit(block->getBlockDecl()->getBody());
9625 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00009626
9627 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
9628 if (Capturer) return;
9629 if (OVE->getSourceExpr())
9630 Visit(OVE->getSourceExpr());
9631 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009632 void VisitBinaryOperator(BinaryOperator *BinOp) {
9633 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
9634 return;
9635 Expr *LHS = BinOp->getLHS();
9636 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
9637 if (DRE->getDecl() != Variable)
9638 return;
9639 if (Expr *RHS = BinOp->getRHS()) {
9640 RHS = RHS->IgnoreParenCasts();
9641 llvm::APSInt Value;
9642 VarWillBeReased =
9643 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
9644 }
9645 }
9646 }
John McCall31168b02011-06-15 23:02:42 +00009647 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009648} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +00009649
9650/// Check whether the given argument is a block which captures a
9651/// variable.
9652static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
9653 assert(owner.Variable && owner.Loc.isValid());
9654
9655 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00009656
9657 // Look through [^{...} copy] and Block_copy(^{...}).
9658 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
9659 Selector Cmd = ME->getSelector();
9660 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
9661 e = ME->getInstanceReceiver();
9662 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +00009663 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +00009664 e = e->IgnoreParenCasts();
9665 }
9666 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
9667 if (CE->getNumArgs() == 1) {
9668 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00009669 if (Fn) {
9670 const IdentifierInfo *FnI = Fn->getIdentifier();
9671 if (FnI && FnI->isStr("_Block_copy")) {
9672 e = CE->getArg(0)->IgnoreParenCasts();
9673 }
9674 }
Jordan Rose67e887c2012-09-17 17:54:30 +00009675 }
9676 }
9677
John McCall31168b02011-06-15 23:02:42 +00009678 BlockExpr *block = dyn_cast<BlockExpr>(e);
9679 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +00009680 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00009681
9682 FindCaptureVisitor visitor(S.Context, owner.Variable);
9683 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009684 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +00009685}
9686
9687static void diagnoseRetainCycle(Sema &S, Expr *capturer,
9688 RetainCycleOwner &owner) {
9689 assert(capturer);
9690 assert(owner.Variable && owner.Loc.isValid());
9691
9692 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
9693 << owner.Variable << capturer->getSourceRange();
9694 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
9695 << owner.Indirect << owner.Range;
9696}
9697
9698/// Check for a keyword selector that starts with the word 'add' or
9699/// 'set'.
9700static bool isSetterLikeSelector(Selector sel) {
9701 if (sel.isUnarySelector()) return false;
9702
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009703 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00009704 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00009705 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00009706 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00009707 else if (str.startswith("add")) {
9708 // Specially whitelist 'addOperationWithBlock:'.
9709 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
9710 return false;
9711 str = str.substr(3);
9712 }
John McCall31168b02011-06-15 23:02:42 +00009713 else
9714 return false;
9715
9716 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00009717 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00009718}
9719
Benjamin Kramer3a743452015-03-09 15:03:32 +00009720static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
9721 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009722 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
9723 Message->getReceiverInterface(),
9724 NSAPI::ClassId_NSMutableArray);
9725 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009726 return None;
9727 }
9728
9729 Selector Sel = Message->getSelector();
9730
9731 Optional<NSAPI::NSArrayMethodKind> MKOpt =
9732 S.NSAPIObj->getNSArrayMethodKind(Sel);
9733 if (!MKOpt) {
9734 return None;
9735 }
9736
9737 NSAPI::NSArrayMethodKind MK = *MKOpt;
9738
9739 switch (MK) {
9740 case NSAPI::NSMutableArr_addObject:
9741 case NSAPI::NSMutableArr_insertObjectAtIndex:
9742 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
9743 return 0;
9744 case NSAPI::NSMutableArr_replaceObjectAtIndex:
9745 return 1;
9746
9747 default:
9748 return None;
9749 }
9750
9751 return None;
9752}
9753
9754static
9755Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
9756 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009757 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
9758 Message->getReceiverInterface(),
9759 NSAPI::ClassId_NSMutableDictionary);
9760 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009761 return None;
9762 }
9763
9764 Selector Sel = Message->getSelector();
9765
9766 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
9767 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
9768 if (!MKOpt) {
9769 return None;
9770 }
9771
9772 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
9773
9774 switch (MK) {
9775 case NSAPI::NSMutableDict_setObjectForKey:
9776 case NSAPI::NSMutableDict_setValueForKey:
9777 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
9778 return 0;
9779
9780 default:
9781 return None;
9782 }
9783
9784 return None;
9785}
9786
9787static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009788 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
9789 Message->getReceiverInterface(),
9790 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +00009791
Alex Denisov5dfac812015-08-06 04:51:14 +00009792 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
9793 Message->getReceiverInterface(),
9794 NSAPI::ClassId_NSMutableOrderedSet);
9795 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009796 return None;
9797 }
9798
9799 Selector Sel = Message->getSelector();
9800
9801 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
9802 if (!MKOpt) {
9803 return None;
9804 }
9805
9806 NSAPI::NSSetMethodKind MK = *MKOpt;
9807
9808 switch (MK) {
9809 case NSAPI::NSMutableSet_addObject:
9810 case NSAPI::NSOrderedSet_setObjectAtIndex:
9811 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
9812 case NSAPI::NSOrderedSet_insertObjectAtIndex:
9813 return 0;
9814 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
9815 return 1;
9816 }
9817
9818 return None;
9819}
9820
9821void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
9822 if (!Message->isInstanceMessage()) {
9823 return;
9824 }
9825
9826 Optional<int> ArgOpt;
9827
9828 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
9829 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
9830 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
9831 return;
9832 }
9833
9834 int ArgIndex = *ArgOpt;
9835
Alex Denisove1d882c2015-03-04 17:55:52 +00009836 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
9837 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
9838 Arg = OE->getSourceExpr()->IgnoreImpCasts();
9839 }
9840
Alex Denisov5dfac812015-08-06 04:51:14 +00009841 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009842 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009843 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009844 Diag(Message->getSourceRange().getBegin(),
9845 diag::warn_objc_circular_container)
Alex Denisov5dfac812015-08-06 04:51:14 +00009846 << ArgRE->getDecl()->getName() << StringRef("super");
Alex Denisove1d882c2015-03-04 17:55:52 +00009847 }
9848 }
Alex Denisov5dfac812015-08-06 04:51:14 +00009849 } else {
9850 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
9851
9852 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
9853 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
9854 }
9855
9856 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
9857 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
9858 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
9859 ValueDecl *Decl = ReceiverRE->getDecl();
9860 Diag(Message->getSourceRange().getBegin(),
9861 diag::warn_objc_circular_container)
9862 << Decl->getName() << Decl->getName();
9863 if (!ArgRE->isObjCSelfExpr()) {
9864 Diag(Decl->getLocation(),
9865 diag::note_objc_circular_container_declared_here)
9866 << Decl->getName();
9867 }
9868 }
9869 }
9870 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
9871 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
9872 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
9873 ObjCIvarDecl *Decl = IvarRE->getDecl();
9874 Diag(Message->getSourceRange().getBegin(),
9875 diag::warn_objc_circular_container)
9876 << Decl->getName() << Decl->getName();
9877 Diag(Decl->getLocation(),
9878 diag::note_objc_circular_container_declared_here)
9879 << Decl->getName();
9880 }
Alex Denisove1d882c2015-03-04 17:55:52 +00009881 }
9882 }
9883 }
Alex Denisove1d882c2015-03-04 17:55:52 +00009884}
9885
John McCall31168b02011-06-15 23:02:42 +00009886/// Check a message send to see if it's likely to cause a retain cycle.
9887void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
9888 // Only check instance methods whose selector looks like a setter.
9889 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
9890 return;
9891
9892 // Try to find a variable that the receiver is strongly owned by.
9893 RetainCycleOwner owner;
9894 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009895 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00009896 return;
9897 } else {
9898 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
9899 owner.Variable = getCurMethodDecl()->getSelfDecl();
9900 owner.Loc = msg->getSuperLoc();
9901 owner.Range = msg->getSuperLoc();
9902 }
9903
9904 // Check whether the receiver is captured by any of the arguments.
9905 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
9906 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
9907 return diagnoseRetainCycle(*this, capturer, owner);
9908}
9909
9910/// Check a property assign to see if it's likely to cause a retain cycle.
9911void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
9912 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009913 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00009914 return;
9915
9916 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
9917 diagnoseRetainCycle(*this, capturer, owner);
9918}
9919
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009920void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
9921 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +00009922 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009923 return;
9924
9925 // Because we don't have an expression for the variable, we have to set the
9926 // location explicitly here.
9927 Owner.Loc = Var->getLocation();
9928 Owner.Range = Var->getSourceRange();
9929
9930 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
9931 diagnoseRetainCycle(*this, Capturer, Owner);
9932}
9933
Ted Kremenek9304da92012-12-21 08:04:28 +00009934static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
9935 Expr *RHS, bool isProperty) {
9936 // Check if RHS is an Objective-C object literal, which also can get
9937 // immediately zapped in a weak reference. Note that we explicitly
9938 // allow ObjCStringLiterals, since those are designed to never really die.
9939 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009940
Ted Kremenek64873352012-12-21 22:46:35 +00009941 // This enum needs to match with the 'select' in
9942 // warn_objc_arc_literal_assign (off-by-1).
9943 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
9944 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
9945 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009946
9947 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00009948 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00009949 << (isProperty ? 0 : 1)
9950 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009951
9952 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00009953}
9954
Ted Kremenekc1f014a2012-12-21 19:45:30 +00009955static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
9956 Qualifiers::ObjCLifetime LT,
9957 Expr *RHS, bool isProperty) {
9958 // Strip off any implicit cast added to get to the one ARC-specific.
9959 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
9960 if (cast->getCastKind() == CK_ARCConsumeObject) {
9961 S.Diag(Loc, diag::warn_arc_retained_assign)
9962 << (LT == Qualifiers::OCL_ExplicitNone)
9963 << (isProperty ? 0 : 1)
9964 << RHS->getSourceRange();
9965 return true;
9966 }
9967 RHS = cast->getSubExpr();
9968 }
9969
9970 if (LT == Qualifiers::OCL_Weak &&
9971 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
9972 return true;
9973
9974 return false;
9975}
9976
Ted Kremenekb36234d2012-12-21 08:04:20 +00009977bool Sema::checkUnsafeAssigns(SourceLocation Loc,
9978 QualType LHS, Expr *RHS) {
9979 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
9980
9981 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
9982 return false;
9983
9984 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
9985 return true;
9986
9987 return false;
9988}
9989
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009990void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
9991 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009992 QualType LHSType;
9993 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00009994 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009995 ObjCPropertyRefExpr *PRE
9996 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
9997 if (PRE && !PRE->isImplicitProperty()) {
9998 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
9999 if (PD)
10000 LHSType = PD->getType();
10001 }
10002
10003 if (LHSType.isNull())
10004 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +000010005
10006 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
10007
10008 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010009 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +000010010 getCurFunction()->markSafeWeakUse(LHS);
10011 }
10012
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010013 if (checkUnsafeAssigns(Loc, LHSType, RHS))
10014 return;
Jordan Rose657b5f42012-09-28 22:21:35 +000010015
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010016 // FIXME. Check for other life times.
10017 if (LT != Qualifiers::OCL_None)
10018 return;
10019
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010020 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010021 if (PRE->isImplicitProperty())
10022 return;
10023 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
10024 if (!PD)
10025 return;
10026
Bill Wendling44426052012-12-20 19:22:21 +000010027 unsigned Attributes = PD->getPropertyAttributes();
10028 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010029 // when 'assign' attribute was not explicitly specified
10030 // by user, ignore it and rely on property type itself
10031 // for lifetime info.
10032 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
10033 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
10034 LHSType->isObjCRetainableType())
10035 return;
10036
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010037 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +000010038 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010039 Diag(Loc, diag::warn_arc_retained_property_assign)
10040 << RHS->getSourceRange();
10041 return;
10042 }
10043 RHS = cast->getSubExpr();
10044 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010045 }
Bill Wendling44426052012-12-20 19:22:21 +000010046 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +000010047 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
10048 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +000010049 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010050 }
10051}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010052
10053//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
10054
10055namespace {
10056bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
10057 SourceLocation StmtLoc,
10058 const NullStmt *Body) {
10059 // Do not warn if the body is a macro that expands to nothing, e.g:
10060 //
10061 // #define CALL(x)
10062 // if (condition)
10063 // CALL(0);
10064 //
10065 if (Body->hasLeadingEmptyMacro())
10066 return false;
10067
10068 // Get line numbers of statement and body.
10069 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +000010070 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010071 &StmtLineInvalid);
10072 if (StmtLineInvalid)
10073 return false;
10074
10075 bool BodyLineInvalid;
10076 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
10077 &BodyLineInvalid);
10078 if (BodyLineInvalid)
10079 return false;
10080
10081 // Warn if null statement and body are on the same line.
10082 if (StmtLine != BodyLine)
10083 return false;
10084
10085 return true;
10086}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010087} // end anonymous namespace
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010088
10089void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
10090 const Stmt *Body,
10091 unsigned DiagID) {
10092 // Since this is a syntactic check, don't emit diagnostic for template
10093 // instantiations, this just adds noise.
10094 if (CurrentInstantiationScope)
10095 return;
10096
10097 // The body should be a null statement.
10098 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
10099 if (!NBody)
10100 return;
10101
10102 // Do the usual checks.
10103 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
10104 return;
10105
10106 Diag(NBody->getSemiLoc(), DiagID);
10107 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
10108}
10109
10110void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
10111 const Stmt *PossibleBody) {
10112 assert(!CurrentInstantiationScope); // Ensured by caller
10113
10114 SourceLocation StmtLoc;
10115 const Stmt *Body;
10116 unsigned DiagID;
10117 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
10118 StmtLoc = FS->getRParenLoc();
10119 Body = FS->getBody();
10120 DiagID = diag::warn_empty_for_body;
10121 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
10122 StmtLoc = WS->getCond()->getSourceRange().getEnd();
10123 Body = WS->getBody();
10124 DiagID = diag::warn_empty_while_body;
10125 } else
10126 return; // Neither `for' nor `while'.
10127
10128 // The body should be a null statement.
10129 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
10130 if (!NBody)
10131 return;
10132
10133 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010134 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010135 return;
10136
10137 // Do the usual checks.
10138 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
10139 return;
10140
10141 // `for(...);' and `while(...);' are popular idioms, so in order to keep
10142 // noise level low, emit diagnostics only if for/while is followed by a
10143 // CompoundStmt, e.g.:
10144 // for (int i = 0; i < n; i++);
10145 // {
10146 // a(i);
10147 // }
10148 // or if for/while is followed by a statement with more indentation
10149 // than for/while itself:
10150 // for (int i = 0; i < n; i++);
10151 // a(i);
10152 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
10153 if (!ProbableTypo) {
10154 bool BodyColInvalid;
10155 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
10156 PossibleBody->getLocStart(),
10157 &BodyColInvalid);
10158 if (BodyColInvalid)
10159 return;
10160
10161 bool StmtColInvalid;
10162 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
10163 S->getLocStart(),
10164 &StmtColInvalid);
10165 if (StmtColInvalid)
10166 return;
10167
10168 if (BodyCol > StmtCol)
10169 ProbableTypo = true;
10170 }
10171
10172 if (ProbableTypo) {
10173 Diag(NBody->getSemiLoc(), DiagID);
10174 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
10175 }
10176}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010177
Richard Trieu36d0b2b2015-01-13 02:32:02 +000010178//===--- CHECK: Warn on self move with std::move. -------------------------===//
10179
10180/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
10181void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
10182 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +000010183 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
10184 return;
10185
10186 if (!ActiveTemplateInstantiations.empty())
10187 return;
10188
10189 // Strip parens and casts away.
10190 LHSExpr = LHSExpr->IgnoreParenImpCasts();
10191 RHSExpr = RHSExpr->IgnoreParenImpCasts();
10192
10193 // Check for a call expression
10194 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
10195 if (!CE || CE->getNumArgs() != 1)
10196 return;
10197
10198 // Check for a call to std::move
10199 const FunctionDecl *FD = CE->getDirectCallee();
10200 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
10201 !FD->getIdentifier()->isStr("move"))
10202 return;
10203
10204 // Get argument from std::move
10205 RHSExpr = CE->getArg(0);
10206
10207 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
10208 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
10209
10210 // Two DeclRefExpr's, check that the decls are the same.
10211 if (LHSDeclRef && RHSDeclRef) {
10212 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
10213 return;
10214 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
10215 RHSDeclRef->getDecl()->getCanonicalDecl())
10216 return;
10217
10218 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10219 << LHSExpr->getSourceRange()
10220 << RHSExpr->getSourceRange();
10221 return;
10222 }
10223
10224 // Member variables require a different approach to check for self moves.
10225 // MemberExpr's are the same if every nested MemberExpr refers to the same
10226 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
10227 // the base Expr's are CXXThisExpr's.
10228 const Expr *LHSBase = LHSExpr;
10229 const Expr *RHSBase = RHSExpr;
10230 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
10231 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
10232 if (!LHSME || !RHSME)
10233 return;
10234
10235 while (LHSME && RHSME) {
10236 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
10237 RHSME->getMemberDecl()->getCanonicalDecl())
10238 return;
10239
10240 LHSBase = LHSME->getBase();
10241 RHSBase = RHSME->getBase();
10242 LHSME = dyn_cast<MemberExpr>(LHSBase);
10243 RHSME = dyn_cast<MemberExpr>(RHSBase);
10244 }
10245
10246 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
10247 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
10248 if (LHSDeclRef && RHSDeclRef) {
10249 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
10250 return;
10251 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
10252 RHSDeclRef->getDecl()->getCanonicalDecl())
10253 return;
10254
10255 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10256 << LHSExpr->getSourceRange()
10257 << RHSExpr->getSourceRange();
10258 return;
10259 }
10260
10261 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
10262 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10263 << LHSExpr->getSourceRange()
10264 << RHSExpr->getSourceRange();
10265}
10266
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010267//===--- Layout compatibility ----------------------------------------------//
10268
10269namespace {
10270
10271bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
10272
10273/// \brief Check if two enumeration types are layout-compatible.
10274bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
10275 // C++11 [dcl.enum] p8:
10276 // Two enumeration types are layout-compatible if they have the same
10277 // underlying type.
10278 return ED1->isComplete() && ED2->isComplete() &&
10279 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
10280}
10281
10282/// \brief Check if two fields are layout-compatible.
10283bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
10284 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
10285 return false;
10286
10287 if (Field1->isBitField() != Field2->isBitField())
10288 return false;
10289
10290 if (Field1->isBitField()) {
10291 // Make sure that the bit-fields are the same length.
10292 unsigned Bits1 = Field1->getBitWidthValue(C);
10293 unsigned Bits2 = Field2->getBitWidthValue(C);
10294
10295 if (Bits1 != Bits2)
10296 return false;
10297 }
10298
10299 return true;
10300}
10301
10302/// \brief Check if two standard-layout structs are layout-compatible.
10303/// (C++11 [class.mem] p17)
10304bool isLayoutCompatibleStruct(ASTContext &C,
10305 RecordDecl *RD1,
10306 RecordDecl *RD2) {
10307 // If both records are C++ classes, check that base classes match.
10308 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
10309 // If one of records is a CXXRecordDecl we are in C++ mode,
10310 // thus the other one is a CXXRecordDecl, too.
10311 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
10312 // Check number of base classes.
10313 if (D1CXX->getNumBases() != D2CXX->getNumBases())
10314 return false;
10315
10316 // Check the base classes.
10317 for (CXXRecordDecl::base_class_const_iterator
10318 Base1 = D1CXX->bases_begin(),
10319 BaseEnd1 = D1CXX->bases_end(),
10320 Base2 = D2CXX->bases_begin();
10321 Base1 != BaseEnd1;
10322 ++Base1, ++Base2) {
10323 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
10324 return false;
10325 }
10326 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
10327 // If only RD2 is a C++ class, it should have zero base classes.
10328 if (D2CXX->getNumBases() > 0)
10329 return false;
10330 }
10331
10332 // Check the fields.
10333 RecordDecl::field_iterator Field2 = RD2->field_begin(),
10334 Field2End = RD2->field_end(),
10335 Field1 = RD1->field_begin(),
10336 Field1End = RD1->field_end();
10337 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
10338 if (!isLayoutCompatible(C, *Field1, *Field2))
10339 return false;
10340 }
10341 if (Field1 != Field1End || Field2 != Field2End)
10342 return false;
10343
10344 return true;
10345}
10346
10347/// \brief Check if two standard-layout unions are layout-compatible.
10348/// (C++11 [class.mem] p18)
10349bool isLayoutCompatibleUnion(ASTContext &C,
10350 RecordDecl *RD1,
10351 RecordDecl *RD2) {
10352 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010353 for (auto *Field2 : RD2->fields())
10354 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010355
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010356 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010357 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
10358 I = UnmatchedFields.begin(),
10359 E = UnmatchedFields.end();
10360
10361 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010362 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010363 bool Result = UnmatchedFields.erase(*I);
10364 (void) Result;
10365 assert(Result);
10366 break;
10367 }
10368 }
10369 if (I == E)
10370 return false;
10371 }
10372
10373 return UnmatchedFields.empty();
10374}
10375
10376bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
10377 if (RD1->isUnion() != RD2->isUnion())
10378 return false;
10379
10380 if (RD1->isUnion())
10381 return isLayoutCompatibleUnion(C, RD1, RD2);
10382 else
10383 return isLayoutCompatibleStruct(C, RD1, RD2);
10384}
10385
10386/// \brief Check if two types are layout-compatible in C++11 sense.
10387bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
10388 if (T1.isNull() || T2.isNull())
10389 return false;
10390
10391 // C++11 [basic.types] p11:
10392 // If two types T1 and T2 are the same type, then T1 and T2 are
10393 // layout-compatible types.
10394 if (C.hasSameType(T1, T2))
10395 return true;
10396
10397 T1 = T1.getCanonicalType().getUnqualifiedType();
10398 T2 = T2.getCanonicalType().getUnqualifiedType();
10399
10400 const Type::TypeClass TC1 = T1->getTypeClass();
10401 const Type::TypeClass TC2 = T2->getTypeClass();
10402
10403 if (TC1 != TC2)
10404 return false;
10405
10406 if (TC1 == Type::Enum) {
10407 return isLayoutCompatible(C,
10408 cast<EnumType>(T1)->getDecl(),
10409 cast<EnumType>(T2)->getDecl());
10410 } else if (TC1 == Type::Record) {
10411 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
10412 return false;
10413
10414 return isLayoutCompatible(C,
10415 cast<RecordType>(T1)->getDecl(),
10416 cast<RecordType>(T2)->getDecl());
10417 }
10418
10419 return false;
10420}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010421} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010422
10423//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
10424
10425namespace {
10426/// \brief Given a type tag expression find the type tag itself.
10427///
10428/// \param TypeExpr Type tag expression, as it appears in user's code.
10429///
10430/// \param VD Declaration of an identifier that appears in a type tag.
10431///
10432/// \param MagicValue Type tag magic value.
10433bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
10434 const ValueDecl **VD, uint64_t *MagicValue) {
10435 while(true) {
10436 if (!TypeExpr)
10437 return false;
10438
10439 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
10440
10441 switch (TypeExpr->getStmtClass()) {
10442 case Stmt::UnaryOperatorClass: {
10443 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
10444 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
10445 TypeExpr = UO->getSubExpr();
10446 continue;
10447 }
10448 return false;
10449 }
10450
10451 case Stmt::DeclRefExprClass: {
10452 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
10453 *VD = DRE->getDecl();
10454 return true;
10455 }
10456
10457 case Stmt::IntegerLiteralClass: {
10458 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
10459 llvm::APInt MagicValueAPInt = IL->getValue();
10460 if (MagicValueAPInt.getActiveBits() <= 64) {
10461 *MagicValue = MagicValueAPInt.getZExtValue();
10462 return true;
10463 } else
10464 return false;
10465 }
10466
10467 case Stmt::BinaryConditionalOperatorClass:
10468 case Stmt::ConditionalOperatorClass: {
10469 const AbstractConditionalOperator *ACO =
10470 cast<AbstractConditionalOperator>(TypeExpr);
10471 bool Result;
10472 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
10473 if (Result)
10474 TypeExpr = ACO->getTrueExpr();
10475 else
10476 TypeExpr = ACO->getFalseExpr();
10477 continue;
10478 }
10479 return false;
10480 }
10481
10482 case Stmt::BinaryOperatorClass: {
10483 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
10484 if (BO->getOpcode() == BO_Comma) {
10485 TypeExpr = BO->getRHS();
10486 continue;
10487 }
10488 return false;
10489 }
10490
10491 default:
10492 return false;
10493 }
10494 }
10495}
10496
10497/// \brief Retrieve the C type corresponding to type tag TypeExpr.
10498///
10499/// \param TypeExpr Expression that specifies a type tag.
10500///
10501/// \param MagicValues Registered magic values.
10502///
10503/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
10504/// kind.
10505///
10506/// \param TypeInfo Information about the corresponding C type.
10507///
10508/// \returns true if the corresponding C type was found.
10509bool GetMatchingCType(
10510 const IdentifierInfo *ArgumentKind,
10511 const Expr *TypeExpr, const ASTContext &Ctx,
10512 const llvm::DenseMap<Sema::TypeTagMagicValue,
10513 Sema::TypeTagData> *MagicValues,
10514 bool &FoundWrongKind,
10515 Sema::TypeTagData &TypeInfo) {
10516 FoundWrongKind = false;
10517
10518 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000010519 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010520
10521 uint64_t MagicValue;
10522
10523 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
10524 return false;
10525
10526 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000010527 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010528 if (I->getArgumentKind() != ArgumentKind) {
10529 FoundWrongKind = true;
10530 return false;
10531 }
10532 TypeInfo.Type = I->getMatchingCType();
10533 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
10534 TypeInfo.MustBeNull = I->getMustBeNull();
10535 return true;
10536 }
10537 return false;
10538 }
10539
10540 if (!MagicValues)
10541 return false;
10542
10543 llvm::DenseMap<Sema::TypeTagMagicValue,
10544 Sema::TypeTagData>::const_iterator I =
10545 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
10546 if (I == MagicValues->end())
10547 return false;
10548
10549 TypeInfo = I->second;
10550 return true;
10551}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010552} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010553
10554void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
10555 uint64_t MagicValue, QualType Type,
10556 bool LayoutCompatible,
10557 bool MustBeNull) {
10558 if (!TypeTagForDatatypeMagicValues)
10559 TypeTagForDatatypeMagicValues.reset(
10560 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
10561
10562 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
10563 (*TypeTagForDatatypeMagicValues)[Magic] =
10564 TypeTagData(Type, LayoutCompatible, MustBeNull);
10565}
10566
10567namespace {
10568bool IsSameCharType(QualType T1, QualType T2) {
10569 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
10570 if (!BT1)
10571 return false;
10572
10573 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
10574 if (!BT2)
10575 return false;
10576
10577 BuiltinType::Kind T1Kind = BT1->getKind();
10578 BuiltinType::Kind T2Kind = BT2->getKind();
10579
10580 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
10581 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
10582 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
10583 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
10584}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010585} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010586
10587void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
10588 const Expr * const *ExprArgs) {
10589 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
10590 bool IsPointerAttr = Attr->getIsPointer();
10591
10592 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
10593 bool FoundWrongKind;
10594 TypeTagData TypeInfo;
10595 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
10596 TypeTagForDatatypeMagicValues.get(),
10597 FoundWrongKind, TypeInfo)) {
10598 if (FoundWrongKind)
10599 Diag(TypeTagExpr->getExprLoc(),
10600 diag::warn_type_tag_for_datatype_wrong_kind)
10601 << TypeTagExpr->getSourceRange();
10602 return;
10603 }
10604
10605 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
10606 if (IsPointerAttr) {
10607 // Skip implicit cast of pointer to `void *' (as a function argument).
10608 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000010609 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000010610 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010611 ArgumentExpr = ICE->getSubExpr();
10612 }
10613 QualType ArgumentType = ArgumentExpr->getType();
10614
10615 // Passing a `void*' pointer shouldn't trigger a warning.
10616 if (IsPointerAttr && ArgumentType->isVoidPointerType())
10617 return;
10618
10619 if (TypeInfo.MustBeNull) {
10620 // Type tag with matching void type requires a null pointer.
10621 if (!ArgumentExpr->isNullPointerConstant(Context,
10622 Expr::NPC_ValueDependentIsNotNull)) {
10623 Diag(ArgumentExpr->getExprLoc(),
10624 diag::warn_type_safety_null_pointer_required)
10625 << ArgumentKind->getName()
10626 << ArgumentExpr->getSourceRange()
10627 << TypeTagExpr->getSourceRange();
10628 }
10629 return;
10630 }
10631
10632 QualType RequiredType = TypeInfo.Type;
10633 if (IsPointerAttr)
10634 RequiredType = Context.getPointerType(RequiredType);
10635
10636 bool mismatch = false;
10637 if (!TypeInfo.LayoutCompatible) {
10638 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
10639
10640 // C++11 [basic.fundamental] p1:
10641 // Plain char, signed char, and unsigned char are three distinct types.
10642 //
10643 // But we treat plain `char' as equivalent to `signed char' or `unsigned
10644 // char' depending on the current char signedness mode.
10645 if (mismatch)
10646 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
10647 RequiredType->getPointeeType())) ||
10648 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
10649 mismatch = false;
10650 } else
10651 if (IsPointerAttr)
10652 mismatch = !isLayoutCompatible(Context,
10653 ArgumentType->getPointeeType(),
10654 RequiredType->getPointeeType());
10655 else
10656 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
10657
10658 if (mismatch)
10659 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000010660 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010661 << TypeInfo.LayoutCompatible << RequiredType
10662 << ArgumentExpr->getSourceRange()
10663 << TypeTagExpr->getSourceRange();
10664}