blob: ec01b04fcf95a0b96439052b2ca2af472833f04b [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
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000264static inline bool isBlockPointer(Expr *Arg) {
265 return Arg->getType()->isBlockPointerType();
266}
267
268/// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
269/// void*, which is a requirement of device side enqueue.
270static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
271 const BlockPointerType *BPT =
272 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
273 ArrayRef<QualType> Params =
274 BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
275 unsigned ArgCounter = 0;
276 bool IllegalParams = false;
277 // Iterate through the block parameters until either one is found that is not
278 // a local void*, or the block is valid.
279 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
280 I != E; ++I, ++ArgCounter) {
281 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
282 (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
283 LangAS::opencl_local) {
284 // Get the location of the error. If a block literal has been passed
285 // (BlockExpr) then we can point straight to the offending argument,
286 // else we just point to the variable reference.
287 SourceLocation ErrorLoc;
288 if (isa<BlockExpr>(BlockArg)) {
289 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
290 ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart();
291 } else if (isa<DeclRefExpr>(BlockArg)) {
292 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart();
293 }
294 S.Diag(ErrorLoc,
295 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
296 IllegalParams = true;
297 }
298 }
299
300 return IllegalParams;
301}
302
303/// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
304/// get_kernel_work_group_size
305/// and get_kernel_preferred_work_group_size_multiple builtin functions.
306static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
307 if (checkArgCount(S, TheCall, 1))
308 return true;
309
310 Expr *BlockArg = TheCall->getArg(0);
311 if (!isBlockPointer(BlockArg)) {
312 S.Diag(BlockArg->getLocStart(),
313 diag::err_opencl_enqueue_kernel_expected_type) << "block";
314 return true;
315 }
316 return checkOpenCLBlockArgs(S, BlockArg);
317}
318
319static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
320 unsigned Start, unsigned End);
321
322/// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
323/// 'local void*' parameter of passed block.
324static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
325 Expr *BlockArg,
326 unsigned NumNonVarArgs) {
327 const BlockPointerType *BPT =
328 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
329 unsigned NumBlockParams =
330 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
331 unsigned TotalNumArgs = TheCall->getNumArgs();
332
333 // For each argument passed to the block, a corresponding uint needs to
334 // be passed to describe the size of the local memory.
335 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
336 S.Diag(TheCall->getLocStart(),
337 diag::err_opencl_enqueue_kernel_local_size_args);
338 return true;
339 }
340
341 // Check that the sizes of the local memory are specified by integers.
342 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
343 TotalNumArgs - 1);
344}
345
346/// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
347/// overload formats specified in Table 6.13.17.1.
348/// int enqueue_kernel(queue_t queue,
349/// kernel_enqueue_flags_t flags,
350/// const ndrange_t ndrange,
351/// void (^block)(void))
352/// int enqueue_kernel(queue_t queue,
353/// kernel_enqueue_flags_t flags,
354/// const ndrange_t ndrange,
355/// uint num_events_in_wait_list,
356/// clk_event_t *event_wait_list,
357/// clk_event_t *event_ret,
358/// void (^block)(void))
359/// int enqueue_kernel(queue_t queue,
360/// kernel_enqueue_flags_t flags,
361/// const ndrange_t ndrange,
362/// void (^block)(local void*, ...),
363/// uint size0, ...)
364/// int enqueue_kernel(queue_t queue,
365/// kernel_enqueue_flags_t flags,
366/// const ndrange_t ndrange,
367/// uint num_events_in_wait_list,
368/// clk_event_t *event_wait_list,
369/// clk_event_t *event_ret,
370/// void (^block)(local void*, ...),
371/// uint size0, ...)
372static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
373 unsigned NumArgs = TheCall->getNumArgs();
374
375 if (NumArgs < 4) {
376 S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args);
377 return true;
378 }
379
380 Expr *Arg0 = TheCall->getArg(0);
381 Expr *Arg1 = TheCall->getArg(1);
382 Expr *Arg2 = TheCall->getArg(2);
383 Expr *Arg3 = TheCall->getArg(3);
384
385 // First argument always needs to be a queue_t type.
386 if (!Arg0->getType()->isQueueT()) {
387 S.Diag(TheCall->getArg(0)->getLocStart(),
388 diag::err_opencl_enqueue_kernel_expected_type)
389 << S.Context.OCLQueueTy;
390 return true;
391 }
392
393 // Second argument always needs to be a kernel_enqueue_flags_t enum value.
394 if (!Arg1->getType()->isIntegerType()) {
395 S.Diag(TheCall->getArg(1)->getLocStart(),
396 diag::err_opencl_enqueue_kernel_expected_type)
397 << "'kernel_enqueue_flags_t' (i.e. uint)";
398 return true;
399 }
400
401 // Third argument is always an ndrange_t type.
402 if (!Arg2->getType()->isNDRangeT()) {
403 S.Diag(TheCall->getArg(2)->getLocStart(),
404 diag::err_opencl_enqueue_kernel_expected_type)
405 << S.Context.OCLNDRangeTy;
406 return true;
407 }
408
409 // With four arguments, there is only one form that the function could be
410 // called in: no events and no variable arguments.
411 if (NumArgs == 4) {
412 // check that the last argument is the right block type.
413 if (!isBlockPointer(Arg3)) {
414 S.Diag(Arg3->getLocStart(), diag::err_opencl_enqueue_kernel_expected_type)
415 << "block";
416 return true;
417 }
418 // we have a block type, check the prototype
419 const BlockPointerType *BPT =
420 cast<BlockPointerType>(Arg3->getType().getCanonicalType());
421 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
422 S.Diag(Arg3->getLocStart(),
423 diag::err_opencl_enqueue_kernel_blocks_no_args);
424 return true;
425 }
426 return false;
427 }
428 // we can have block + varargs.
429 if (isBlockPointer(Arg3))
430 return (checkOpenCLBlockArgs(S, Arg3) ||
431 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
432 // last two cases with either exactly 7 args or 7 args and varargs.
433 if (NumArgs >= 7) {
434 // check common block argument.
435 Expr *Arg6 = TheCall->getArg(6);
436 if (!isBlockPointer(Arg6)) {
437 S.Diag(Arg6->getLocStart(), diag::err_opencl_enqueue_kernel_expected_type)
438 << "block";
439 return true;
440 }
441 if (checkOpenCLBlockArgs(S, Arg6))
442 return true;
443
444 // Forth argument has to be any integer type.
445 if (!Arg3->getType()->isIntegerType()) {
446 S.Diag(TheCall->getArg(3)->getLocStart(),
447 diag::err_opencl_enqueue_kernel_expected_type)
448 << "integer";
449 return true;
450 }
451 // check remaining common arguments.
452 Expr *Arg4 = TheCall->getArg(4);
453 Expr *Arg5 = TheCall->getArg(5);
454
455 // Fith argument is always passed as pointers to clk_event_t.
456 if (!Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
457 S.Diag(TheCall->getArg(4)->getLocStart(),
458 diag::err_opencl_enqueue_kernel_expected_type)
459 << S.Context.getPointerType(S.Context.OCLClkEventTy);
460 return true;
461 }
462
463 // Sixth argument is always passed as pointers to clk_event_t.
464 if (!(Arg5->getType()->isPointerType() &&
465 Arg5->getType()->getPointeeType()->isClkEventT())) {
466 S.Diag(TheCall->getArg(5)->getLocStart(),
467 diag::err_opencl_enqueue_kernel_expected_type)
468 << S.Context.getPointerType(S.Context.OCLClkEventTy);
469 return true;
470 }
471
472 if (NumArgs == 7)
473 return false;
474
475 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
476 }
477
478 // None of the specific case has been detected, give generic error
479 S.Diag(TheCall->getLocStart(),
480 diag::err_opencl_enqueue_kernel_incorrect_args);
481 return true;
482}
483
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000484/// Returns OpenCL access qual.
Xiuli Pan11e13f62016-02-26 03:13:03 +0000485static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
Xiuli Pan11e13f62016-02-26 03:13:03 +0000486 return D->getAttr<OpenCLAccessAttr>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000487}
488
489/// Returns true if pipe element type is different from the pointer.
490static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
491 const Expr *Arg0 = Call->getArg(0);
492 // First argument type should always be pipe.
493 if (!Arg0->getType()->isPipeType()) {
494 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000495 << Call->getDirectCallee() << Arg0->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000496 return true;
497 }
Xiuli Pan11e13f62016-02-26 03:13:03 +0000498 OpenCLAccessAttr *AccessQual =
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000499 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
500 // Validates the access qualifier is compatible with the call.
501 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
502 // read_only and write_only, and assumed to be read_only if no qualifier is
503 // specified.
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000504 switch (Call->getDirectCallee()->getBuiltinID()) {
505 case Builtin::BIread_pipe:
506 case Builtin::BIreserve_read_pipe:
507 case Builtin::BIcommit_read_pipe:
508 case Builtin::BIwork_group_reserve_read_pipe:
509 case Builtin::BIsub_group_reserve_read_pipe:
510 case Builtin::BIwork_group_commit_read_pipe:
511 case Builtin::BIsub_group_commit_read_pipe:
512 if (!(!AccessQual || AccessQual->isReadOnly())) {
513 S.Diag(Arg0->getLocStart(),
514 diag::err_opencl_builtin_pipe_invalid_access_modifier)
515 << "read_only" << Arg0->getSourceRange();
516 return true;
517 }
518 break;
519 case Builtin::BIwrite_pipe:
520 case Builtin::BIreserve_write_pipe:
521 case Builtin::BIcommit_write_pipe:
522 case Builtin::BIwork_group_reserve_write_pipe:
523 case Builtin::BIsub_group_reserve_write_pipe:
524 case Builtin::BIwork_group_commit_write_pipe:
525 case Builtin::BIsub_group_commit_write_pipe:
526 if (!(AccessQual && AccessQual->isWriteOnly())) {
527 S.Diag(Arg0->getLocStart(),
528 diag::err_opencl_builtin_pipe_invalid_access_modifier)
529 << "write_only" << Arg0->getSourceRange();
530 return true;
531 }
532 break;
533 default:
534 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000535 }
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000536 return false;
537}
538
539/// Returns true if pipe element type is different from the pointer.
540static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
541 const Expr *Arg0 = Call->getArg(0);
542 const Expr *ArgIdx = Call->getArg(Idx);
543 const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000544 const QualType EltTy = PipeTy->getElementType();
545 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000546 // The Idx argument should be a pointer and the type of the pointer and
547 // the type of pipe element should also be the same.
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000548 if (!ArgTy ||
549 !S.Context.hasSameType(
550 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000551 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000552 << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000553 << ArgIdx->getType() << ArgIdx->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000554 return true;
555 }
556 return false;
557}
558
559// \brief Performs semantic analysis for the read/write_pipe call.
560// \param S Reference to the semantic analyzer.
561// \param Call A pointer to the builtin call.
562// \return True if a semantic error has been found, false otherwise.
563static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000564 // OpenCL v2.0 s6.13.16.2 - The built-in read/write
565 // functions have two forms.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000566 switch (Call->getNumArgs()) {
567 case 2: {
568 if (checkOpenCLPipeArg(S, Call))
569 return true;
570 // The call with 2 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000571 // read/write_pipe(pipe T, T*).
572 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000573 if (checkOpenCLPipePacketType(S, Call, 1))
574 return true;
575 } break;
576
577 case 4: {
578 if (checkOpenCLPipeArg(S, Call))
579 return true;
580 // The call with 4 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000581 // read/write_pipe(pipe T, reserve_id_t, uint, T*).
582 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000583 if (!Call->getArg(1)->getType()->isReserveIDT()) {
584 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000585 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000586 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000587 return true;
588 }
589
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000590 // Check the index.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000591 const Expr *Arg2 = Call->getArg(2);
592 if (!Arg2->getType()->isIntegerType() &&
593 !Arg2->getType()->isUnsignedIntegerType()) {
594 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000595 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000596 << Arg2->getType() << Arg2->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000597 return true;
598 }
599
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000600 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000601 if (checkOpenCLPipePacketType(S, Call, 3))
602 return true;
603 } break;
604 default:
605 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000606 << Call->getDirectCallee() << Call->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000607 return true;
608 }
609
610 return false;
611}
612
613// \brief Performs a semantic analysis on the {work_group_/sub_group_
614// /_}reserve_{read/write}_pipe
615// \param S Reference to the semantic analyzer.
616// \param Call The call to the builtin function to be analyzed.
617// \return True if a semantic error was found, false otherwise.
618static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
619 if (checkArgCount(S, Call, 2))
620 return true;
621
622 if (checkOpenCLPipeArg(S, Call))
623 return true;
624
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000625 // Check the reserve size.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000626 if (!Call->getArg(1)->getType()->isIntegerType() &&
627 !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
628 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000629 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000630 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000631 return true;
632 }
633
634 return false;
635}
636
637// \brief Performs a semantic analysis on {work_group_/sub_group_
638// /_}commit_{read/write}_pipe
639// \param S Reference to the semantic analyzer.
640// \param Call The call to the builtin function to be analyzed.
641// \return True if a semantic error was found, false otherwise.
642static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
643 if (checkArgCount(S, Call, 2))
644 return true;
645
646 if (checkOpenCLPipeArg(S, Call))
647 return true;
648
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000649 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000650 if (!Call->getArg(1)->getType()->isReserveIDT()) {
651 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000652 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000653 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000654 return true;
655 }
656
657 return false;
658}
659
660// \brief Performs a semantic analysis on the call to built-in Pipe
661// Query Functions.
662// \param S Reference to the semantic analyzer.
663// \param Call The call to the builtin function to be analyzed.
664// \return True if a semantic error was found, false otherwise.
665static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
666 if (checkArgCount(S, Call, 1))
667 return true;
668
669 if (!Call->getArg(0)->getType()->isPipeType()) {
670 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000671 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000672 return true;
673 }
674
675 return false;
676}
Anastasia Stulova7f8d6dc2016-07-04 16:07:18 +0000677// \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions.
Yaxun Liuf7449a12016-05-20 19:54:38 +0000678// \brief Performs semantic analysis for the to_global/local/private call.
679// \param S Reference to the semantic analyzer.
680// \param BuiltinID ID of the builtin function.
681// \param Call A pointer to the builtin call.
682// \return True if a semantic error has been found, false otherwise.
683static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
684 CallExpr *Call) {
Yaxun Liuf7449a12016-05-20 19:54:38 +0000685 if (Call->getNumArgs() != 1) {
686 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
687 << Call->getDirectCallee() << Call->getSourceRange();
688 return true;
689 }
690
691 auto RT = Call->getArg(0)->getType();
692 if (!RT->isPointerType() || RT->getPointeeType()
693 .getAddressSpace() == LangAS::opencl_constant) {
694 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
695 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
696 return true;
697 }
698
699 RT = RT->getPointeeType();
700 auto Qual = RT.getQualifiers();
701 switch (BuiltinID) {
702 case Builtin::BIto_global:
703 Qual.setAddressSpace(LangAS::opencl_global);
704 break;
705 case Builtin::BIto_local:
706 Qual.setAddressSpace(LangAS::opencl_local);
707 break;
708 default:
709 Qual.removeAddressSpace();
710 }
711 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
712 RT.getUnqualifiedType(), Qual)));
713
714 return false;
715}
716
John McCalldadc5752010-08-24 06:29:42 +0000717ExprResult
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000718Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
719 CallExpr *TheCall) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000720 ExprResult TheCallResult(TheCall);
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000721
Chris Lattner3be167f2010-10-01 23:23:24 +0000722 // Find out if any arguments are required to be integer constant expressions.
723 unsigned ICEArguments = 0;
724 ASTContext::GetBuiltinTypeError Error;
725 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
726 if (Error != ASTContext::GE_None)
727 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
728
729 // If any arguments are required to be ICE's, check and diagnose.
730 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
731 // Skip arguments not required to be ICE's.
732 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
733
734 llvm::APSInt Result;
735 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
736 return true;
737 ICEArguments &= ~(1 << ArgNo);
738 }
739
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000740 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000741 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000742 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000743 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000744 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000745 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000746 break;
Ted Kremeneka174c522008-07-09 17:58:53 +0000747 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000748 case Builtin::BI__builtin_va_start:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000749 if (SemaBuiltinVAStart(TheCall))
750 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000751 break;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000752 case Builtin::BI__va_start: {
753 switch (Context.getTargetInfo().getTriple().getArch()) {
754 case llvm::Triple::arm:
755 case llvm::Triple::thumb:
756 if (SemaBuiltinVAStartARM(TheCall))
757 return ExprError();
758 break;
759 default:
760 if (SemaBuiltinVAStart(TheCall))
761 return ExprError();
762 break;
763 }
764 break;
765 }
Chris Lattner2da14fb2007-12-20 00:26:33 +0000766 case Builtin::BI__builtin_isgreater:
767 case Builtin::BI__builtin_isgreaterequal:
768 case Builtin::BI__builtin_isless:
769 case Builtin::BI__builtin_islessequal:
770 case Builtin::BI__builtin_islessgreater:
771 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000772 if (SemaBuiltinUnorderedCompare(TheCall))
773 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000774 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000775 case Builtin::BI__builtin_fpclassify:
776 if (SemaBuiltinFPClassification(TheCall, 6))
777 return ExprError();
778 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000779 case Builtin::BI__builtin_isfinite:
780 case Builtin::BI__builtin_isinf:
781 case Builtin::BI__builtin_isinf_sign:
782 case Builtin::BI__builtin_isnan:
783 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000784 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000785 return ExprError();
786 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000787 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000788 return SemaBuiltinShuffleVector(TheCall);
789 // TheCall will be freed by the smart pointer here, but that's fine, since
790 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000791 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000792 if (SemaBuiltinPrefetch(TheCall))
793 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000794 break;
Hal Finkelf0417332014-07-17 14:25:55 +0000795 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +0000796 case Builtin::BI__builtin_assume:
Hal Finkelf0417332014-07-17 14:25:55 +0000797 if (SemaBuiltinAssume(TheCall))
798 return ExprError();
799 break;
Hal Finkelbcc06082014-09-07 22:58:14 +0000800 case Builtin::BI__builtin_assume_aligned:
801 if (SemaBuiltinAssumeAligned(TheCall))
802 return ExprError();
803 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000804 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000805 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000806 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000807 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000808 case Builtin::BI__builtin_longjmp:
809 if (SemaBuiltinLongjmp(TheCall))
810 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000811 break;
Joerg Sonnenberger27173282015-03-11 23:46:32 +0000812 case Builtin::BI__builtin_setjmp:
813 if (SemaBuiltinSetjmp(TheCall))
814 return ExprError();
815 break;
David Majnemerc403a1c2015-03-20 17:03:35 +0000816 case Builtin::BI_setjmp:
817 case Builtin::BI_setjmpex:
818 if (checkArgCount(*this, TheCall, 1))
819 return true;
820 break;
John McCallbebede42011-02-26 05:39:39 +0000821
822 case Builtin::BI__builtin_classify_type:
823 if (checkArgCount(*this, TheCall, 1)) return true;
824 TheCall->setType(Context.IntTy);
825 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000826 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000827 if (checkArgCount(*this, TheCall, 1)) return true;
828 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000829 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000830 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000831 case Builtin::BI__sync_fetch_and_add_1:
832 case Builtin::BI__sync_fetch_and_add_2:
833 case Builtin::BI__sync_fetch_and_add_4:
834 case Builtin::BI__sync_fetch_and_add_8:
835 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000836 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000837 case Builtin::BI__sync_fetch_and_sub_1:
838 case Builtin::BI__sync_fetch_and_sub_2:
839 case Builtin::BI__sync_fetch_and_sub_4:
840 case Builtin::BI__sync_fetch_and_sub_8:
841 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000842 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000843 case Builtin::BI__sync_fetch_and_or_1:
844 case Builtin::BI__sync_fetch_and_or_2:
845 case Builtin::BI__sync_fetch_and_or_4:
846 case Builtin::BI__sync_fetch_and_or_8:
847 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000848 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000849 case Builtin::BI__sync_fetch_and_and_1:
850 case Builtin::BI__sync_fetch_and_and_2:
851 case Builtin::BI__sync_fetch_and_and_4:
852 case Builtin::BI__sync_fetch_and_and_8:
853 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000854 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000855 case Builtin::BI__sync_fetch_and_xor_1:
856 case Builtin::BI__sync_fetch_and_xor_2:
857 case Builtin::BI__sync_fetch_and_xor_4:
858 case Builtin::BI__sync_fetch_and_xor_8:
859 case Builtin::BI__sync_fetch_and_xor_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000860 case Builtin::BI__sync_fetch_and_nand:
861 case Builtin::BI__sync_fetch_and_nand_1:
862 case Builtin::BI__sync_fetch_and_nand_2:
863 case Builtin::BI__sync_fetch_and_nand_4:
864 case Builtin::BI__sync_fetch_and_nand_8:
865 case Builtin::BI__sync_fetch_and_nand_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000866 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000867 case Builtin::BI__sync_add_and_fetch_1:
868 case Builtin::BI__sync_add_and_fetch_2:
869 case Builtin::BI__sync_add_and_fetch_4:
870 case Builtin::BI__sync_add_and_fetch_8:
871 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000872 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000873 case Builtin::BI__sync_sub_and_fetch_1:
874 case Builtin::BI__sync_sub_and_fetch_2:
875 case Builtin::BI__sync_sub_and_fetch_4:
876 case Builtin::BI__sync_sub_and_fetch_8:
877 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000878 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000879 case Builtin::BI__sync_and_and_fetch_1:
880 case Builtin::BI__sync_and_and_fetch_2:
881 case Builtin::BI__sync_and_and_fetch_4:
882 case Builtin::BI__sync_and_and_fetch_8:
883 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000884 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000885 case Builtin::BI__sync_or_and_fetch_1:
886 case Builtin::BI__sync_or_and_fetch_2:
887 case Builtin::BI__sync_or_and_fetch_4:
888 case Builtin::BI__sync_or_and_fetch_8:
889 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000890 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000891 case Builtin::BI__sync_xor_and_fetch_1:
892 case Builtin::BI__sync_xor_and_fetch_2:
893 case Builtin::BI__sync_xor_and_fetch_4:
894 case Builtin::BI__sync_xor_and_fetch_8:
895 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000896 case Builtin::BI__sync_nand_and_fetch:
897 case Builtin::BI__sync_nand_and_fetch_1:
898 case Builtin::BI__sync_nand_and_fetch_2:
899 case Builtin::BI__sync_nand_and_fetch_4:
900 case Builtin::BI__sync_nand_and_fetch_8:
901 case Builtin::BI__sync_nand_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000902 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000903 case Builtin::BI__sync_val_compare_and_swap_1:
904 case Builtin::BI__sync_val_compare_and_swap_2:
905 case Builtin::BI__sync_val_compare_and_swap_4:
906 case Builtin::BI__sync_val_compare_and_swap_8:
907 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000908 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000909 case Builtin::BI__sync_bool_compare_and_swap_1:
910 case Builtin::BI__sync_bool_compare_and_swap_2:
911 case Builtin::BI__sync_bool_compare_and_swap_4:
912 case Builtin::BI__sync_bool_compare_and_swap_8:
913 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000914 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000915 case Builtin::BI__sync_lock_test_and_set_1:
916 case Builtin::BI__sync_lock_test_and_set_2:
917 case Builtin::BI__sync_lock_test_and_set_4:
918 case Builtin::BI__sync_lock_test_and_set_8:
919 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000920 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000921 case Builtin::BI__sync_lock_release_1:
922 case Builtin::BI__sync_lock_release_2:
923 case Builtin::BI__sync_lock_release_4:
924 case Builtin::BI__sync_lock_release_8:
925 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000926 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000927 case Builtin::BI__sync_swap_1:
928 case Builtin::BI__sync_swap_2:
929 case Builtin::BI__sync_swap_4:
930 case Builtin::BI__sync_swap_8:
931 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000932 return SemaBuiltinAtomicOverloaded(TheCallResult);
Michael Zolotukhin84df1232015-09-08 23:52:33 +0000933 case Builtin::BI__builtin_nontemporal_load:
934 case Builtin::BI__builtin_nontemporal_store:
935 return SemaBuiltinNontemporalOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +0000936#define BUILTIN(ID, TYPE, ATTRS)
937#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
938 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000939 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +0000940#include "clang/Basic/Builtins.def"
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000941 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000942 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000943 return ExprError();
944 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +0000945 case Builtin::BI__builtin_addressof:
946 if (SemaBuiltinAddressof(*this, TheCall))
947 return ExprError();
948 break;
John McCall03107a42015-10-29 20:48:01 +0000949 case Builtin::BI__builtin_add_overflow:
950 case Builtin::BI__builtin_sub_overflow:
951 case Builtin::BI__builtin_mul_overflow:
Craig Toppera86e70d2015-11-07 06:16:14 +0000952 if (SemaBuiltinOverflow(*this, TheCall))
953 return ExprError();
954 break;
Richard Smith760520b2014-06-03 23:27:44 +0000955 case Builtin::BI__builtin_operator_new:
956 case Builtin::BI__builtin_operator_delete:
957 if (!getLangOpts().CPlusPlus) {
958 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
959 << (BuiltinID == Builtin::BI__builtin_operator_new
960 ? "__builtin_operator_new"
961 : "__builtin_operator_delete")
962 << "C++";
963 return ExprError();
964 }
965 // CodeGen assumes it can find the global new and delete to call,
966 // so ensure that they are declared.
967 DeclareGlobalNewDelete();
968 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000969
970 // check secure string manipulation functions where overflows
971 // are detectable at compile time
972 case Builtin::BI__builtin___memcpy_chk:
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000973 case Builtin::BI__builtin___memmove_chk:
974 case Builtin::BI__builtin___memset_chk:
975 case Builtin::BI__builtin___strlcat_chk:
976 case Builtin::BI__builtin___strlcpy_chk:
977 case Builtin::BI__builtin___strncat_chk:
978 case Builtin::BI__builtin___strncpy_chk:
979 case Builtin::BI__builtin___stpncpy_chk:
980 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
981 break;
Steven Wu566c14e2014-09-24 04:37:33 +0000982 case Builtin::BI__builtin___memccpy_chk:
983 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
984 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000985 case Builtin::BI__builtin___snprintf_chk:
986 case Builtin::BI__builtin___vsnprintf_chk:
987 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
988 break;
Peter Collingbournef7706832014-12-12 23:41:25 +0000989 case Builtin::BI__builtin_call_with_static_chain:
990 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
991 return ExprError();
992 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000993 case Builtin::BI__exception_code:
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000994 case Builtin::BI_exception_code:
Reid Kleckner1d59f992015-01-22 01:36:17 +0000995 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
996 diag::err_seh___except_block))
997 return ExprError();
998 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000999 case Builtin::BI__exception_info:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001000 case Builtin::BI_exception_info:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001001 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1002 diag::err_seh___except_filter))
1003 return ExprError();
1004 break;
David Majnemerba3e5ec2015-03-13 18:26:17 +00001005 case Builtin::BI__GetExceptionInfo:
1006 if (checkArgCount(*this, TheCall, 1))
1007 return ExprError();
1008
1009 if (CheckCXXThrowOperand(
1010 TheCall->getLocStart(),
1011 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1012 TheCall))
1013 return ExprError();
1014
1015 TheCall->setType(Context.VoidPtrTy);
1016 break;
Anastasia Stulova7f8d6dc2016-07-04 16:07:18 +00001017 // OpenCL v2.0, s6.13.16 - Pipe functions
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001018 case Builtin::BIread_pipe:
1019 case Builtin::BIwrite_pipe:
1020 // Since those two functions are declared with var args, we need a semantic
1021 // check for the argument.
1022 if (SemaBuiltinRWPipe(*this, TheCall))
1023 return ExprError();
1024 break;
1025 case Builtin::BIreserve_read_pipe:
1026 case Builtin::BIreserve_write_pipe:
1027 case Builtin::BIwork_group_reserve_read_pipe:
1028 case Builtin::BIwork_group_reserve_write_pipe:
1029 case Builtin::BIsub_group_reserve_read_pipe:
1030 case Builtin::BIsub_group_reserve_write_pipe:
1031 if (SemaBuiltinReserveRWPipe(*this, TheCall))
1032 return ExprError();
1033 // Since return type of reserve_read/write_pipe built-in function is
1034 // reserve_id_t, which is not defined in the builtin def file , we used int
1035 // as return type and need to override the return type of these functions.
1036 TheCall->setType(Context.OCLReserveIDTy);
1037 break;
1038 case Builtin::BIcommit_read_pipe:
1039 case Builtin::BIcommit_write_pipe:
1040 case Builtin::BIwork_group_commit_read_pipe:
1041 case Builtin::BIwork_group_commit_write_pipe:
1042 case Builtin::BIsub_group_commit_read_pipe:
1043 case Builtin::BIsub_group_commit_write_pipe:
1044 if (SemaBuiltinCommitRWPipe(*this, TheCall))
1045 return ExprError();
1046 break;
1047 case Builtin::BIget_pipe_num_packets:
1048 case Builtin::BIget_pipe_max_packets:
1049 if (SemaBuiltinPipePackets(*this, TheCall))
1050 return ExprError();
1051 break;
Yaxun Liuf7449a12016-05-20 19:54:38 +00001052 case Builtin::BIto_global:
1053 case Builtin::BIto_local:
1054 case Builtin::BIto_private:
1055 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1056 return ExprError();
1057 break;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00001058 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1059 case Builtin::BIenqueue_kernel:
1060 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1061 return ExprError();
1062 break;
1063 case Builtin::BIget_kernel_work_group_size:
1064 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1065 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1066 return ExprError();
Nate Begeman4904e322010-06-08 02:47:44 +00001067 }
Richard Smith760520b2014-06-03 23:27:44 +00001068
Nate Begeman4904e322010-06-08 02:47:44 +00001069 // Since the target specific builtins for each arch overlap, only check those
1070 // of the arch we are compiling for.
Artem Belevich9674a642015-09-22 17:23:05 +00001071 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001072 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +00001073 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001074 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001075 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001076 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001077 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1078 return ExprError();
1079 break;
Tim Northover25e8a672014-05-24 12:51:25 +00001080 case llvm::Triple::aarch64:
1081 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +00001082 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +00001083 return ExprError();
1084 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001085 case llvm::Triple::mips:
1086 case llvm::Triple::mipsel:
1087 case llvm::Triple::mips64:
1088 case llvm::Triple::mips64el:
1089 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1090 return ExprError();
1091 break;
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001092 case llvm::Triple::systemz:
1093 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1094 return ExprError();
1095 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001096 case llvm::Triple::x86:
1097 case llvm::Triple::x86_64:
1098 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1099 return ExprError();
1100 break;
Kit Bartone50adcb2015-03-30 19:40:59 +00001101 case llvm::Triple::ppc:
1102 case llvm::Triple::ppc64:
1103 case llvm::Triple::ppc64le:
1104 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1105 return ExprError();
1106 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001107 default:
1108 break;
1109 }
1110 }
1111
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001112 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +00001113}
1114
Nate Begeman91e1fea2010-06-14 05:21:25 +00001115// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +00001116static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +00001117 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +00001118 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +00001119 switch (Type.getEltType()) {
1120 case NeonTypeFlags::Int8:
1121 case NeonTypeFlags::Poly8:
1122 return shift ? 7 : (8 << IsQuad) - 1;
1123 case NeonTypeFlags::Int16:
1124 case NeonTypeFlags::Poly16:
1125 return shift ? 15 : (4 << IsQuad) - 1;
1126 case NeonTypeFlags::Int32:
1127 return shift ? 31 : (2 << IsQuad) - 1;
1128 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +00001129 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +00001130 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001131 case NeonTypeFlags::Poly128:
1132 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +00001133 case NeonTypeFlags::Float16:
1134 assert(!shift && "cannot shift float types!");
1135 return (4 << IsQuad) - 1;
1136 case NeonTypeFlags::Float32:
1137 assert(!shift && "cannot shift float types!");
1138 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001139 case NeonTypeFlags::Float64:
1140 assert(!shift && "cannot shift float types!");
1141 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +00001142 }
David Blaikie8a40f702012-01-17 06:56:22 +00001143 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +00001144}
1145
Bob Wilsone4d77232011-11-08 05:04:11 +00001146/// getNeonEltType - Return the QualType corresponding to the elements of
1147/// the vector type specified by the NeonTypeFlags. This is used to check
1148/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +00001149static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +00001150 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +00001151 switch (Flags.getEltType()) {
1152 case NeonTypeFlags::Int8:
1153 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1154 case NeonTypeFlags::Int16:
1155 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1156 case NeonTypeFlags::Int32:
1157 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1158 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +00001159 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +00001160 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1161 else
1162 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1163 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001164 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +00001165 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001166 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +00001167 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +00001168 case NeonTypeFlags::Poly64:
Kevin Qin78b86532015-05-14 08:18:05 +00001169 if (IsInt64Long)
1170 return Context.UnsignedLongTy;
1171 else
1172 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001173 case NeonTypeFlags::Poly128:
1174 break;
Bob Wilsone4d77232011-11-08 05:04:11 +00001175 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +00001176 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001177 case NeonTypeFlags::Float32:
1178 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +00001179 case NeonTypeFlags::Float64:
1180 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001181 }
David Blaikie8a40f702012-01-17 06:56:22 +00001182 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +00001183}
1184
Tim Northover12670412014-02-19 10:37:05 +00001185bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +00001186 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +00001187 uint64_t mask = 0;
1188 unsigned TV = 0;
1189 int PtrArgNum = -1;
1190 bool HasConstPtr = false;
1191 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +00001192#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001193#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +00001194#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001195 }
1196
1197 // For NEON intrinsics which are overloaded on vector element type, validate
1198 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +00001199 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001200 if (mask) {
1201 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1202 return true;
1203
1204 TV = Result.getLimitedValue(64);
1205 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1206 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +00001207 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +00001208 }
1209
1210 if (PtrArgNum >= 0) {
1211 // Check that pointer arguments have the specified type.
1212 Expr *Arg = TheCall->getArg(PtrArgNum);
1213 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1214 Arg = ICE->getSubExpr();
1215 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1216 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +00001217
Tim Northovera2ee4332014-03-29 15:09:45 +00001218 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Tim Northover40956e62014-07-23 12:32:58 +00001219 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
Tim Northovera2ee4332014-03-29 15:09:45 +00001220 bool IsInt64Long =
1221 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1222 QualType EltTy =
1223 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +00001224 if (HasConstPtr)
1225 EltTy = EltTy.withConst();
1226 QualType LHSTy = Context.getPointerType(EltTy);
1227 AssignConvertType ConvTy;
1228 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1229 if (RHS.isInvalid())
1230 return true;
1231 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1232 RHS.get(), AA_Assigning))
1233 return true;
1234 }
1235
1236 // For NEON intrinsics which take an immediate value as part of the
1237 // instruction, range check them here.
1238 unsigned i = 0, l = 0, u = 0;
1239 switch (BuiltinID) {
1240 default:
1241 return false;
Tim Northover12670412014-02-19 10:37:05 +00001242#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001243#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +00001244#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001245 }
Tim Northover2fe823a2013-08-01 09:23:19 +00001246
Richard Sandiford28940af2014-04-16 08:47:51 +00001247 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +00001248}
1249
Tim Northovera2ee4332014-03-29 15:09:45 +00001250bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1251 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +00001252 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001253 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +00001254 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001255 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +00001256 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001257 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1258 BuiltinID == AArch64::BI__builtin_arm_strex ||
1259 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +00001260 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +00001261 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001262 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1263 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1264 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +00001265
1266 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1267
1268 // Ensure that we have the proper number of arguments.
1269 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1270 return true;
1271
1272 // Inspect the pointer argument of the atomic builtin. This should always be
1273 // a pointer type, whose element is an integral scalar or pointer type.
1274 // Because it is a pointer type, we don't have to worry about any implicit
1275 // casts here.
1276 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1277 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1278 if (PointerArgRes.isInvalid())
1279 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001280 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001281
1282 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1283 if (!pointerType) {
1284 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1285 << PointerArg->getType() << PointerArg->getSourceRange();
1286 return true;
1287 }
1288
1289 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1290 // task is to insert the appropriate casts into the AST. First work out just
1291 // what the appropriate type is.
1292 QualType ValType = pointerType->getPointeeType();
1293 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1294 if (IsLdrex)
1295 AddrType.addConst();
1296
1297 // Issue a warning if the cast is dodgy.
1298 CastKind CastNeeded = CK_NoOp;
1299 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1300 CastNeeded = CK_BitCast;
1301 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1302 << PointerArg->getType()
1303 << Context.getPointerType(AddrType)
1304 << AA_Passing << PointerArg->getSourceRange();
1305 }
1306
1307 // Finally, do the cast and replace the argument with the corrected version.
1308 AddrType = Context.getPointerType(AddrType);
1309 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1310 if (PointerArgRes.isInvalid())
1311 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001312 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001313
1314 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1315
1316 // In general, we allow ints, floats and pointers to be loaded and stored.
1317 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1318 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1319 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1320 << PointerArg->getType() << PointerArg->getSourceRange();
1321 return true;
1322 }
1323
1324 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +00001325 if (Context.getTypeSize(ValType) > MaxWidth) {
1326 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +00001327 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1328 << PointerArg->getType() << PointerArg->getSourceRange();
1329 return true;
1330 }
1331
1332 switch (ValType.getObjCLifetime()) {
1333 case Qualifiers::OCL_None:
1334 case Qualifiers::OCL_ExplicitNone:
1335 // okay
1336 break;
1337
1338 case Qualifiers::OCL_Weak:
1339 case Qualifiers::OCL_Strong:
1340 case Qualifiers::OCL_Autoreleasing:
1341 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1342 << ValType << PointerArg->getSourceRange();
1343 return true;
1344 }
1345
Tim Northover6aacd492013-07-16 09:47:53 +00001346 if (IsLdrex) {
1347 TheCall->setType(ValType);
1348 return false;
1349 }
1350
1351 // Initialize the argument to be stored.
1352 ExprResult ValArg = TheCall->getArg(0);
1353 InitializedEntity Entity = InitializedEntity::InitializeParameter(
1354 Context, ValType, /*consume*/ false);
1355 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1356 if (ValArg.isInvalid())
1357 return true;
Tim Northover6aacd492013-07-16 09:47:53 +00001358 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +00001359
1360 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1361 // but the custom checker bypasses all default analysis.
1362 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +00001363 return false;
1364}
1365
Nate Begeman4904e322010-06-08 02:47:44 +00001366bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +00001367 llvm::APSInt Result;
1368
Tim Northover6aacd492013-07-16 09:47:53 +00001369 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001370 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1371 BuiltinID == ARM::BI__builtin_arm_strex ||
1372 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001373 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +00001374 }
1375
Yi Kong26d104a2014-08-13 19:18:14 +00001376 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1377 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1378 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1379 }
1380
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001381 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1382 BuiltinID == ARM::BI__builtin_arm_wsr64)
1383 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1384
1385 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1386 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1387 BuiltinID == ARM::BI__builtin_arm_wsr ||
1388 BuiltinID == ARM::BI__builtin_arm_wsrp)
1389 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1390
Tim Northover12670412014-02-19 10:37:05 +00001391 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1392 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +00001393
Yi Kong4efadfb2014-07-03 16:01:25 +00001394 // For intrinsics which take an immediate value as part of the instruction,
1395 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +00001396 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +00001397 switch (BuiltinID) {
1398 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +00001399 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
1400 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +00001401 case ARM::BI__builtin_arm_vcvtr_f:
1402 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +00001403 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +00001404 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +00001405 case ARM::BI__builtin_arm_isb:
1406 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001407 }
Nate Begemand773fe62010-06-13 04:47:52 +00001408
Nate Begemanf568b072010-08-03 21:32:34 +00001409 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +00001410 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001411}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001412
Tim Northover573cbee2014-05-24 12:52:07 +00001413bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +00001414 CallExpr *TheCall) {
1415 llvm::APSInt Result;
1416
Tim Northover573cbee2014-05-24 12:52:07 +00001417 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001418 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1419 BuiltinID == AArch64::BI__builtin_arm_strex ||
1420 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001421 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1422 }
1423
Yi Konga5548432014-08-13 19:18:20 +00001424 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1425 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1426 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1427 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1428 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1429 }
1430
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001431 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1432 BuiltinID == AArch64::BI__builtin_arm_wsr64)
Tim Northover54e50002016-04-13 17:08:55 +00001433 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001434
1435 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1436 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1437 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1438 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1439 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1440
Tim Northovera2ee4332014-03-29 15:09:45 +00001441 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1442 return true;
1443
Yi Kong19a29ac2014-07-17 10:52:06 +00001444 // For intrinsics which take an immediate value as part of the instruction,
1445 // range check them here.
1446 unsigned i = 0, l = 0, u = 0;
1447 switch (BuiltinID) {
1448 default: return false;
1449 case AArch64::BI__builtin_arm_dmb:
1450 case AArch64::BI__builtin_arm_dsb:
1451 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1452 }
1453
Yi Kong19a29ac2014-07-17 10:52:06 +00001454 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +00001455}
1456
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001457bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1458 unsigned i = 0, l = 0, u = 0;
1459 switch (BuiltinID) {
1460 default: return false;
1461 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1462 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +00001463 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1464 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1465 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1466 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1467 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001468 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001469
Richard Sandiford28940af2014-04-16 08:47:51 +00001470 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001471}
1472
Kit Bartone50adcb2015-03-30 19:40:59 +00001473bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1474 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00001475 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1476 BuiltinID == PPC::BI__builtin_divdeu ||
1477 BuiltinID == PPC::BI__builtin_bpermd;
1478 bool IsTarget64Bit = Context.getTargetInfo()
1479 .getTypeWidth(Context
1480 .getTargetInfo()
1481 .getIntPtrType()) == 64;
1482 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1483 BuiltinID == PPC::BI__builtin_divweu ||
1484 BuiltinID == PPC::BI__builtin_divde ||
1485 BuiltinID == PPC::BI__builtin_divdeu;
1486
1487 if (Is64BitBltin && !IsTarget64Bit)
1488 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1489 << TheCall->getSourceRange();
1490
1491 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1492 (BuiltinID == PPC::BI__builtin_bpermd &&
1493 !Context.getTargetInfo().hasFeature("bpermd")))
1494 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1495 << TheCall->getSourceRange();
1496
Kit Bartone50adcb2015-03-30 19:40:59 +00001497 switch (BuiltinID) {
1498 default: return false;
1499 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1500 case PPC::BI__builtin_altivec_crypto_vshasigmad:
1501 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1502 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1503 case PPC::BI__builtin_tbegin:
1504 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1505 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1506 case PPC::BI__builtin_tabortwc:
1507 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1508 case PPC::BI__builtin_tabortwci:
1509 case PPC::BI__builtin_tabortdci:
1510 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1511 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1512 }
1513 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1514}
1515
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001516bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1517 CallExpr *TheCall) {
1518 if (BuiltinID == SystemZ::BI__builtin_tabort) {
1519 Expr *Arg = TheCall->getArg(0);
1520 llvm::APSInt AbortCode(32);
1521 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1522 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1523 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1524 << Arg->getSourceRange();
1525 }
1526
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001527 // For intrinsics which take an immediate value as part of the instruction,
1528 // range check them here.
1529 unsigned i = 0, l = 0, u = 0;
1530 switch (BuiltinID) {
1531 default: return false;
1532 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1533 case SystemZ::BI__builtin_s390_verimb:
1534 case SystemZ::BI__builtin_s390_verimh:
1535 case SystemZ::BI__builtin_s390_verimf:
1536 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1537 case SystemZ::BI__builtin_s390_vfaeb:
1538 case SystemZ::BI__builtin_s390_vfaeh:
1539 case SystemZ::BI__builtin_s390_vfaef:
1540 case SystemZ::BI__builtin_s390_vfaebs:
1541 case SystemZ::BI__builtin_s390_vfaehs:
1542 case SystemZ::BI__builtin_s390_vfaefs:
1543 case SystemZ::BI__builtin_s390_vfaezb:
1544 case SystemZ::BI__builtin_s390_vfaezh:
1545 case SystemZ::BI__builtin_s390_vfaezf:
1546 case SystemZ::BI__builtin_s390_vfaezbs:
1547 case SystemZ::BI__builtin_s390_vfaezhs:
1548 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1549 case SystemZ::BI__builtin_s390_vfidb:
1550 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1551 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1552 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1553 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1554 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1555 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1556 case SystemZ::BI__builtin_s390_vstrcb:
1557 case SystemZ::BI__builtin_s390_vstrch:
1558 case SystemZ::BI__builtin_s390_vstrcf:
1559 case SystemZ::BI__builtin_s390_vstrczb:
1560 case SystemZ::BI__builtin_s390_vstrczh:
1561 case SystemZ::BI__builtin_s390_vstrczf:
1562 case SystemZ::BI__builtin_s390_vstrcbs:
1563 case SystemZ::BI__builtin_s390_vstrchs:
1564 case SystemZ::BI__builtin_s390_vstrcfs:
1565 case SystemZ::BI__builtin_s390_vstrczbs:
1566 case SystemZ::BI__builtin_s390_vstrczhs:
1567 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1568 }
1569 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001570}
1571
Craig Topper5ba2c502015-11-07 08:08:31 +00001572/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1573/// This checks that the target supports __builtin_cpu_supports and
1574/// that the string argument is constant and valid.
1575static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1576 Expr *Arg = TheCall->getArg(0);
1577
1578 // Check if the argument is a string literal.
1579 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1580 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1581 << Arg->getSourceRange();
1582
1583 // Check the contents of the string.
1584 StringRef Feature =
1585 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1586 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1587 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1588 << Arg->getSourceRange();
1589 return false;
1590}
1591
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001592bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Craig Topper39c87102016-05-18 03:18:12 +00001593 int i = 0, l = 0, u = 0;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001594 switch (BuiltinID) {
Richard Trieucc3949d2016-02-18 22:34:54 +00001595 default:
1596 return false;
Eric Christopherd9832702015-06-29 21:00:05 +00001597 case X86::BI__builtin_cpu_supports:
Craig Topper5ba2c502015-11-07 08:08:31 +00001598 return SemaBuiltinCpuSupports(*this, TheCall);
Charles Davisc7d5c942015-09-17 20:55:33 +00001599 case X86::BI__builtin_ms_va_start:
1600 return SemaBuiltinMSVAStart(TheCall);
Craig Topper39c87102016-05-18 03:18:12 +00001601 case X86::BI__builtin_ia32_extractf64x4_mask:
1602 case X86::BI__builtin_ia32_extracti64x4_mask:
1603 case X86::BI__builtin_ia32_extractf32x8_mask:
1604 case X86::BI__builtin_ia32_extracti32x8_mask:
1605 case X86::BI__builtin_ia32_extractf64x2_256_mask:
1606 case X86::BI__builtin_ia32_extracti64x2_256_mask:
1607 case X86::BI__builtin_ia32_extractf32x4_256_mask:
1608 case X86::BI__builtin_ia32_extracti32x4_256_mask:
1609 i = 1; l = 0; u = 1;
1610 break;
Richard Trieucc3949d2016-02-18 22:34:54 +00001611 case X86::BI_mm_prefetch:
Craig Topper39c87102016-05-18 03:18:12 +00001612 case X86::BI__builtin_ia32_extractf32x4_mask:
1613 case X86::BI__builtin_ia32_extracti32x4_mask:
Craig Topper39c87102016-05-18 03:18:12 +00001614 case X86::BI__builtin_ia32_extractf64x2_512_mask:
1615 case X86::BI__builtin_ia32_extracti64x2_512_mask:
1616 i = 1; l = 0; u = 3;
1617 break;
1618 case X86::BI__builtin_ia32_insertf32x8_mask:
1619 case X86::BI__builtin_ia32_inserti32x8_mask:
1620 case X86::BI__builtin_ia32_insertf64x4_mask:
1621 case X86::BI__builtin_ia32_inserti64x4_mask:
1622 case X86::BI__builtin_ia32_insertf64x2_256_mask:
1623 case X86::BI__builtin_ia32_inserti64x2_256_mask:
1624 case X86::BI__builtin_ia32_insertf32x4_256_mask:
1625 case X86::BI__builtin_ia32_inserti32x4_256_mask:
1626 i = 2; l = 0; u = 1;
Richard Trieucc3949d2016-02-18 22:34:54 +00001627 break;
1628 case X86::BI__builtin_ia32_sha1rnds4:
Craig Topper39c87102016-05-18 03:18:12 +00001629 case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
1630 case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
1631 case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
1632 case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00001633 case X86::BI__builtin_ia32_insertf64x2_512_mask:
1634 case X86::BI__builtin_ia32_inserti64x2_512_mask:
1635 case X86::BI__builtin_ia32_insertf32x4_mask:
1636 case X86::BI__builtin_ia32_inserti32x4_mask:
1637 i = 2; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00001638 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00001639 case X86::BI__builtin_ia32_vpermil2pd:
1640 case X86::BI__builtin_ia32_vpermil2pd256:
1641 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00001642 case X86::BI__builtin_ia32_vpermil2ps256:
Craig Topper39c87102016-05-18 03:18:12 +00001643 i = 3; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00001644 break;
Craig Topper95b0d732015-01-25 23:30:05 +00001645 case X86::BI__builtin_ia32_cmpb128_mask:
1646 case X86::BI__builtin_ia32_cmpw128_mask:
1647 case X86::BI__builtin_ia32_cmpd128_mask:
1648 case X86::BI__builtin_ia32_cmpq128_mask:
1649 case X86::BI__builtin_ia32_cmpb256_mask:
1650 case X86::BI__builtin_ia32_cmpw256_mask:
1651 case X86::BI__builtin_ia32_cmpd256_mask:
1652 case X86::BI__builtin_ia32_cmpq256_mask:
1653 case X86::BI__builtin_ia32_cmpb512_mask:
1654 case X86::BI__builtin_ia32_cmpw512_mask:
1655 case X86::BI__builtin_ia32_cmpd512_mask:
1656 case X86::BI__builtin_ia32_cmpq512_mask:
1657 case X86::BI__builtin_ia32_ucmpb128_mask:
1658 case X86::BI__builtin_ia32_ucmpw128_mask:
1659 case X86::BI__builtin_ia32_ucmpd128_mask:
1660 case X86::BI__builtin_ia32_ucmpq128_mask:
1661 case X86::BI__builtin_ia32_ucmpb256_mask:
1662 case X86::BI__builtin_ia32_ucmpw256_mask:
1663 case X86::BI__builtin_ia32_ucmpd256_mask:
1664 case X86::BI__builtin_ia32_ucmpq256_mask:
1665 case X86::BI__builtin_ia32_ucmpb512_mask:
1666 case X86::BI__builtin_ia32_ucmpw512_mask:
1667 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00001668 case X86::BI__builtin_ia32_ucmpq512_mask:
Craig Topper8dd7d0d2015-02-13 06:04:48 +00001669 case X86::BI__builtin_ia32_vpcomub:
1670 case X86::BI__builtin_ia32_vpcomuw:
1671 case X86::BI__builtin_ia32_vpcomud:
1672 case X86::BI__builtin_ia32_vpcomuq:
1673 case X86::BI__builtin_ia32_vpcomb:
1674 case X86::BI__builtin_ia32_vpcomw:
1675 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00001676 case X86::BI__builtin_ia32_vpcomq:
Craig Topper39c87102016-05-18 03:18:12 +00001677 i = 2; l = 0; u = 7;
1678 break;
1679 case X86::BI__builtin_ia32_roundps:
1680 case X86::BI__builtin_ia32_roundpd:
1681 case X86::BI__builtin_ia32_roundps256:
1682 case X86::BI__builtin_ia32_roundpd256:
Craig Topper39c87102016-05-18 03:18:12 +00001683 i = 1; l = 0; u = 15;
1684 break;
1685 case X86::BI__builtin_ia32_roundss:
1686 case X86::BI__builtin_ia32_roundsd:
1687 case X86::BI__builtin_ia32_rangepd128_mask:
1688 case X86::BI__builtin_ia32_rangepd256_mask:
1689 case X86::BI__builtin_ia32_rangepd512_mask:
1690 case X86::BI__builtin_ia32_rangeps128_mask:
1691 case X86::BI__builtin_ia32_rangeps256_mask:
1692 case X86::BI__builtin_ia32_rangeps512_mask:
1693 case X86::BI__builtin_ia32_getmantsd_round_mask:
1694 case X86::BI__builtin_ia32_getmantss_round_mask:
Craig Topper39c87102016-05-18 03:18:12 +00001695 i = 2; l = 0; u = 15;
1696 break;
1697 case X86::BI__builtin_ia32_cmpps:
1698 case X86::BI__builtin_ia32_cmpss:
1699 case X86::BI__builtin_ia32_cmppd:
1700 case X86::BI__builtin_ia32_cmpsd:
1701 case X86::BI__builtin_ia32_cmpps256:
1702 case X86::BI__builtin_ia32_cmppd256:
1703 case X86::BI__builtin_ia32_cmpps128_mask:
1704 case X86::BI__builtin_ia32_cmppd128_mask:
1705 case X86::BI__builtin_ia32_cmpps256_mask:
1706 case X86::BI__builtin_ia32_cmppd256_mask:
1707 case X86::BI__builtin_ia32_cmpps512_mask:
1708 case X86::BI__builtin_ia32_cmppd512_mask:
1709 case X86::BI__builtin_ia32_cmpsd_mask:
1710 case X86::BI__builtin_ia32_cmpss_mask:
1711 i = 2; l = 0; u = 31;
1712 break;
1713 case X86::BI__builtin_ia32_xabort:
1714 i = 0; l = -128; u = 255;
1715 break;
1716 case X86::BI__builtin_ia32_pshufw:
1717 case X86::BI__builtin_ia32_aeskeygenassist128:
1718 i = 1; l = -128; u = 255;
1719 break;
1720 case X86::BI__builtin_ia32_vcvtps2ph:
1721 case X86::BI__builtin_ia32_vcvtps2ph256:
Craig Topper39c87102016-05-18 03:18:12 +00001722 case X86::BI__builtin_ia32_rndscaleps_128_mask:
1723 case X86::BI__builtin_ia32_rndscalepd_128_mask:
1724 case X86::BI__builtin_ia32_rndscaleps_256_mask:
1725 case X86::BI__builtin_ia32_rndscalepd_256_mask:
1726 case X86::BI__builtin_ia32_rndscaleps_mask:
1727 case X86::BI__builtin_ia32_rndscalepd_mask:
1728 case X86::BI__builtin_ia32_reducepd128_mask:
1729 case X86::BI__builtin_ia32_reducepd256_mask:
1730 case X86::BI__builtin_ia32_reducepd512_mask:
1731 case X86::BI__builtin_ia32_reduceps128_mask:
1732 case X86::BI__builtin_ia32_reduceps256_mask:
1733 case X86::BI__builtin_ia32_reduceps512_mask:
1734 case X86::BI__builtin_ia32_prold512_mask:
1735 case X86::BI__builtin_ia32_prolq512_mask:
1736 case X86::BI__builtin_ia32_prold128_mask:
1737 case X86::BI__builtin_ia32_prold256_mask:
1738 case X86::BI__builtin_ia32_prolq128_mask:
1739 case X86::BI__builtin_ia32_prolq256_mask:
1740 case X86::BI__builtin_ia32_prord128_mask:
1741 case X86::BI__builtin_ia32_prord256_mask:
1742 case X86::BI__builtin_ia32_prorq128_mask:
1743 case X86::BI__builtin_ia32_prorq256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00001744 case X86::BI__builtin_ia32_psllwi512_mask:
1745 case X86::BI__builtin_ia32_psllwi128_mask:
1746 case X86::BI__builtin_ia32_psllwi256_mask:
1747 case X86::BI__builtin_ia32_psrldi128_mask:
1748 case X86::BI__builtin_ia32_psrldi256_mask:
1749 case X86::BI__builtin_ia32_psrldi512_mask:
1750 case X86::BI__builtin_ia32_psrlqi128_mask:
1751 case X86::BI__builtin_ia32_psrlqi256_mask:
1752 case X86::BI__builtin_ia32_psrlqi512_mask:
1753 case X86::BI__builtin_ia32_psrawi512_mask:
1754 case X86::BI__builtin_ia32_psrawi128_mask:
1755 case X86::BI__builtin_ia32_psrawi256_mask:
1756 case X86::BI__builtin_ia32_psrlwi512_mask:
1757 case X86::BI__builtin_ia32_psrlwi128_mask:
1758 case X86::BI__builtin_ia32_psrlwi256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00001759 case X86::BI__builtin_ia32_psradi128_mask:
1760 case X86::BI__builtin_ia32_psradi256_mask:
1761 case X86::BI__builtin_ia32_psradi512_mask:
1762 case X86::BI__builtin_ia32_psraqi128_mask:
1763 case X86::BI__builtin_ia32_psraqi256_mask:
1764 case X86::BI__builtin_ia32_psraqi512_mask:
1765 case X86::BI__builtin_ia32_pslldi128_mask:
1766 case X86::BI__builtin_ia32_pslldi256_mask:
1767 case X86::BI__builtin_ia32_pslldi512_mask:
1768 case X86::BI__builtin_ia32_psllqi128_mask:
1769 case X86::BI__builtin_ia32_psllqi256_mask:
1770 case X86::BI__builtin_ia32_psllqi512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00001771 case X86::BI__builtin_ia32_fpclasspd128_mask:
1772 case X86::BI__builtin_ia32_fpclasspd256_mask:
1773 case X86::BI__builtin_ia32_fpclassps128_mask:
1774 case X86::BI__builtin_ia32_fpclassps256_mask:
1775 case X86::BI__builtin_ia32_fpclassps512_mask:
1776 case X86::BI__builtin_ia32_fpclasspd512_mask:
1777 case X86::BI__builtin_ia32_fpclasssd_mask:
1778 case X86::BI__builtin_ia32_fpclassss_mask:
Craig Topper39c87102016-05-18 03:18:12 +00001779 i = 1; l = 0; u = 255;
1780 break;
1781 case X86::BI__builtin_ia32_palignr:
1782 case X86::BI__builtin_ia32_insertps128:
1783 case X86::BI__builtin_ia32_dpps:
1784 case X86::BI__builtin_ia32_dppd:
1785 case X86::BI__builtin_ia32_dpps256:
1786 case X86::BI__builtin_ia32_mpsadbw128:
1787 case X86::BI__builtin_ia32_mpsadbw256:
1788 case X86::BI__builtin_ia32_pcmpistrm128:
1789 case X86::BI__builtin_ia32_pcmpistri128:
1790 case X86::BI__builtin_ia32_pcmpistria128:
1791 case X86::BI__builtin_ia32_pcmpistric128:
1792 case X86::BI__builtin_ia32_pcmpistrio128:
1793 case X86::BI__builtin_ia32_pcmpistris128:
1794 case X86::BI__builtin_ia32_pcmpistriz128:
1795 case X86::BI__builtin_ia32_pclmulqdq128:
1796 case X86::BI__builtin_ia32_vperm2f128_pd256:
1797 case X86::BI__builtin_ia32_vperm2f128_ps256:
1798 case X86::BI__builtin_ia32_vperm2f128_si256:
1799 case X86::BI__builtin_ia32_permti256:
1800 i = 2; l = -128; u = 255;
1801 break;
1802 case X86::BI__builtin_ia32_palignr128:
1803 case X86::BI__builtin_ia32_palignr256:
1804 case X86::BI__builtin_ia32_palignr128_mask:
1805 case X86::BI__builtin_ia32_palignr256_mask:
1806 case X86::BI__builtin_ia32_palignr512_mask:
1807 case X86::BI__builtin_ia32_alignq512_mask:
1808 case X86::BI__builtin_ia32_alignd512_mask:
1809 case X86::BI__builtin_ia32_alignd128_mask:
1810 case X86::BI__builtin_ia32_alignd256_mask:
1811 case X86::BI__builtin_ia32_alignq128_mask:
1812 case X86::BI__builtin_ia32_alignq256_mask:
1813 case X86::BI__builtin_ia32_vcomisd:
1814 case X86::BI__builtin_ia32_vcomiss:
1815 case X86::BI__builtin_ia32_shuf_f32x4_mask:
1816 case X86::BI__builtin_ia32_shuf_f64x2_mask:
1817 case X86::BI__builtin_ia32_shuf_i32x4_mask:
1818 case X86::BI__builtin_ia32_shuf_i64x2_mask:
Craig Topper39c87102016-05-18 03:18:12 +00001819 case X86::BI__builtin_ia32_dbpsadbw128_mask:
1820 case X86::BI__builtin_ia32_dbpsadbw256_mask:
1821 case X86::BI__builtin_ia32_dbpsadbw512_mask:
1822 i = 2; l = 0; u = 255;
1823 break;
1824 case X86::BI__builtin_ia32_fixupimmpd512_mask:
1825 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
1826 case X86::BI__builtin_ia32_fixupimmps512_mask:
1827 case X86::BI__builtin_ia32_fixupimmps512_maskz:
1828 case X86::BI__builtin_ia32_fixupimmsd_mask:
1829 case X86::BI__builtin_ia32_fixupimmsd_maskz:
1830 case X86::BI__builtin_ia32_fixupimmss_mask:
1831 case X86::BI__builtin_ia32_fixupimmss_maskz:
1832 case X86::BI__builtin_ia32_fixupimmpd128_mask:
1833 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
1834 case X86::BI__builtin_ia32_fixupimmpd256_mask:
1835 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
1836 case X86::BI__builtin_ia32_fixupimmps128_mask:
1837 case X86::BI__builtin_ia32_fixupimmps128_maskz:
1838 case X86::BI__builtin_ia32_fixupimmps256_mask:
1839 case X86::BI__builtin_ia32_fixupimmps256_maskz:
1840 case X86::BI__builtin_ia32_pternlogd512_mask:
1841 case X86::BI__builtin_ia32_pternlogd512_maskz:
1842 case X86::BI__builtin_ia32_pternlogq512_mask:
1843 case X86::BI__builtin_ia32_pternlogq512_maskz:
1844 case X86::BI__builtin_ia32_pternlogd128_mask:
1845 case X86::BI__builtin_ia32_pternlogd128_maskz:
1846 case X86::BI__builtin_ia32_pternlogd256_mask:
1847 case X86::BI__builtin_ia32_pternlogd256_maskz:
1848 case X86::BI__builtin_ia32_pternlogq128_mask:
1849 case X86::BI__builtin_ia32_pternlogq128_maskz:
1850 case X86::BI__builtin_ia32_pternlogq256_mask:
1851 case X86::BI__builtin_ia32_pternlogq256_maskz:
1852 i = 3; l = 0; u = 255;
1853 break;
1854 case X86::BI__builtin_ia32_pcmpestrm128:
1855 case X86::BI__builtin_ia32_pcmpestri128:
1856 case X86::BI__builtin_ia32_pcmpestria128:
1857 case X86::BI__builtin_ia32_pcmpestric128:
1858 case X86::BI__builtin_ia32_pcmpestrio128:
1859 case X86::BI__builtin_ia32_pcmpestris128:
1860 case X86::BI__builtin_ia32_pcmpestriz128:
1861 i = 4; l = -128; u = 255;
1862 break;
1863 case X86::BI__builtin_ia32_rndscalesd_round_mask:
1864 case X86::BI__builtin_ia32_rndscaless_round_mask:
1865 i = 4; l = 0; u = 255;
Richard Trieucc3949d2016-02-18 22:34:54 +00001866 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001867 }
Craig Topperdd84ec52014-12-27 07:00:08 +00001868 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001869}
1870
Richard Smith55ce3522012-06-25 20:30:08 +00001871/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
1872/// parameter with the FormatAttr's correct format_idx and firstDataArg.
1873/// Returns true when the format fits the function and the FormatStringInfo has
1874/// been populated.
1875bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
1876 FormatStringInfo *FSI) {
1877 FSI->HasVAListArg = Format->getFirstArg() == 0;
1878 FSI->FormatIdx = Format->getFormatIdx() - 1;
1879 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001880
Richard Smith55ce3522012-06-25 20:30:08 +00001881 // The way the format attribute works in GCC, the implicit this argument
1882 // of member functions is counted. However, it doesn't appear in our own
1883 // lists, so decrement format_idx in that case.
1884 if (IsCXXMember) {
1885 if(FSI->FormatIdx == 0)
1886 return false;
1887 --FSI->FormatIdx;
1888 if (FSI->FirstDataArg != 0)
1889 --FSI->FirstDataArg;
1890 }
1891 return true;
1892}
Mike Stump11289f42009-09-09 15:08:12 +00001893
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001894/// Checks if a the given expression evaluates to null.
1895///
1896/// \brief Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00001897static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001898 // If the expression has non-null type, it doesn't evaluate to null.
1899 if (auto nullability
1900 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
1901 if (*nullability == NullabilityKind::NonNull)
1902 return false;
1903 }
1904
Ted Kremeneka146db32014-01-17 06:24:47 +00001905 // As a special case, transparent unions initialized with zero are
1906 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001907 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00001908 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
1909 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001910 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00001911 if (const InitListExpr *ILE =
1912 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001913 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00001914 }
1915
1916 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00001917 return (!Expr->isValueDependent() &&
1918 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
1919 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001920}
1921
1922static void CheckNonNullArgument(Sema &S,
1923 const Expr *ArgExpr,
1924 SourceLocation CallSiteLoc) {
1925 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00001926 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
1927 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00001928}
1929
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001930bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
1931 FormatStringInfo FSI;
1932 if ((GetFormatStringType(Format) == FST_NSString) &&
1933 getFormatStringInfo(Format, false, &FSI)) {
1934 Idx = FSI.FormatIdx;
1935 return true;
1936 }
1937 return false;
1938}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001939/// \brief Diagnose use of %s directive in an NSString which is being passed
1940/// as formatting string to formatting method.
1941static void
1942DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
1943 const NamedDecl *FDecl,
1944 Expr **Args,
1945 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001946 unsigned Idx = 0;
1947 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001948 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
1949 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001950 Idx = 2;
1951 Format = true;
1952 }
1953 else
1954 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
1955 if (S.GetFormatNSStringIdx(I, Idx)) {
1956 Format = true;
1957 break;
1958 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001959 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001960 if (!Format || NumArgs <= Idx)
1961 return;
1962 const Expr *FormatExpr = Args[Idx];
1963 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
1964 FormatExpr = CSCE->getSubExpr();
1965 const StringLiteral *FormatString;
1966 if (const ObjCStringLiteral *OSL =
1967 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
1968 FormatString = OSL->getString();
1969 else
1970 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
1971 if (!FormatString)
1972 return;
1973 if (S.FormatStringHasSArg(FormatString)) {
1974 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
1975 << "%s" << 1 << 1;
1976 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
1977 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001978 }
1979}
1980
Douglas Gregorb4866e82015-06-19 18:13:19 +00001981/// Determine whether the given type has a non-null nullability annotation.
1982static bool isNonNullType(ASTContext &ctx, QualType type) {
1983 if (auto nullability = type->getNullability(ctx))
1984 return *nullability == NullabilityKind::NonNull;
1985
1986 return false;
1987}
1988
Ted Kremenek2bc73332014-01-17 06:24:43 +00001989static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00001990 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00001991 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00001992 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00001993 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001994 assert((FDecl || Proto) && "Need a function declaration or prototype");
1995
Ted Kremenek9aedc152014-01-17 06:24:56 +00001996 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00001997 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00001998 if (FDecl) {
1999 // Handle the nonnull attribute on the function/method declaration itself.
2000 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2001 if (!NonNull->args_size()) {
2002 // Easy case: all pointer arguments are nonnull.
2003 for (const auto *Arg : Args)
2004 if (S.isValidPointerAttrType(Arg->getType()))
2005 CheckNonNullArgument(S, Arg, CallSiteLoc);
2006 return;
2007 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002008
Douglas Gregorb4866e82015-06-19 18:13:19 +00002009 for (unsigned Val : NonNull->args()) {
2010 if (Val >= Args.size())
2011 continue;
2012 if (NonNullArgs.empty())
2013 NonNullArgs.resize(Args.size());
2014 NonNullArgs.set(Val);
2015 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002016 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002017 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002018
Douglas Gregorb4866e82015-06-19 18:13:19 +00002019 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2020 // Handle the nonnull attribute on the parameters of the
2021 // function/method.
2022 ArrayRef<ParmVarDecl*> parms;
2023 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2024 parms = FD->parameters();
2025 else
2026 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2027
2028 unsigned ParamIndex = 0;
2029 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2030 I != E; ++I, ++ParamIndex) {
2031 const ParmVarDecl *PVD = *I;
2032 if (PVD->hasAttr<NonNullAttr>() ||
2033 isNonNullType(S.Context, PVD->getType())) {
2034 if (NonNullArgs.empty())
2035 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00002036
Douglas Gregorb4866e82015-06-19 18:13:19 +00002037 NonNullArgs.set(ParamIndex);
2038 }
2039 }
2040 } else {
2041 // If we have a non-function, non-method declaration but no
2042 // function prototype, try to dig out the function prototype.
2043 if (!Proto) {
2044 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2045 QualType type = VD->getType().getNonReferenceType();
2046 if (auto pointerType = type->getAs<PointerType>())
2047 type = pointerType->getPointeeType();
2048 else if (auto blockType = type->getAs<BlockPointerType>())
2049 type = blockType->getPointeeType();
2050 // FIXME: data member pointers?
2051
2052 // Dig out the function prototype, if there is one.
2053 Proto = type->getAs<FunctionProtoType>();
2054 }
2055 }
2056
2057 // Fill in non-null argument information from the nullability
2058 // information on the parameter types (if we have them).
2059 if (Proto) {
2060 unsigned Index = 0;
2061 for (auto paramType : Proto->getParamTypes()) {
2062 if (isNonNullType(S.Context, paramType)) {
2063 if (NonNullArgs.empty())
2064 NonNullArgs.resize(Args.size());
2065
2066 NonNullArgs.set(Index);
2067 }
2068
2069 ++Index;
2070 }
2071 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002072 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002073
Douglas Gregorb4866e82015-06-19 18:13:19 +00002074 // Check for non-null arguments.
2075 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2076 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00002077 if (NonNullArgs[ArgIndex])
2078 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00002079 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002080}
2081
Richard Smith55ce3522012-06-25 20:30:08 +00002082/// Handles the checks for format strings, non-POD arguments to vararg
2083/// functions, and NULL arguments passed to non-NULL parameters.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002084void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2085 ArrayRef<const Expr *> Args, bool IsMemberFunction,
Alp Toker9cacbab2014-01-20 20:26:09 +00002086 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +00002087 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00002088 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00002089 if (CurContext->isDependentContext())
2090 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00002091
Ted Kremenekb8176da2010-09-09 04:33:05 +00002092 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00002093 llvm::SmallBitVector CheckedVarArgs;
2094 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002095 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002096 // Only create vector if there are format attributes.
2097 CheckedVarArgs.resize(Args.size());
2098
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002099 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00002100 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002101 }
Richard Smithd7293d72013-08-05 18:49:43 +00002102 }
Richard Smith55ce3522012-06-25 20:30:08 +00002103
2104 // Refuse POD arguments that weren't caught by the format string
2105 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +00002106 if (CallType != VariadicDoesNotApply) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002107 unsigned NumParams = Proto ? Proto->getNumParams()
2108 : FDecl && isa<FunctionDecl>(FDecl)
2109 ? cast<FunctionDecl>(FDecl)->getNumParams()
2110 : FDecl && isa<ObjCMethodDecl>(FDecl)
2111 ? cast<ObjCMethodDecl>(FDecl)->param_size()
2112 : 0;
2113
Alp Toker9cacbab2014-01-20 20:26:09 +00002114 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002115 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00002116 if (const Expr *Arg = Args[ArgIdx]) {
2117 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2118 checkVariadicArgument(Arg, CallType);
2119 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002120 }
Richard Smithd7293d72013-08-05 18:49:43 +00002121 }
Mike Stump11289f42009-09-09 15:08:12 +00002122
Douglas Gregorb4866e82015-06-19 18:13:19 +00002123 if (FDecl || Proto) {
2124 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002125
Richard Trieu41bc0992013-06-22 00:20:41 +00002126 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002127 if (FDecl) {
2128 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
2129 CheckArgumentWithTypeTag(I, Args.data());
2130 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002131 }
Richard Smith55ce3522012-06-25 20:30:08 +00002132}
2133
2134/// CheckConstructorCall - Check a constructor call for correctness and safety
2135/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002136void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2137 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002138 const FunctionProtoType *Proto,
2139 SourceLocation Loc) {
2140 VariadicCallType CallType =
2141 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Douglas Gregorb4866e82015-06-19 18:13:19 +00002142 checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(),
2143 CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00002144}
2145
2146/// CheckFunctionCall - Check a direct function call for various correctness
2147/// and safety properties not strictly enforced by the C type system.
2148bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2149 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002150 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2151 isa<CXXMethodDecl>(FDecl);
2152 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2153 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00002154 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2155 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00002156 Expr** Args = TheCall->getArgs();
2157 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +00002158 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002159 // If this is a call to a member operator, hide the first argument
2160 // from checkCall.
2161 // FIXME: Our choice of AST representation here is less than ideal.
2162 ++Args;
2163 --NumArgs;
2164 }
Douglas Gregorb4866e82015-06-19 18:13:19 +00002165 checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00002166 IsMemberFunction, TheCall->getRParenLoc(),
2167 TheCall->getCallee()->getSourceRange(), CallType);
2168
2169 IdentifierInfo *FnInfo = FDecl->getIdentifier();
2170 // None of the checks below are needed for functions that don't have
2171 // simple names (e.g., C++ conversion functions).
2172 if (!FnInfo)
2173 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002174
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00002175 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002176 if (getLangOpts().ObjC1)
2177 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00002178
Anna Zaks22122702012-01-17 00:37:07 +00002179 unsigned CMId = FDecl->getMemoryFunctionKind();
2180 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00002181 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00002182
Anna Zaks201d4892012-01-13 21:52:01 +00002183 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00002184 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00002185 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00002186 else if (CMId == Builtin::BIstrncat)
2187 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00002188 else
Anna Zaks22122702012-01-17 00:37:07 +00002189 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00002190
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002191 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00002192}
2193
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002194bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00002195 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00002196 VariadicCallType CallType =
2197 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002198
Douglas Gregorb4866e82015-06-19 18:13:19 +00002199 checkCall(Method, nullptr, Args,
2200 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
2201 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002202
2203 return false;
2204}
2205
Richard Trieu664c4c62013-06-20 21:03:13 +00002206bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2207 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00002208 QualType Ty;
2209 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002210 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002211 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002212 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002213 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002214 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002215
Douglas Gregorb4866e82015-06-19 18:13:19 +00002216 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2217 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002218 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002219
Richard Trieu664c4c62013-06-20 21:03:13 +00002220 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00002221 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00002222 CallType = VariadicDoesNotApply;
2223 } else if (Ty->isBlockPointerType()) {
2224 CallType = VariadicBlock;
2225 } else { // Ty->isFunctionPointerType()
2226 CallType = VariadicFunction;
2227 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002228
Douglas Gregorb4866e82015-06-19 18:13:19 +00002229 checkCall(NDecl, Proto,
2230 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2231 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00002232 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00002233
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002234 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00002235}
2236
Richard Trieu41bc0992013-06-22 00:20:41 +00002237/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2238/// such as function pointers returned from functions.
2239bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002240 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00002241 TheCall->getCallee());
Douglas Gregorb4866e82015-06-19 18:13:19 +00002242 checkCall(/*FDecl=*/nullptr, Proto,
Craig Topper8c2a2a02014-08-30 16:55:39 +00002243 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00002244 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00002245 TheCall->getCallee()->getSourceRange(), CallType);
2246
2247 return false;
2248}
2249
Tim Northovere94a34c2014-03-11 10:49:14 +00002250static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
JF Bastiendda2cb12016-04-18 18:01:49 +00002251 if (!llvm::isValidAtomicOrderingCABI(Ordering))
Tim Northovere94a34c2014-03-11 10:49:14 +00002252 return false;
2253
JF Bastiendda2cb12016-04-18 18:01:49 +00002254 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
Tim Northovere94a34c2014-03-11 10:49:14 +00002255 switch (Op) {
2256 case AtomicExpr::AO__c11_atomic_init:
2257 llvm_unreachable("There is no ordering argument for an init");
2258
2259 case AtomicExpr::AO__c11_atomic_load:
2260 case AtomicExpr::AO__atomic_load_n:
2261 case AtomicExpr::AO__atomic_load:
JF Bastiendda2cb12016-04-18 18:01:49 +00002262 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2263 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002264
2265 case AtomicExpr::AO__c11_atomic_store:
2266 case AtomicExpr::AO__atomic_store:
2267 case AtomicExpr::AO__atomic_store_n:
JF Bastiendda2cb12016-04-18 18:01:49 +00002268 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2269 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2270 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002271
2272 default:
2273 return true;
2274 }
2275}
2276
Richard Smithfeea8832012-04-12 05:08:17 +00002277ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2278 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002279 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2280 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002281
Richard Smithfeea8832012-04-12 05:08:17 +00002282 // All these operations take one of the following forms:
2283 enum {
2284 // C __c11_atomic_init(A *, C)
2285 Init,
2286 // C __c11_atomic_load(A *, int)
2287 Load,
2288 // void __atomic_load(A *, CP, int)
Eric Fiselier8d662442016-03-30 23:39:56 +00002289 LoadCopy,
2290 // void __atomic_store(A *, CP, int)
Richard Smithfeea8832012-04-12 05:08:17 +00002291 Copy,
2292 // C __c11_atomic_add(A *, M, int)
2293 Arithmetic,
2294 // C __atomic_exchange_n(A *, CP, int)
2295 Xchg,
2296 // void __atomic_exchange(A *, C *, CP, int)
2297 GNUXchg,
2298 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2299 C11CmpXchg,
2300 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2301 GNUCmpXchg
2302 } Form = Init;
Eric Fiselier8d662442016-03-30 23:39:56 +00002303 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2304 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
Richard Smithfeea8832012-04-12 05:08:17 +00002305 // where:
2306 // C is an appropriate type,
2307 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2308 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2309 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2310 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002311
Gabor Horvath98bd0982015-03-16 09:59:54 +00002312 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2313 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2314 AtomicExpr::AO__atomic_load,
2315 "need to update code for modified C11 atomics");
Richard Smithfeea8832012-04-12 05:08:17 +00002316 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
2317 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
2318 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2319 Op == AtomicExpr::AO__atomic_store_n ||
2320 Op == AtomicExpr::AO__atomic_exchange_n ||
2321 Op == AtomicExpr::AO__atomic_compare_exchange_n;
2322 bool IsAddSub = false;
2323
2324 switch (Op) {
2325 case AtomicExpr::AO__c11_atomic_init:
2326 Form = Init;
2327 break;
2328
2329 case AtomicExpr::AO__c11_atomic_load:
2330 case AtomicExpr::AO__atomic_load_n:
2331 Form = Load;
2332 break;
2333
Richard Smithfeea8832012-04-12 05:08:17 +00002334 case AtomicExpr::AO__atomic_load:
Eric Fiselier8d662442016-03-30 23:39:56 +00002335 Form = LoadCopy;
2336 break;
2337
2338 case AtomicExpr::AO__c11_atomic_store:
Richard Smithfeea8832012-04-12 05:08:17 +00002339 case AtomicExpr::AO__atomic_store:
2340 case AtomicExpr::AO__atomic_store_n:
2341 Form = Copy;
2342 break;
2343
2344 case AtomicExpr::AO__c11_atomic_fetch_add:
2345 case AtomicExpr::AO__c11_atomic_fetch_sub:
2346 case AtomicExpr::AO__atomic_fetch_add:
2347 case AtomicExpr::AO__atomic_fetch_sub:
2348 case AtomicExpr::AO__atomic_add_fetch:
2349 case AtomicExpr::AO__atomic_sub_fetch:
2350 IsAddSub = true;
2351 // Fall through.
2352 case AtomicExpr::AO__c11_atomic_fetch_and:
2353 case AtomicExpr::AO__c11_atomic_fetch_or:
2354 case AtomicExpr::AO__c11_atomic_fetch_xor:
2355 case AtomicExpr::AO__atomic_fetch_and:
2356 case AtomicExpr::AO__atomic_fetch_or:
2357 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00002358 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00002359 case AtomicExpr::AO__atomic_and_fetch:
2360 case AtomicExpr::AO__atomic_or_fetch:
2361 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00002362 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00002363 Form = Arithmetic;
2364 break;
2365
2366 case AtomicExpr::AO__c11_atomic_exchange:
2367 case AtomicExpr::AO__atomic_exchange_n:
2368 Form = Xchg;
2369 break;
2370
2371 case AtomicExpr::AO__atomic_exchange:
2372 Form = GNUXchg;
2373 break;
2374
2375 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
2376 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
2377 Form = C11CmpXchg;
2378 break;
2379
2380 case AtomicExpr::AO__atomic_compare_exchange:
2381 case AtomicExpr::AO__atomic_compare_exchange_n:
2382 Form = GNUCmpXchg;
2383 break;
2384 }
2385
2386 // Check we have the right number of arguments.
2387 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002388 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00002389 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002390 << TheCall->getCallee()->getSourceRange();
2391 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00002392 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
2393 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002394 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00002395 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002396 << TheCall->getCallee()->getSourceRange();
2397 return ExprError();
2398 }
2399
Richard Smithfeea8832012-04-12 05:08:17 +00002400 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002401 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002402 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
2403 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
2404 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00002405 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002406 << Ptr->getType() << Ptr->getSourceRange();
2407 return ExprError();
2408 }
2409
Richard Smithfeea8832012-04-12 05:08:17 +00002410 // For a __c11 builtin, this should be a pointer to an _Atomic type.
2411 QualType AtomTy = pointerType->getPointeeType(); // 'A'
2412 QualType ValType = AtomTy; // 'C'
2413 if (IsC11) {
2414 if (!AtomTy->isAtomicType()) {
2415 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
2416 << Ptr->getType() << Ptr->getSourceRange();
2417 return ExprError();
2418 }
Richard Smithe00921a2012-09-15 06:09:58 +00002419 if (AtomTy.isConstQualified()) {
2420 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
2421 << Ptr->getType() << Ptr->getSourceRange();
2422 return ExprError();
2423 }
Richard Smithfeea8832012-04-12 05:08:17 +00002424 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiselier8d662442016-03-30 23:39:56 +00002425 } else if (Form != Load && Form != LoadCopy) {
Eric Fiseliera3a7c562015-10-04 00:11:02 +00002426 if (ValType.isConstQualified()) {
2427 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
2428 << Ptr->getType() << Ptr->getSourceRange();
2429 return ExprError();
2430 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002431 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002432
Richard Smithfeea8832012-04-12 05:08:17 +00002433 // For an arithmetic operation, the implied arithmetic must be well-formed.
2434 if (Form == Arithmetic) {
2435 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
2436 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
2437 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2438 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2439 return ExprError();
2440 }
2441 if (!IsAddSub && !ValType->isIntegerType()) {
2442 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
2443 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2444 return ExprError();
2445 }
David Majnemere85cff82015-01-28 05:48:06 +00002446 if (IsC11 && ValType->isPointerType() &&
2447 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
2448 diag::err_incomplete_type)) {
2449 return ExprError();
2450 }
Richard Smithfeea8832012-04-12 05:08:17 +00002451 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
2452 // For __atomic_*_n operations, the value type must be a scalar integral or
2453 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002454 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00002455 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2456 return ExprError();
2457 }
2458
Eli Friedmanaa769812013-09-11 03:49:34 +00002459 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
2460 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00002461 // For GNU atomics, require a trivially-copyable type. This is not part of
2462 // the GNU atomics specification, but we enforce it for sanity.
2463 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002464 << Ptr->getType() << Ptr->getSourceRange();
2465 return ExprError();
2466 }
2467
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002468 switch (ValType.getObjCLifetime()) {
2469 case Qualifiers::OCL_None:
2470 case Qualifiers::OCL_ExplicitNone:
2471 // okay
2472 break;
2473
2474 case Qualifiers::OCL_Weak:
2475 case Qualifiers::OCL_Strong:
2476 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00002477 // FIXME: Can this happen? By this point, ValType should be known
2478 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002479 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
2480 << ValType << Ptr->getSourceRange();
2481 return ExprError();
2482 }
2483
David Majnemerc6eb6502015-06-03 00:26:35 +00002484 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
2485 // volatile-ness of the pointee-type inject itself into the result or the
Eric Fiselier8d662442016-03-30 23:39:56 +00002486 // other operands. Similarly atomic_load can take a pointer to a const 'A'.
David Majnemerc6eb6502015-06-03 00:26:35 +00002487 ValType.removeLocalVolatile();
Eric Fiselier8d662442016-03-30 23:39:56 +00002488 ValType.removeLocalConst();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002489 QualType ResultType = ValType;
Eric Fiselier8d662442016-03-30 23:39:56 +00002490 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002491 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00002492 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002493 ResultType = Context.BoolTy;
2494
Richard Smithfeea8832012-04-12 05:08:17 +00002495 // The type of a parameter passed 'by value'. In the GNU atomics, such
2496 // arguments are actually passed as pointers.
2497 QualType ByValType = ValType; // 'CP'
2498 if (!IsC11 && !IsN)
2499 ByValType = Ptr->getType();
2500
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002501 // The first argument --- the pointer --- has a fixed type; we
2502 // deduce the types of the rest of the arguments accordingly. Walk
2503 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00002504 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002505 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00002506 if (i < NumVals[Form] + 1) {
2507 switch (i) {
2508 case 1:
2509 // The second argument is the non-atomic operand. For arithmetic, this
2510 // is always passed by value, and for a compare_exchange it is always
2511 // passed by address. For the rest, GNU uses by-address and C11 uses
2512 // by-value.
2513 assert(Form != Load);
2514 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
2515 Ty = ValType;
2516 else if (Form == Copy || Form == Xchg)
2517 Ty = ByValType;
2518 else if (Form == Arithmetic)
2519 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00002520 else {
2521 Expr *ValArg = TheCall->getArg(i);
2522 unsigned AS = 0;
2523 // Keep address space of non-atomic pointer type.
2524 if (const PointerType *PtrTy =
2525 ValArg->getType()->getAs<PointerType>()) {
2526 AS = PtrTy->getPointeeType().getAddressSpace();
2527 }
2528 Ty = Context.getPointerType(
2529 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
2530 }
Richard Smithfeea8832012-04-12 05:08:17 +00002531 break;
2532 case 2:
2533 // The third argument to compare_exchange / GNU exchange is a
2534 // (pointer to a) desired value.
2535 Ty = ByValType;
2536 break;
2537 case 3:
2538 // The fourth argument to GNU compare_exchange is a 'weak' flag.
2539 Ty = Context.BoolTy;
2540 break;
2541 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002542 } else {
2543 // The order(s) are always converted to int.
2544 Ty = Context.IntTy;
2545 }
Richard Smithfeea8832012-04-12 05:08:17 +00002546
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002547 InitializedEntity Entity =
2548 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00002549 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002550 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2551 if (Arg.isInvalid())
2552 return true;
2553 TheCall->setArg(i, Arg.get());
2554 }
2555
Richard Smithfeea8832012-04-12 05:08:17 +00002556 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002557 SmallVector<Expr*, 5> SubExprs;
2558 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00002559 switch (Form) {
2560 case Init:
2561 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00002562 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00002563 break;
2564 case Load:
2565 SubExprs.push_back(TheCall->getArg(1)); // Order
2566 break;
Eric Fiselier8d662442016-03-30 23:39:56 +00002567 case LoadCopy:
Richard Smithfeea8832012-04-12 05:08:17 +00002568 case Copy:
2569 case Arithmetic:
2570 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002571 SubExprs.push_back(TheCall->getArg(2)); // Order
2572 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00002573 break;
2574 case GNUXchg:
2575 // Note, AtomicExpr::getVal2() has a special case for this atomic.
2576 SubExprs.push_back(TheCall->getArg(3)); // Order
2577 SubExprs.push_back(TheCall->getArg(1)); // Val1
2578 SubExprs.push_back(TheCall->getArg(2)); // Val2
2579 break;
2580 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002581 SubExprs.push_back(TheCall->getArg(3)); // Order
2582 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002583 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00002584 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00002585 break;
2586 case GNUCmpXchg:
2587 SubExprs.push_back(TheCall->getArg(4)); // Order
2588 SubExprs.push_back(TheCall->getArg(1)); // Val1
2589 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
2590 SubExprs.push_back(TheCall->getArg(2)); // Val2
2591 SubExprs.push_back(TheCall->getArg(3)); // Weak
2592 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002593 }
Tim Northovere94a34c2014-03-11 10:49:14 +00002594
2595 if (SubExprs.size() >= 2 && Form != Init) {
2596 llvm::APSInt Result(32);
2597 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
2598 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00002599 Diag(SubExprs[1]->getLocStart(),
2600 diag::warn_atomic_op_has_invalid_memory_order)
2601 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00002602 }
2603
Fariborz Jahanian615de762013-05-28 17:37:39 +00002604 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
2605 SubExprs, ResultType, Op,
2606 TheCall->getRParenLoc());
2607
2608 if ((Op == AtomicExpr::AO__c11_atomic_load ||
2609 (Op == AtomicExpr::AO__c11_atomic_store)) &&
2610 Context.AtomicUsesUnsupportedLibcall(AE))
2611 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
2612 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002613
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002614 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002615}
2616
John McCall29ad95b2011-08-27 01:09:30 +00002617/// checkBuiltinArgument - Given a call to a builtin function, perform
2618/// normal type-checking on the given argument, updating the call in
2619/// place. This is useful when a builtin function requires custom
2620/// type-checking for some of its arguments but not necessarily all of
2621/// them.
2622///
2623/// Returns true on error.
2624static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
2625 FunctionDecl *Fn = E->getDirectCallee();
2626 assert(Fn && "builtin call without direct callee!");
2627
2628 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
2629 InitializedEntity Entity =
2630 InitializedEntity::InitializeParameter(S.Context, Param);
2631
2632 ExprResult Arg = E->getArg(0);
2633 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
2634 if (Arg.isInvalid())
2635 return true;
2636
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002637 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00002638 return false;
2639}
2640
Chris Lattnerdc046542009-05-08 06:58:22 +00002641/// SemaBuiltinAtomicOverloaded - We have a call to a function like
2642/// __sync_fetch_and_add, which is an overloaded function based on the pointer
2643/// type of its first argument. The main ActOnCallExpr routines have already
2644/// promoted the types of arguments because all of these calls are prototyped as
2645/// void(...).
2646///
2647/// This function goes through and does final semantic checking for these
2648/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00002649ExprResult
2650Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002651 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00002652 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2653 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2654
2655 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002656 if (TheCall->getNumArgs() < 1) {
2657 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2658 << 0 << 1 << TheCall->getNumArgs()
2659 << TheCall->getCallee()->getSourceRange();
2660 return ExprError();
2661 }
Mike Stump11289f42009-09-09 15:08:12 +00002662
Chris Lattnerdc046542009-05-08 06:58:22 +00002663 // Inspect the first argument of the atomic builtin. This should always be
2664 // a pointer type, whose element is an integral scalar or pointer type.
2665 // Because it is a pointer type, we don't have to worry about any implicit
2666 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002667 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00002668 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00002669 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
2670 if (FirstArgResult.isInvalid())
2671 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002672 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00002673 TheCall->setArg(0, FirstArg);
2674
John McCall31168b02011-06-15 23:02:42 +00002675 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
2676 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002677 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
2678 << FirstArg->getType() << FirstArg->getSourceRange();
2679 return ExprError();
2680 }
Mike Stump11289f42009-09-09 15:08:12 +00002681
John McCall31168b02011-06-15 23:02:42 +00002682 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00002683 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002684 !ValType->isBlockPointerType()) {
2685 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
2686 << FirstArg->getType() << FirstArg->getSourceRange();
2687 return ExprError();
2688 }
Chris Lattnerdc046542009-05-08 06:58:22 +00002689
John McCall31168b02011-06-15 23:02:42 +00002690 switch (ValType.getObjCLifetime()) {
2691 case Qualifiers::OCL_None:
2692 case Qualifiers::OCL_ExplicitNone:
2693 // okay
2694 break;
2695
2696 case Qualifiers::OCL_Weak:
2697 case Qualifiers::OCL_Strong:
2698 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00002699 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00002700 << ValType << FirstArg->getSourceRange();
2701 return ExprError();
2702 }
2703
John McCallb50451a2011-10-05 07:41:44 +00002704 // Strip any qualifiers off ValType.
2705 ValType = ValType.getUnqualifiedType();
2706
Chandler Carruth3973af72010-07-18 20:54:12 +00002707 // The majority of builtins return a value, but a few have special return
2708 // types, so allow them to override appropriately below.
2709 QualType ResultType = ValType;
2710
Chris Lattnerdc046542009-05-08 06:58:22 +00002711 // We need to figure out which concrete builtin this maps onto. For example,
2712 // __sync_fetch_and_add with a 2 byte object turns into
2713 // __sync_fetch_and_add_2.
2714#define BUILTIN_ROW(x) \
2715 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
2716 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00002717
Chris Lattnerdc046542009-05-08 06:58:22 +00002718 static const unsigned BuiltinIndices[][5] = {
2719 BUILTIN_ROW(__sync_fetch_and_add),
2720 BUILTIN_ROW(__sync_fetch_and_sub),
2721 BUILTIN_ROW(__sync_fetch_and_or),
2722 BUILTIN_ROW(__sync_fetch_and_and),
2723 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00002724 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00002725
Chris Lattnerdc046542009-05-08 06:58:22 +00002726 BUILTIN_ROW(__sync_add_and_fetch),
2727 BUILTIN_ROW(__sync_sub_and_fetch),
2728 BUILTIN_ROW(__sync_and_and_fetch),
2729 BUILTIN_ROW(__sync_or_and_fetch),
2730 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00002731 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00002732
Chris Lattnerdc046542009-05-08 06:58:22 +00002733 BUILTIN_ROW(__sync_val_compare_and_swap),
2734 BUILTIN_ROW(__sync_bool_compare_and_swap),
2735 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00002736 BUILTIN_ROW(__sync_lock_release),
2737 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00002738 };
Mike Stump11289f42009-09-09 15:08:12 +00002739#undef BUILTIN_ROW
2740
Chris Lattnerdc046542009-05-08 06:58:22 +00002741 // Determine the index of the size.
2742 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00002743 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00002744 case 1: SizeIndex = 0; break;
2745 case 2: SizeIndex = 1; break;
2746 case 4: SizeIndex = 2; break;
2747 case 8: SizeIndex = 3; break;
2748 case 16: SizeIndex = 4; break;
2749 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002750 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
2751 << FirstArg->getType() << FirstArg->getSourceRange();
2752 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00002753 }
Mike Stump11289f42009-09-09 15:08:12 +00002754
Chris Lattnerdc046542009-05-08 06:58:22 +00002755 // Each of these builtins has one pointer argument, followed by some number of
2756 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
2757 // that we ignore. Find out which row of BuiltinIndices to read from as well
2758 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00002759 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00002760 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00002761 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00002762 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00002763 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00002764 case Builtin::BI__sync_fetch_and_add:
2765 case Builtin::BI__sync_fetch_and_add_1:
2766 case Builtin::BI__sync_fetch_and_add_2:
2767 case Builtin::BI__sync_fetch_and_add_4:
2768 case Builtin::BI__sync_fetch_and_add_8:
2769 case Builtin::BI__sync_fetch_and_add_16:
2770 BuiltinIndex = 0;
2771 break;
2772
2773 case Builtin::BI__sync_fetch_and_sub:
2774 case Builtin::BI__sync_fetch_and_sub_1:
2775 case Builtin::BI__sync_fetch_and_sub_2:
2776 case Builtin::BI__sync_fetch_and_sub_4:
2777 case Builtin::BI__sync_fetch_and_sub_8:
2778 case Builtin::BI__sync_fetch_and_sub_16:
2779 BuiltinIndex = 1;
2780 break;
2781
2782 case Builtin::BI__sync_fetch_and_or:
2783 case Builtin::BI__sync_fetch_and_or_1:
2784 case Builtin::BI__sync_fetch_and_or_2:
2785 case Builtin::BI__sync_fetch_and_or_4:
2786 case Builtin::BI__sync_fetch_and_or_8:
2787 case Builtin::BI__sync_fetch_and_or_16:
2788 BuiltinIndex = 2;
2789 break;
2790
2791 case Builtin::BI__sync_fetch_and_and:
2792 case Builtin::BI__sync_fetch_and_and_1:
2793 case Builtin::BI__sync_fetch_and_and_2:
2794 case Builtin::BI__sync_fetch_and_and_4:
2795 case Builtin::BI__sync_fetch_and_and_8:
2796 case Builtin::BI__sync_fetch_and_and_16:
2797 BuiltinIndex = 3;
2798 break;
Mike Stump11289f42009-09-09 15:08:12 +00002799
Douglas Gregor73722482011-11-28 16:30:08 +00002800 case Builtin::BI__sync_fetch_and_xor:
2801 case Builtin::BI__sync_fetch_and_xor_1:
2802 case Builtin::BI__sync_fetch_and_xor_2:
2803 case Builtin::BI__sync_fetch_and_xor_4:
2804 case Builtin::BI__sync_fetch_and_xor_8:
2805 case Builtin::BI__sync_fetch_and_xor_16:
2806 BuiltinIndex = 4;
2807 break;
2808
Hal Finkeld2208b52014-10-02 20:53:50 +00002809 case Builtin::BI__sync_fetch_and_nand:
2810 case Builtin::BI__sync_fetch_and_nand_1:
2811 case Builtin::BI__sync_fetch_and_nand_2:
2812 case Builtin::BI__sync_fetch_and_nand_4:
2813 case Builtin::BI__sync_fetch_and_nand_8:
2814 case Builtin::BI__sync_fetch_and_nand_16:
2815 BuiltinIndex = 5;
2816 WarnAboutSemanticsChange = true;
2817 break;
2818
Douglas Gregor73722482011-11-28 16:30:08 +00002819 case Builtin::BI__sync_add_and_fetch:
2820 case Builtin::BI__sync_add_and_fetch_1:
2821 case Builtin::BI__sync_add_and_fetch_2:
2822 case Builtin::BI__sync_add_and_fetch_4:
2823 case Builtin::BI__sync_add_and_fetch_8:
2824 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002825 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00002826 break;
2827
2828 case Builtin::BI__sync_sub_and_fetch:
2829 case Builtin::BI__sync_sub_and_fetch_1:
2830 case Builtin::BI__sync_sub_and_fetch_2:
2831 case Builtin::BI__sync_sub_and_fetch_4:
2832 case Builtin::BI__sync_sub_and_fetch_8:
2833 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002834 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00002835 break;
2836
2837 case Builtin::BI__sync_and_and_fetch:
2838 case Builtin::BI__sync_and_and_fetch_1:
2839 case Builtin::BI__sync_and_and_fetch_2:
2840 case Builtin::BI__sync_and_and_fetch_4:
2841 case Builtin::BI__sync_and_and_fetch_8:
2842 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002843 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00002844 break;
2845
2846 case Builtin::BI__sync_or_and_fetch:
2847 case Builtin::BI__sync_or_and_fetch_1:
2848 case Builtin::BI__sync_or_and_fetch_2:
2849 case Builtin::BI__sync_or_and_fetch_4:
2850 case Builtin::BI__sync_or_and_fetch_8:
2851 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002852 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00002853 break;
2854
2855 case Builtin::BI__sync_xor_and_fetch:
2856 case Builtin::BI__sync_xor_and_fetch_1:
2857 case Builtin::BI__sync_xor_and_fetch_2:
2858 case Builtin::BI__sync_xor_and_fetch_4:
2859 case Builtin::BI__sync_xor_and_fetch_8:
2860 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002861 BuiltinIndex = 10;
2862 break;
2863
2864 case Builtin::BI__sync_nand_and_fetch:
2865 case Builtin::BI__sync_nand_and_fetch_1:
2866 case Builtin::BI__sync_nand_and_fetch_2:
2867 case Builtin::BI__sync_nand_and_fetch_4:
2868 case Builtin::BI__sync_nand_and_fetch_8:
2869 case Builtin::BI__sync_nand_and_fetch_16:
2870 BuiltinIndex = 11;
2871 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00002872 break;
Mike Stump11289f42009-09-09 15:08:12 +00002873
Chris Lattnerdc046542009-05-08 06:58:22 +00002874 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00002875 case Builtin::BI__sync_val_compare_and_swap_1:
2876 case Builtin::BI__sync_val_compare_and_swap_2:
2877 case Builtin::BI__sync_val_compare_and_swap_4:
2878 case Builtin::BI__sync_val_compare_and_swap_8:
2879 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002880 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00002881 NumFixed = 2;
2882 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002883
Chris Lattnerdc046542009-05-08 06:58:22 +00002884 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00002885 case Builtin::BI__sync_bool_compare_and_swap_1:
2886 case Builtin::BI__sync_bool_compare_and_swap_2:
2887 case Builtin::BI__sync_bool_compare_and_swap_4:
2888 case Builtin::BI__sync_bool_compare_and_swap_8:
2889 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002890 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00002891 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00002892 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00002893 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002894
2895 case Builtin::BI__sync_lock_test_and_set:
2896 case Builtin::BI__sync_lock_test_and_set_1:
2897 case Builtin::BI__sync_lock_test_and_set_2:
2898 case Builtin::BI__sync_lock_test_and_set_4:
2899 case Builtin::BI__sync_lock_test_and_set_8:
2900 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002901 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00002902 break;
2903
Chris Lattnerdc046542009-05-08 06:58:22 +00002904 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00002905 case Builtin::BI__sync_lock_release_1:
2906 case Builtin::BI__sync_lock_release_2:
2907 case Builtin::BI__sync_lock_release_4:
2908 case Builtin::BI__sync_lock_release_8:
2909 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002910 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00002911 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00002912 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00002913 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002914
2915 case Builtin::BI__sync_swap:
2916 case Builtin::BI__sync_swap_1:
2917 case Builtin::BI__sync_swap_2:
2918 case Builtin::BI__sync_swap_4:
2919 case Builtin::BI__sync_swap_8:
2920 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002921 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00002922 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00002923 }
Mike Stump11289f42009-09-09 15:08:12 +00002924
Chris Lattnerdc046542009-05-08 06:58:22 +00002925 // Now that we know how many fixed arguments we expect, first check that we
2926 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002927 if (TheCall->getNumArgs() < 1+NumFixed) {
2928 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2929 << 0 << 1+NumFixed << TheCall->getNumArgs()
2930 << TheCall->getCallee()->getSourceRange();
2931 return ExprError();
2932 }
Mike Stump11289f42009-09-09 15:08:12 +00002933
Hal Finkeld2208b52014-10-02 20:53:50 +00002934 if (WarnAboutSemanticsChange) {
2935 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
2936 << TheCall->getCallee()->getSourceRange();
2937 }
2938
Chris Lattner5b9241b2009-05-08 15:36:58 +00002939 // Get the decl for the concrete builtin from this, we can tell what the
2940 // concrete integer type we should convert to is.
2941 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Eric Christopher02d5d862015-08-06 01:01:12 +00002942 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00002943 FunctionDecl *NewBuiltinDecl;
2944 if (NewBuiltinID == BuiltinID)
2945 NewBuiltinDecl = FDecl;
2946 else {
2947 // Perform builtin lookup to avoid redeclaring it.
2948 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
2949 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
2950 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
2951 assert(Res.getFoundDecl());
2952 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00002953 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00002954 return ExprError();
2955 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002956
John McCallcf142162010-08-07 06:22:56 +00002957 // The first argument --- the pointer --- has a fixed type; we
2958 // deduce the types of the rest of the arguments accordingly. Walk
2959 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00002960 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00002961 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00002962
Chris Lattnerdc046542009-05-08 06:58:22 +00002963 // GCC does an implicit conversion to the pointer or integer ValType. This
2964 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00002965 // Initialize the argument.
2966 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2967 ValType, /*consume*/ false);
2968 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00002969 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002970 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002971
Chris Lattnerdc046542009-05-08 06:58:22 +00002972 // Okay, we have something that *can* be converted to the right type. Check
2973 // to see if there is a potentially weird extension going on here. This can
2974 // happen when you do an atomic operation on something like an char* and
2975 // pass in 42. The 42 gets converted to char. This is even more strange
2976 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00002977 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002978 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00002979 }
Mike Stump11289f42009-09-09 15:08:12 +00002980
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002981 ASTContext& Context = this->getASTContext();
2982
2983 // Create a new DeclRefExpr to refer to the new decl.
2984 DeclRefExpr* NewDRE = DeclRefExpr::Create(
2985 Context,
2986 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00002987 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002988 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00002989 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002990 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00002991 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002992 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00002993
Chris Lattnerdc046542009-05-08 06:58:22 +00002994 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00002995 // FIXME: This loses syntactic information.
2996 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
2997 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
2998 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002999 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00003000
Chandler Carruthbc8cab12010-07-18 07:23:17 +00003001 // Change the result type of the call to match the original value type. This
3002 // is arbitrary, but the codegen for these builtins ins design to handle it
3003 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00003004 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003005
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003006 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00003007}
3008
Michael Zolotukhin84df1232015-09-08 23:52:33 +00003009/// SemaBuiltinNontemporalOverloaded - We have a call to
3010/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3011/// overloaded function based on the pointer type of its last argument.
3012///
3013/// This function goes through and does final semantic checking for these
3014/// builtins.
3015ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3016 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3017 DeclRefExpr *DRE =
3018 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3019 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3020 unsigned BuiltinID = FDecl->getBuiltinID();
3021 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3022 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3023 "Unexpected nontemporal load/store builtin!");
3024 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3025 unsigned numArgs = isStore ? 2 : 1;
3026
3027 // Ensure that we have the proper number of arguments.
3028 if (checkArgCount(*this, TheCall, numArgs))
3029 return ExprError();
3030
3031 // Inspect the last argument of the nontemporal builtin. This should always
3032 // be a pointer type, from which we imply the type of the memory access.
3033 // Because it is a pointer type, we don't have to worry about any implicit
3034 // casts here.
3035 Expr *PointerArg = TheCall->getArg(numArgs - 1);
3036 ExprResult PointerArgResult =
3037 DefaultFunctionArrayLvalueConversion(PointerArg);
3038
3039 if (PointerArgResult.isInvalid())
3040 return ExprError();
3041 PointerArg = PointerArgResult.get();
3042 TheCall->setArg(numArgs - 1, PointerArg);
3043
3044 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3045 if (!pointerType) {
3046 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3047 << PointerArg->getType() << PointerArg->getSourceRange();
3048 return ExprError();
3049 }
3050
3051 QualType ValType = pointerType->getPointeeType();
3052
3053 // Strip any qualifiers off ValType.
3054 ValType = ValType.getUnqualifiedType();
3055 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3056 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3057 !ValType->isVectorType()) {
3058 Diag(DRE->getLocStart(),
3059 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3060 << PointerArg->getType() << PointerArg->getSourceRange();
3061 return ExprError();
3062 }
3063
3064 if (!isStore) {
3065 TheCall->setType(ValType);
3066 return TheCallResult;
3067 }
3068
3069 ExprResult ValArg = TheCall->getArg(0);
3070 InitializedEntity Entity = InitializedEntity::InitializeParameter(
3071 Context, ValType, /*consume*/ false);
3072 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3073 if (ValArg.isInvalid())
3074 return ExprError();
3075
3076 TheCall->setArg(0, ValArg.get());
3077 TheCall->setType(Context.VoidTy);
3078 return TheCallResult;
3079}
3080
Chris Lattner6436fb62009-02-18 06:01:06 +00003081/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00003082/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00003083/// Note: It might also make sense to do the UTF-16 conversion here (would
3084/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00003085bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00003086 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00003087 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3088
Douglas Gregorfb65e592011-07-27 05:40:30 +00003089 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003090 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3091 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00003092 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00003093 }
Mike Stump11289f42009-09-09 15:08:12 +00003094
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003095 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003096 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003097 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003098 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00003099 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003100 UTF16 *ToPtr = &ToBuf[0];
3101
3102 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
3103 &ToPtr, ToPtr + NumBytes,
3104 strictConversion);
3105 // Check for conversion failure.
3106 if (Result != conversionOK)
3107 Diag(Arg->getLocStart(),
3108 diag::warn_cfstring_truncated) << Arg->getSourceRange();
3109 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00003110 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003111}
3112
Charles Davisc7d5c942015-09-17 20:55:33 +00003113/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3114/// for validity. Emit an error and return true on failure; return false
3115/// on success.
3116bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00003117 Expr *Fn = TheCall->getCallee();
3118 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00003119 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003120 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003121 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3122 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00003123 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003124 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00003125 return true;
3126 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003127
3128 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00003129 return Diag(TheCall->getLocEnd(),
3130 diag::err_typecheck_call_too_few_args_at_least)
3131 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003132 }
3133
John McCall29ad95b2011-08-27 01:09:30 +00003134 // Type-check the first argument normally.
3135 if (checkBuiltinArgument(*this, TheCall, 0))
3136 return true;
3137
Chris Lattnere202e6a2007-12-20 00:05:45 +00003138 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00003139 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00003140 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00003141 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00003142 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00003143 else if (FunctionDecl *FD = getCurFunctionDecl())
3144 isVariadic = FD->isVariadic();
3145 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00003146 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00003147
Chris Lattnere202e6a2007-12-20 00:05:45 +00003148 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00003149 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3150 return true;
3151 }
Mike Stump11289f42009-09-09 15:08:12 +00003152
Chris Lattner43be2e62007-12-19 23:59:04 +00003153 // Verify that the second argument to the builtin is the last argument of the
3154 // current function or method.
3155 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00003156 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00003157
Nico Weber9eea7642013-05-24 23:31:57 +00003158 // These are valid if SecondArgIsLastNamedArgument is false after the next
3159 // block.
3160 QualType Type;
3161 SourceLocation ParamLoc;
Aaron Ballman1de59c52016-04-24 13:30:21 +00003162 bool IsCRegister = false;
Nico Weber9eea7642013-05-24 23:31:57 +00003163
Anders Carlsson6a8350b2008-02-11 04:20:54 +00003164 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3165 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00003166 // FIXME: This isn't correct for methods (results in bogus warning).
3167 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00003168 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00003169 if (CurBlock)
David Majnemera3debed2016-06-24 05:33:44 +00003170 LastArg = CurBlock->TheDecl->parameters().back();
Steve Naroff439a3e42009-04-15 19:33:47 +00003171 else if (FunctionDecl *FD = getCurFunctionDecl())
David Majnemera3debed2016-06-24 05:33:44 +00003172 LastArg = FD->parameters().back();
Chris Lattner43be2e62007-12-19 23:59:04 +00003173 else
David Majnemera3debed2016-06-24 05:33:44 +00003174 LastArg = getCurMethodDecl()->parameters().back();
Chris Lattner43be2e62007-12-19 23:59:04 +00003175 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00003176
3177 Type = PV->getType();
3178 ParamLoc = PV->getLocation();
Aaron Ballman1de59c52016-04-24 13:30:21 +00003179 IsCRegister =
3180 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
Chris Lattner43be2e62007-12-19 23:59:04 +00003181 }
3182 }
Mike Stump11289f42009-09-09 15:08:12 +00003183
Chris Lattner43be2e62007-12-19 23:59:04 +00003184 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00003185 Diag(TheCall->getArg(1)->getLocStart(),
Aaron Ballman05164812016-04-18 18:10:53 +00003186 diag::warn_second_arg_of_va_start_not_last_named_param);
Aaron Ballman1de59c52016-04-24 13:30:21 +00003187 else if (IsCRegister || Type->isReferenceType() ||
3188 Type->isPromotableIntegerType() ||
3189 Type->isSpecificBuiltinType(BuiltinType::Float)) {
3190 unsigned Reason = 0;
3191 if (Type->isReferenceType()) Reason = 1;
3192 else if (IsCRegister) Reason = 2;
3193 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
Nico Weber9eea7642013-05-24 23:31:57 +00003194 Diag(ParamLoc, diag::note_parameter_type) << Type;
3195 }
3196
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00003197 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00003198 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00003199}
Chris Lattner43be2e62007-12-19 23:59:04 +00003200
Charles Davisc7d5c942015-09-17 20:55:33 +00003201/// Check the arguments to '__builtin_va_start' for validity, and that
3202/// it was called from a function of the native ABI.
3203/// Emit an error and return true on failure; return false on success.
3204bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
3205 // On x86-64 Unix, don't allow this in Win64 ABI functions.
3206 // On x64 Windows, don't allow this in System V ABI functions.
3207 // (Yes, that means there's no corresponding way to support variadic
3208 // System V ABI functions on Windows.)
3209 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) {
3210 unsigned OS = Context.getTargetInfo().getTriple().getOS();
3211 clang::CallingConv CC = CC_C;
3212 if (const FunctionDecl *FD = getCurFunctionDecl())
3213 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3214 if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) ||
3215 (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64))
3216 return Diag(TheCall->getCallee()->getLocStart(),
3217 diag::err_va_start_used_in_wrong_abi_function)
3218 << (OS != llvm::Triple::Win32);
3219 }
3220 return SemaBuiltinVAStartImpl(TheCall);
3221}
3222
3223/// Check the arguments to '__builtin_ms_va_start' for validity, and that
3224/// it was called from a Win64 ABI function.
3225/// Emit an error and return true on failure; return false on success.
3226bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) {
3227 // This only makes sense for x86-64.
3228 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3229 Expr *Callee = TheCall->getCallee();
3230 if (TT.getArch() != llvm::Triple::x86_64)
3231 return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt);
3232 // Don't allow this in System V ABI functions.
3233 clang::CallingConv CC = CC_C;
3234 if (const FunctionDecl *FD = getCurFunctionDecl())
3235 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3236 if (CC == CC_X86_64SysV ||
3237 (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64))
3238 return Diag(Callee->getLocStart(),
3239 diag::err_ms_va_start_used_in_sysv_function);
3240 return SemaBuiltinVAStartImpl(TheCall);
3241}
3242
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003243bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
3244 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
3245 // const char *named_addr);
3246
3247 Expr *Func = Call->getCallee();
3248
3249 if (Call->getNumArgs() < 3)
3250 return Diag(Call->getLocEnd(),
3251 diag::err_typecheck_call_too_few_args_at_least)
3252 << 0 /*function call*/ << 3 << Call->getNumArgs();
3253
3254 // Determine whether the current function is variadic or not.
3255 bool IsVariadic;
3256 if (BlockScopeInfo *CurBlock = getCurBlock())
3257 IsVariadic = CurBlock->TheDecl->isVariadic();
3258 else if (FunctionDecl *FD = getCurFunctionDecl())
3259 IsVariadic = FD->isVariadic();
3260 else if (ObjCMethodDecl *MD = getCurMethodDecl())
3261 IsVariadic = MD->isVariadic();
3262 else
3263 llvm_unreachable("unexpected statement type");
3264
3265 if (!IsVariadic) {
3266 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3267 return true;
3268 }
3269
3270 // Type-check the first argument normally.
3271 if (checkBuiltinArgument(*this, Call, 0))
3272 return true;
3273
Benjamin Kramere0ca6e12015-03-01 18:09:50 +00003274 const struct {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003275 unsigned ArgNo;
3276 QualType Type;
3277 } ArgumentTypes[] = {
3278 { 1, Context.getPointerType(Context.CharTy.withConst()) },
3279 { 2, Context.getSizeType() },
3280 };
3281
3282 for (const auto &AT : ArgumentTypes) {
3283 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
3284 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
3285 continue;
3286 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
3287 << Arg->getType() << AT.Type << 1 /* different class */
3288 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
3289 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
3290 }
3291
3292 return false;
3293}
3294
Chris Lattner2da14fb2007-12-20 00:26:33 +00003295/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
3296/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00003297bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
3298 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00003299 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00003300 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00003301 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00003302 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003303 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003304 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00003305 << SourceRange(TheCall->getArg(2)->getLocStart(),
3306 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003307
John Wiegley01296292011-04-08 18:41:53 +00003308 ExprResult OrigArg0 = TheCall->getArg(0);
3309 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00003310
Chris Lattner2da14fb2007-12-20 00:26:33 +00003311 // Do standard promotions between the two arguments, returning their common
3312 // type.
Chris Lattner08464942007-12-28 05:29:59 +00003313 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00003314 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
3315 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00003316
3317 // Make sure any conversions are pushed back into the call; this is
3318 // type safe since unordered compare builtins are declared as "_Bool
3319 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00003320 TheCall->setArg(0, OrigArg0.get());
3321 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00003322
John Wiegley01296292011-04-08 18:41:53 +00003323 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00003324 return false;
3325
Chris Lattner2da14fb2007-12-20 00:26:33 +00003326 // If the common type isn't a real floating type, then the arguments were
3327 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00003328 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00003329 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003330 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00003331 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
3332 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003333
Chris Lattner2da14fb2007-12-20 00:26:33 +00003334 return false;
3335}
3336
Benjamin Kramer634fc102010-02-15 22:42:31 +00003337/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
3338/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00003339/// to check everything. We expect the last argument to be a floating point
3340/// value.
3341bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
3342 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00003343 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00003344 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00003345 if (TheCall->getNumArgs() > NumArgs)
3346 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003347 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003348 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00003349 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003350 (*(TheCall->arg_end()-1))->getLocEnd());
3351
Benjamin Kramer64aae502010-02-16 10:07:31 +00003352 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00003353
Eli Friedman7e4faac2009-08-31 20:06:00 +00003354 if (OrigArg->isTypeDependent())
3355 return false;
3356
Chris Lattner68784ef2010-05-06 05:50:07 +00003357 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00003358 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00003359 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003360 diag::err_typecheck_call_invalid_unary_fp)
3361 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003362
Chris Lattner68784ef2010-05-06 05:50:07 +00003363 // If this is an implicit conversion from float -> double, remove it.
3364 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
3365 Expr *CastArg = Cast->getSubExpr();
3366 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
3367 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
3368 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00003369 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00003370 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00003371 }
3372 }
3373
Eli Friedman7e4faac2009-08-31 20:06:00 +00003374 return false;
3375}
3376
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003377/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
3378// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00003379ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00003380 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003381 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00003382 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00003383 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3384 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003385
Nate Begemana0110022010-06-08 00:16:34 +00003386 // Determine which of the following types of shufflevector we're checking:
3387 // 1) unary, vector mask: (lhs, mask)
Craig Topperb3174a82016-05-18 04:11:25 +00003388 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
Nate Begemana0110022010-06-08 00:16:34 +00003389 QualType resType = TheCall->getArg(0)->getType();
3390 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00003391
Douglas Gregorc25f7662009-05-19 22:10:17 +00003392 if (!TheCall->getArg(0)->isTypeDependent() &&
3393 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00003394 QualType LHSType = TheCall->getArg(0)->getType();
3395 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00003396
Craig Topperbaca3892013-07-29 06:47:04 +00003397 if (!LHSType->isVectorType() || !RHSType->isVectorType())
3398 return ExprError(Diag(TheCall->getLocStart(),
3399 diag::err_shufflevector_non_vector)
3400 << SourceRange(TheCall->getArg(0)->getLocStart(),
3401 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00003402
Nate Begemana0110022010-06-08 00:16:34 +00003403 numElements = LHSType->getAs<VectorType>()->getNumElements();
3404 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00003405
Nate Begemana0110022010-06-08 00:16:34 +00003406 // Check to see if we have a call with 2 vector arguments, the unary shuffle
3407 // with mask. If so, verify that RHS is an integer vector type with the
3408 // same number of elts as lhs.
3409 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00003410 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00003411 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00003412 return ExprError(Diag(TheCall->getLocStart(),
3413 diag::err_shufflevector_incompatible_vector)
3414 << SourceRange(TheCall->getArg(1)->getLocStart(),
3415 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00003416 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00003417 return ExprError(Diag(TheCall->getLocStart(),
3418 diag::err_shufflevector_incompatible_vector)
3419 << SourceRange(TheCall->getArg(0)->getLocStart(),
3420 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00003421 } else if (numElements != numResElements) {
3422 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00003423 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00003424 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00003425 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003426 }
3427
3428 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00003429 if (TheCall->getArg(i)->isTypeDependent() ||
3430 TheCall->getArg(i)->isValueDependent())
3431 continue;
3432
Nate Begemana0110022010-06-08 00:16:34 +00003433 llvm::APSInt Result(32);
3434 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
3435 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00003436 diag::err_shufflevector_nonconstant_argument)
3437 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003438
Craig Topper50ad5b72013-08-03 17:40:38 +00003439 // Allow -1 which will be translated to undef in the IR.
3440 if (Result.isSigned() && Result.isAllOnesValue())
3441 continue;
3442
Chris Lattner7ab824e2008-08-10 02:05:13 +00003443 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003444 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00003445 diag::err_shufflevector_argument_too_large)
3446 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003447 }
3448
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003449 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003450
Chris Lattner7ab824e2008-08-10 02:05:13 +00003451 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003452 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00003453 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003454 }
3455
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003456 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
3457 TheCall->getCallee()->getLocStart(),
3458 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003459}
Chris Lattner43be2e62007-12-19 23:59:04 +00003460
Hal Finkelc4d7c822013-09-18 03:29:45 +00003461/// SemaConvertVectorExpr - Handle __builtin_convertvector
3462ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
3463 SourceLocation BuiltinLoc,
3464 SourceLocation RParenLoc) {
3465 ExprValueKind VK = VK_RValue;
3466 ExprObjectKind OK = OK_Ordinary;
3467 QualType DstTy = TInfo->getType();
3468 QualType SrcTy = E->getType();
3469
3470 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
3471 return ExprError(Diag(BuiltinLoc,
3472 diag::err_convertvector_non_vector)
3473 << E->getSourceRange());
3474 if (!DstTy->isVectorType() && !DstTy->isDependentType())
3475 return ExprError(Diag(BuiltinLoc,
3476 diag::err_convertvector_non_vector_type));
3477
3478 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
3479 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
3480 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
3481 if (SrcElts != DstElts)
3482 return ExprError(Diag(BuiltinLoc,
3483 diag::err_convertvector_incompatible_vector)
3484 << E->getSourceRange());
3485 }
3486
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003487 return new (Context)
3488 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00003489}
3490
Daniel Dunbarb7257262008-07-21 22:59:13 +00003491/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
3492// This is declared to take (const void*, ...) and can take two
3493// optional constant int args.
3494bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00003495 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003496
Chris Lattner3b054132008-11-19 05:08:23 +00003497 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003498 return Diag(TheCall->getLocEnd(),
3499 diag::err_typecheck_call_too_many_args_at_most)
3500 << 0 /*function call*/ << 3 << NumArgs
3501 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003502
3503 // Argument 0 is checked for us and the remaining arguments must be
3504 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00003505 for (unsigned i = 1; i != NumArgs; ++i)
3506 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00003507 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003508
Warren Hunt20e4a5d2014-02-21 23:08:53 +00003509 return false;
3510}
3511
Hal Finkelf0417332014-07-17 14:25:55 +00003512/// SemaBuiltinAssume - Handle __assume (MS Extension).
3513// __assume does not evaluate its arguments, and should warn if its argument
3514// has side effects.
3515bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
3516 Expr *Arg = TheCall->getArg(0);
3517 if (Arg->isInstantiationDependent()) return false;
3518
3519 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00003520 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00003521 << Arg->getSourceRange()
3522 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
3523
3524 return false;
3525}
3526
3527/// Handle __builtin_assume_aligned. This is declared
3528/// as (const void*, size_t, ...) and can take one optional constant int arg.
3529bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
3530 unsigned NumArgs = TheCall->getNumArgs();
3531
3532 if (NumArgs > 3)
3533 return Diag(TheCall->getLocEnd(),
3534 diag::err_typecheck_call_too_many_args_at_most)
3535 << 0 /*function call*/ << 3 << NumArgs
3536 << TheCall->getSourceRange();
3537
3538 // The alignment must be a constant integer.
3539 Expr *Arg = TheCall->getArg(1);
3540
3541 // We can't check the value of a dependent argument.
3542 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
3543 llvm::APSInt Result;
3544 if (SemaBuiltinConstantArg(TheCall, 1, Result))
3545 return true;
3546
3547 if (!Result.isPowerOf2())
3548 return Diag(TheCall->getLocStart(),
3549 diag::err_alignment_not_power_of_two)
3550 << Arg->getSourceRange();
3551 }
3552
3553 if (NumArgs > 2) {
3554 ExprResult Arg(TheCall->getArg(2));
3555 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3556 Context.getSizeType(), false);
3557 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3558 if (Arg.isInvalid()) return true;
3559 TheCall->setArg(2, Arg.get());
3560 }
Hal Finkelf0417332014-07-17 14:25:55 +00003561
3562 return false;
3563}
3564
Eric Christopher8d0c6212010-04-17 02:26:23 +00003565/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
3566/// TheCall is a constant expression.
3567bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
3568 llvm::APSInt &Result) {
3569 Expr *Arg = TheCall->getArg(ArgNum);
3570 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3571 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3572
3573 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
3574
3575 if (!Arg->isIntegerConstantExpr(Result, Context))
3576 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00003577 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00003578
Chris Lattnerd545ad12009-09-23 06:06:36 +00003579 return false;
3580}
3581
Richard Sandiford28940af2014-04-16 08:47:51 +00003582/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
3583/// TheCall is a constant expression in the range [Low, High].
3584bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
3585 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00003586 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00003587
3588 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00003589 Expr *Arg = TheCall->getArg(ArgNum);
3590 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00003591 return false;
3592
Eric Christopher8d0c6212010-04-17 02:26:23 +00003593 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00003594 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00003595 return true;
3596
Richard Sandiford28940af2014-04-16 08:47:51 +00003597 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00003598 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00003599 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00003600
3601 return false;
3602}
3603
Luke Cheeseman59b2d832015-06-15 17:51:01 +00003604/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
3605/// TheCall is an ARM/AArch64 special register string literal.
3606bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
3607 int ArgNum, unsigned ExpectedFieldNum,
3608 bool AllowName) {
3609 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
3610 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
3611 BuiltinID == ARM::BI__builtin_arm_rsr ||
3612 BuiltinID == ARM::BI__builtin_arm_rsrp ||
3613 BuiltinID == ARM::BI__builtin_arm_wsr ||
3614 BuiltinID == ARM::BI__builtin_arm_wsrp;
3615 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
3616 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
3617 BuiltinID == AArch64::BI__builtin_arm_rsr ||
3618 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
3619 BuiltinID == AArch64::BI__builtin_arm_wsr ||
3620 BuiltinID == AArch64::BI__builtin_arm_wsrp;
3621 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
3622
3623 // We can't check the value of a dependent argument.
3624 Expr *Arg = TheCall->getArg(ArgNum);
3625 if (Arg->isTypeDependent() || Arg->isValueDependent())
3626 return false;
3627
3628 // Check if the argument is a string literal.
3629 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3630 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
3631 << Arg->getSourceRange();
3632
3633 // Check the type of special register given.
3634 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3635 SmallVector<StringRef, 6> Fields;
3636 Reg.split(Fields, ":");
3637
3638 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
3639 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
3640 << Arg->getSourceRange();
3641
3642 // If the string is the name of a register then we cannot check that it is
3643 // valid here but if the string is of one the forms described in ACLE then we
3644 // can check that the supplied fields are integers and within the valid
3645 // ranges.
3646 if (Fields.size() > 1) {
3647 bool FiveFields = Fields.size() == 5;
3648
3649 bool ValidString = true;
3650 if (IsARMBuiltin) {
3651 ValidString &= Fields[0].startswith_lower("cp") ||
3652 Fields[0].startswith_lower("p");
3653 if (ValidString)
3654 Fields[0] =
3655 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
3656
3657 ValidString &= Fields[2].startswith_lower("c");
3658 if (ValidString)
3659 Fields[2] = Fields[2].drop_front(1);
3660
3661 if (FiveFields) {
3662 ValidString &= Fields[3].startswith_lower("c");
3663 if (ValidString)
3664 Fields[3] = Fields[3].drop_front(1);
3665 }
3666 }
3667
3668 SmallVector<int, 5> Ranges;
3669 if (FiveFields)
3670 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15});
3671 else
3672 Ranges.append({15, 7, 15});
3673
3674 for (unsigned i=0; i<Fields.size(); ++i) {
3675 int IntField;
3676 ValidString &= !Fields[i].getAsInteger(10, IntField);
3677 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
3678 }
3679
3680 if (!ValidString)
3681 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
3682 << Arg->getSourceRange();
3683
3684 } else if (IsAArch64Builtin && Fields.size() == 1) {
3685 // If the register name is one of those that appear in the condition below
3686 // and the special register builtin being used is one of the write builtins,
3687 // then we require that the argument provided for writing to the register
3688 // is an integer constant expression. This is because it will be lowered to
3689 // an MSR (immediate) instruction, so we need to know the immediate at
3690 // compile time.
3691 if (TheCall->getNumArgs() != 2)
3692 return false;
3693
3694 std::string RegLower = Reg.lower();
3695 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
3696 RegLower != "pan" && RegLower != "uao")
3697 return false;
3698
3699 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
3700 }
3701
3702 return false;
3703}
3704
Eli Friedmanc97d0142009-05-03 06:04:26 +00003705/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003706/// This checks that the target supports __builtin_longjmp and
3707/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003708bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003709 if (!Context.getTargetInfo().hasSjLjLowering())
3710 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
3711 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
3712
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003713 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00003714 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00003715
Eric Christopher8d0c6212010-04-17 02:26:23 +00003716 // TODO: This is less than ideal. Overload this to take a value.
3717 if (SemaBuiltinConstantArg(TheCall, 1, Result))
3718 return true;
3719
3720 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003721 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
3722 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
3723
3724 return false;
3725}
3726
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003727/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
3728/// This checks that the target supports __builtin_setjmp.
3729bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
3730 if (!Context.getTargetInfo().hasSjLjLowering())
3731 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
3732 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
3733 return false;
3734}
3735
Richard Smithd7293d72013-08-05 18:49:43 +00003736namespace {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003737class UncoveredArgHandler {
3738 enum { Unknown = -1, AllCovered = -2 };
3739 signed FirstUncoveredArg;
3740 SmallVector<const Expr *, 4> DiagnosticExprs;
3741
3742public:
3743 UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
3744
3745 bool hasUncoveredArg() const {
3746 return (FirstUncoveredArg >= 0);
3747 }
3748
3749 unsigned getUncoveredArg() const {
3750 assert(hasUncoveredArg() && "no uncovered argument");
3751 return FirstUncoveredArg;
3752 }
3753
3754 void setAllCovered() {
3755 // A string has been found with all arguments covered, so clear out
3756 // the diagnostics.
3757 DiagnosticExprs.clear();
3758 FirstUncoveredArg = AllCovered;
3759 }
3760
3761 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
3762 assert(NewFirstUncoveredArg >= 0 && "Outside range");
3763
3764 // Don't update if a previous string covers all arguments.
3765 if (FirstUncoveredArg == AllCovered)
3766 return;
3767
3768 // UncoveredArgHandler tracks the highest uncovered argument index
3769 // and with it all the strings that match this index.
3770 if (NewFirstUncoveredArg == FirstUncoveredArg)
3771 DiagnosticExprs.push_back(StrExpr);
3772 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
3773 DiagnosticExprs.clear();
3774 DiagnosticExprs.push_back(StrExpr);
3775 FirstUncoveredArg = NewFirstUncoveredArg;
3776 }
3777 }
3778
3779 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
3780};
3781
Richard Smithd7293d72013-08-05 18:49:43 +00003782enum StringLiteralCheckType {
3783 SLCT_NotALiteral,
3784 SLCT_UncheckedLiteral,
3785 SLCT_CheckedLiteral
3786};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003787} // end anonymous namespace
Richard Smithd7293d72013-08-05 18:49:43 +00003788
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00003789static void CheckFormatString(Sema &S, const StringLiteral *FExpr,
3790 const Expr *OrigFormatExpr,
3791 ArrayRef<const Expr *> Args,
3792 bool HasVAListArg, unsigned format_idx,
3793 unsigned firstDataArg,
3794 Sema::FormatStringType Type,
3795 bool inFunctionCall,
3796 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003797 llvm::SmallBitVector &CheckedVarArgs,
3798 UncoveredArgHandler &UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00003799
Richard Smith55ce3522012-06-25 20:30:08 +00003800// Determine if an expression is a string literal or constant string.
3801// If this function returns false on the arguments to a function expecting a
3802// format string, we will usually need to emit a warning.
3803// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00003804static StringLiteralCheckType
3805checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
3806 bool HasVAListArg, unsigned format_idx,
3807 unsigned firstDataArg, Sema::FormatStringType Type,
3808 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003809 llvm::SmallBitVector &CheckedVarArgs,
3810 UncoveredArgHandler &UncoveredArg) {
Ted Kremenek808829352010-09-09 03:51:39 +00003811 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00003812 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00003813 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003814
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003815 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00003816
Richard Smithd7293d72013-08-05 18:49:43 +00003817 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00003818 // Technically -Wformat-nonliteral does not warn about this case.
3819 // The behavior of printf and friends in this case is implementation
3820 // dependent. Ideally if the format string cannot be null then
3821 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00003822 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00003823
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003824 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00003825 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003826 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00003827 // The expression is a literal if both sub-expressions were, and it was
3828 // completely checked only if both sub-expressions were checked.
3829 const AbstractConditionalOperator *C =
3830 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003831
3832 // Determine whether it is necessary to check both sub-expressions, for
3833 // example, because the condition expression is a constant that can be
3834 // evaluated at compile time.
3835 bool CheckLeft = true, CheckRight = true;
3836
3837 bool Cond;
3838 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
3839 if (Cond)
3840 CheckRight = false;
3841 else
3842 CheckLeft = false;
3843 }
3844
3845 StringLiteralCheckType Left;
3846 if (!CheckLeft)
3847 Left = SLCT_UncheckedLiteral;
3848 else {
3849 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
3850 HasVAListArg, format_idx, firstDataArg,
3851 Type, CallType, InFunctionCall,
3852 CheckedVarArgs, UncoveredArg);
3853 if (Left == SLCT_NotALiteral || !CheckRight)
3854 return Left;
3855 }
3856
Richard Smith55ce3522012-06-25 20:30:08 +00003857 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00003858 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003859 HasVAListArg, format_idx, firstDataArg,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003860 Type, CallType, InFunctionCall, CheckedVarArgs,
3861 UncoveredArg);
3862
3863 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003864 }
3865
3866 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00003867 E = cast<ImplicitCastExpr>(E)->getSubExpr();
3868 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003869 }
3870
John McCallc07a0c72011-02-17 10:25:35 +00003871 case Stmt::OpaqueValueExprClass:
3872 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
3873 E = src;
3874 goto tryAgain;
3875 }
Richard Smith55ce3522012-06-25 20:30:08 +00003876 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00003877
Ted Kremeneka8890832011-02-24 23:03:04 +00003878 case Stmt::PredefinedExprClass:
3879 // While __func__, etc., are technically not string literals, they
3880 // cannot contain format specifiers and thus are not a security
3881 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00003882 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00003883
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003884 case Stmt::DeclRefExprClass: {
3885 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00003886
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003887 // As an exception, do not flag errors for variables binding to
3888 // const string literals.
3889 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
3890 bool isConstant = false;
3891 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003892
Richard Smithd7293d72013-08-05 18:49:43 +00003893 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
3894 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00003895 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00003896 isConstant = T.isConstant(S.Context) &&
3897 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00003898 } else if (T->isObjCObjectPointerType()) {
3899 // In ObjC, there is usually no "const ObjectPointer" type,
3900 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00003901 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003902 }
Mike Stump11289f42009-09-09 15:08:12 +00003903
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003904 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00003905 if (const Expr *Init = VD->getAnyInitializer()) {
3906 // Look through initializers like const char c[] = { "foo" }
3907 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3908 if (InitList->isStringLiteralInit())
3909 Init = InitList->getInit(0)->IgnoreParenImpCasts();
3910 }
Richard Smithd7293d72013-08-05 18:49:43 +00003911 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003912 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003913 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003914 /*InFunctionCall*/false, CheckedVarArgs,
3915 UncoveredArg);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00003916 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003917 }
Mike Stump11289f42009-09-09 15:08:12 +00003918
Anders Carlssonb012ca92009-06-28 19:55:58 +00003919 // For vprintf* functions (i.e., HasVAListArg==true), we add a
3920 // special check to see if the format string is a function parameter
3921 // of the function calling the printf function. If the function
3922 // has an attribute indicating it is a printf-like function, then we
3923 // should suppress warnings concerning non-literals being used in a call
3924 // to a vprintf function. For example:
3925 //
3926 // void
3927 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
3928 // va_list ap;
3929 // va_start(ap, fmt);
3930 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
3931 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00003932 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003933 if (HasVAListArg) {
3934 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
3935 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
3936 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003937 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003938 // adjust for implicit parameter
3939 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
3940 if (MD->isInstance())
3941 ++PVIndex;
3942 // We also check if the formats are compatible.
3943 // We can't pass a 'scanf' string to a 'printf' function.
3944 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00003945 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00003946 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003947 }
3948 }
3949 }
3950 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003951 }
Mike Stump11289f42009-09-09 15:08:12 +00003952
Richard Smith55ce3522012-06-25 20:30:08 +00003953 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003954 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003955
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00003956 case Stmt::CallExprClass:
3957 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003958 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00003959 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
3960 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
3961 unsigned ArgIndex = FA->getFormatIdx();
3962 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
3963 if (MD->isInstance())
3964 --ArgIndex;
3965 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00003966
Richard Smithd7293d72013-08-05 18:49:43 +00003967 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003968 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00003969 Type, CallType, InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003970 CheckedVarArgs, UncoveredArg);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003971 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3972 unsigned BuiltinID = FD->getBuiltinID();
3973 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
3974 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
3975 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00003976 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003977 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003978 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003979 InFunctionCall, CheckedVarArgs,
3980 UncoveredArg);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003981 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003982 }
3983 }
Mike Stump11289f42009-09-09 15:08:12 +00003984
Richard Smith55ce3522012-06-25 20:30:08 +00003985 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003986 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003987 case Stmt::ObjCStringLiteralClass:
3988 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00003989 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003990
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003991 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003992 StrE = ObjCFExpr->getString();
3993 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003994 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00003995
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003996 if (StrE) {
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00003997 CheckFormatString(S, StrE, E, Args, HasVAListArg, format_idx,
3998 firstDataArg, Type, InFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003999 CheckedVarArgs, UncoveredArg);
Richard Smith55ce3522012-06-25 20:30:08 +00004000 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004001 }
Mike Stump11289f42009-09-09 15:08:12 +00004002
Richard Smith55ce3522012-06-25 20:30:08 +00004003 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004004 }
Mike Stump11289f42009-09-09 15:08:12 +00004005
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004006 default:
Richard Smith55ce3522012-06-25 20:30:08 +00004007 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004008 }
4009}
4010
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004011Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00004012 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004013 .Case("scanf", FST_Scanf)
4014 .Cases("printf", "printf0", FST_Printf)
4015 .Cases("NSString", "CFString", FST_NSString)
4016 .Case("strftime", FST_Strftime)
4017 .Case("strfmon", FST_Strfmon)
4018 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004019 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00004020 .Case("os_trace", FST_OSTrace)
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004021 .Default(FST_Unknown);
4022}
4023
Jordan Rose3e0ec582012-07-19 18:10:23 +00004024/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00004025/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00004026/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004027bool Sema::CheckFormatArguments(const FormatAttr *Format,
4028 ArrayRef<const Expr *> Args,
4029 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004030 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00004031 SourceLocation Loc, SourceRange Range,
4032 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00004033 FormatStringInfo FSI;
4034 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004035 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00004036 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00004037 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00004038 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004039}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00004040
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004041bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004042 bool HasVAListArg, unsigned format_idx,
4043 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004044 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00004045 SourceLocation Loc, SourceRange Range,
4046 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00004047 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004048 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004049 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00004050 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004051 }
Mike Stump11289f42009-09-09 15:08:12 +00004052
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004053 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00004054
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004055 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00004056 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004057 // Dynamically generated format strings are difficult to
4058 // automatically vet at compile time. Requiring that format strings
4059 // are string literals: (1) permits the checking of format strings by
4060 // the compiler and thereby (2) can practically remove the source of
4061 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00004062
Mike Stump11289f42009-09-09 15:08:12 +00004063 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00004064 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00004065 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00004066 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004067 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00004068 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00004069 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
4070 format_idx, firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004071 /*IsFunctionCall*/true, CheckedVarArgs,
4072 UncoveredArg);
4073
4074 // Generate a diagnostic where an uncovered argument is detected.
4075 if (UncoveredArg.hasUncoveredArg()) {
4076 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
4077 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
4078 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
4079 }
4080
Richard Smith55ce3522012-06-25 20:30:08 +00004081 if (CT != SLCT_NotALiteral)
4082 // Literal format string found, check done!
4083 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00004084
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00004085 // Strftime is particular as it always uses a single 'time' argument,
4086 // so it is safe to pass a non-literal string.
4087 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00004088 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00004089
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00004090 // Do not emit diag when the string param is a macro expansion and the
4091 // format is either NSString or CFString. This is a hack to prevent
4092 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
4093 // which are usually used in place of NS and CF string literals.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004094 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
4095 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
Richard Smith55ce3522012-06-25 20:30:08 +00004096 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00004097
Chris Lattnercc5d1c22009-04-29 04:59:47 +00004098 // If there are no arguments specified, warn with -Wformat-security, otherwise
4099 // warn only with -Wformat-nonliteral.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004100 if (Args.size() == firstDataArg) {
Bob Wilson57819fc2016-03-15 20:56:38 +00004101 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
4102 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004103 switch (Type) {
4104 default:
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004105 break;
4106 case FST_Kprintf:
4107 case FST_FreeBSDKPrintf:
4108 case FST_Printf:
Bob Wilson57819fc2016-03-15 20:56:38 +00004109 Diag(FormatLoc, diag::note_format_security_fixit)
4110 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004111 break;
4112 case FST_NSString:
Bob Wilson57819fc2016-03-15 20:56:38 +00004113 Diag(FormatLoc, diag::note_format_security_fixit)
4114 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004115 break;
4116 }
4117 } else {
4118 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00004119 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004120 }
Richard Smith55ce3522012-06-25 20:30:08 +00004121 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004122}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004123
Ted Kremenekab278de2010-01-28 23:39:18 +00004124namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00004125class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
4126protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00004127 Sema &S;
4128 const StringLiteral *FExpr;
4129 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00004130 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00004131 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00004132 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00004133 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004134 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00004135 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00004136 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00004137 bool usesPositionalArgs;
4138 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00004139 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00004140 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00004141 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004142 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004143
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004144public:
Ted Kremenek02087932010-07-16 02:11:22 +00004145 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00004146 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004147 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004148 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004149 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00004150 Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004151 llvm::SmallBitVector &CheckedVarArgs,
4152 UncoveredArgHandler &UncoveredArg)
Ted Kremenekab278de2010-01-28 23:39:18 +00004153 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004154 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
4155 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004156 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00004157 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00004158 inFunctionCall(inFunctionCall), CallType(callType),
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004159 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00004160 CoveredArgs.resize(numDataArgs);
4161 CoveredArgs.reset();
4162 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004163
Ted Kremenek019d2242010-01-29 01:50:07 +00004164 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004165
Ted Kremenek02087932010-07-16 02:11:22 +00004166 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004167 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004168
Jordan Rose92303592012-09-08 04:00:03 +00004169 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00004170 const analyze_format_string::FormatSpecifier &FS,
4171 const analyze_format_string::ConversionSpecifier &CS,
4172 const char *startSpecifier, unsigned specifierLen,
4173 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00004174
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004175 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00004176 const analyze_format_string::FormatSpecifier &FS,
4177 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004178
4179 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00004180 const analyze_format_string::ConversionSpecifier &CS,
4181 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004182
Craig Toppere14c0f82014-03-12 04:55:44 +00004183 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00004184
Craig Toppere14c0f82014-03-12 04:55:44 +00004185 void HandleInvalidPosition(const char *startSpecifier,
4186 unsigned specifierLen,
4187 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00004188
Craig Toppere14c0f82014-03-12 04:55:44 +00004189 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00004190
Craig Toppere14c0f82014-03-12 04:55:44 +00004191 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004192
Richard Trieu03cf7b72011-10-28 00:41:25 +00004193 template <typename Range>
Benjamin Kramer7320b992016-06-15 14:20:56 +00004194 static void
4195 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
4196 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
4197 bool IsStringLocation, Range StringRange,
4198 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00004199
Ted Kremenek02087932010-07-16 02:11:22 +00004200protected:
Ted Kremenekce815422010-07-19 21:25:57 +00004201 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
4202 const char *startSpec,
4203 unsigned specifierLen,
4204 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00004205
4206 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
4207 const char *startSpec,
4208 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00004209
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004210 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00004211 CharSourceRange getSpecifierRange(const char *startSpecifier,
4212 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00004213 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004214
Ted Kremenek5739de72010-01-29 01:06:55 +00004215 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004216
4217 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
4218 const analyze_format_string::ConversionSpecifier &CS,
4219 const char *startSpecifier, unsigned specifierLen,
4220 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00004221
4222 template <typename Range>
4223 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
4224 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00004225 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00004226};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004227} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00004228
Ted Kremenek02087932010-07-16 02:11:22 +00004229SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00004230 return OrigFormatExpr->getSourceRange();
4231}
4232
Ted Kremenek02087932010-07-16 02:11:22 +00004233CharSourceRange CheckFormatHandler::
4234getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00004235 SourceLocation Start = getLocationOfByte(startSpecifier);
4236 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
4237
4238 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00004239 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00004240
4241 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004242}
4243
Ted Kremenek02087932010-07-16 02:11:22 +00004244SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004245 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00004246}
4247
Ted Kremenek02087932010-07-16 02:11:22 +00004248void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
4249 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00004250 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
4251 getLocationOfByte(startSpecifier),
4252 /*IsStringLocation*/true,
4253 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00004254}
4255
Jordan Rose92303592012-09-08 04:00:03 +00004256void CheckFormatHandler::HandleInvalidLengthModifier(
4257 const analyze_format_string::FormatSpecifier &FS,
4258 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00004259 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00004260 using namespace analyze_format_string;
4261
4262 const LengthModifier &LM = FS.getLengthModifier();
4263 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4264
4265 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00004266 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00004267 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004268 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00004269 getLocationOfByte(LM.getStart()),
4270 /*IsStringLocation*/true,
4271 getSpecifierRange(startSpecifier, specifierLen));
4272
4273 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4274 << FixedLM->toString()
4275 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
4276
4277 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004278 FixItHint Hint;
4279 if (DiagID == diag::warn_format_nonsensical_length)
4280 Hint = FixItHint::CreateRemoval(LMRange);
4281
4282 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00004283 getLocationOfByte(LM.getStart()),
4284 /*IsStringLocation*/true,
4285 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00004286 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00004287 }
4288}
4289
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004290void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00004291 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004292 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004293 using namespace analyze_format_string;
4294
4295 const LengthModifier &LM = FS.getLengthModifier();
4296 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4297
4298 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00004299 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00004300 if (FixedLM) {
4301 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4302 << LM.toString() << 0,
4303 getLocationOfByte(LM.getStart()),
4304 /*IsStringLocation*/true,
4305 getSpecifierRange(startSpecifier, specifierLen));
4306
4307 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4308 << FixedLM->toString()
4309 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
4310
4311 } else {
4312 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4313 << LM.toString() << 0,
4314 getLocationOfByte(LM.getStart()),
4315 /*IsStringLocation*/true,
4316 getSpecifierRange(startSpecifier, specifierLen));
4317 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004318}
4319
4320void CheckFormatHandler::HandleNonStandardConversionSpecifier(
4321 const analyze_format_string::ConversionSpecifier &CS,
4322 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00004323 using namespace analyze_format_string;
4324
4325 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00004326 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00004327 if (FixedCS) {
4328 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4329 << CS.toString() << /*conversion specifier*/1,
4330 getLocationOfByte(CS.getStart()),
4331 /*IsStringLocation*/true,
4332 getSpecifierRange(startSpecifier, specifierLen));
4333
4334 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
4335 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
4336 << FixedCS->toString()
4337 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
4338 } else {
4339 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4340 << CS.toString() << /*conversion specifier*/1,
4341 getLocationOfByte(CS.getStart()),
4342 /*IsStringLocation*/true,
4343 getSpecifierRange(startSpecifier, specifierLen));
4344 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004345}
4346
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00004347void CheckFormatHandler::HandlePosition(const char *startPos,
4348 unsigned posLen) {
4349 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
4350 getLocationOfByte(startPos),
4351 /*IsStringLocation*/true,
4352 getSpecifierRange(startPos, posLen));
4353}
4354
Ted Kremenekd1668192010-02-27 01:41:03 +00004355void
Ted Kremenek02087932010-07-16 02:11:22 +00004356CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
4357 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004358 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
4359 << (unsigned) p,
4360 getLocationOfByte(startPos), /*IsStringLocation*/true,
4361 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00004362}
4363
Ted Kremenek02087932010-07-16 02:11:22 +00004364void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00004365 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004366 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
4367 getLocationOfByte(startPos),
4368 /*IsStringLocation*/true,
4369 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00004370}
4371
Ted Kremenek02087932010-07-16 02:11:22 +00004372void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004373 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00004374 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00004375 EmitFormatDiagnostic(
4376 S.PDiag(diag::warn_printf_format_string_contains_null_char),
4377 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
4378 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00004379 }
Ted Kremenek02087932010-07-16 02:11:22 +00004380}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004381
Jordan Rose58bbe422012-07-19 18:10:08 +00004382// Note that this may return NULL if there was an error parsing or building
4383// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00004384const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004385 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00004386}
4387
4388void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004389 // Does the number of data arguments exceed the number of
4390 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00004391 if (!HasVAListArg) {
4392 // Find any arguments that weren't covered.
4393 CoveredArgs.flip();
4394 signed notCoveredArg = CoveredArgs.find_first();
4395 if (notCoveredArg >= 0) {
4396 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004397 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
4398 } else {
4399 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00004400 }
4401 }
4402}
4403
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004404void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
4405 const Expr *ArgExpr) {
4406 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
4407 "Invalid state");
4408
4409 if (!ArgExpr)
4410 return;
4411
4412 SourceLocation Loc = ArgExpr->getLocStart();
4413
4414 if (S.getSourceManager().isInSystemMacro(Loc))
4415 return;
4416
4417 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
4418 for (auto E : DiagnosticExprs)
4419 PDiag << E->getSourceRange();
4420
4421 CheckFormatHandler::EmitFormatDiagnostic(
4422 S, IsFunctionCall, DiagnosticExprs[0],
4423 PDiag, Loc, /*IsStringLocation*/false,
4424 DiagnosticExprs[0]->getSourceRange());
4425}
4426
Ted Kremenekce815422010-07-19 21:25:57 +00004427bool
4428CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
4429 SourceLocation Loc,
4430 const char *startSpec,
4431 unsigned specifierLen,
4432 const char *csStart,
4433 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00004434 bool keepGoing = true;
4435 if (argIndex < NumDataArgs) {
4436 // Consider the argument coverered, even though the specifier doesn't
4437 // make sense.
4438 CoveredArgs.set(argIndex);
4439 }
4440 else {
4441 // If argIndex exceeds the number of data arguments we
4442 // don't issue a warning because that is just a cascade of warnings (and
4443 // they may have intended '%%' anyway). We don't want to continue processing
4444 // the format string after this point, however, as we will like just get
4445 // gibberish when trying to match arguments.
4446 keepGoing = false;
4447 }
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00004448
4449 StringRef Specifier(csStart, csLen);
4450
4451 // If the specifier in non-printable, it could be the first byte of a UTF-8
4452 // sequence. In that case, print the UTF-8 code point. If not, print the byte
4453 // hex value.
4454 std::string CodePointStr;
4455 if (!llvm::sys::locale::isPrint(*csStart)) {
4456 UTF32 CodePoint;
4457 const UTF8 **B = reinterpret_cast<const UTF8 **>(&csStart);
4458 const UTF8 *E =
4459 reinterpret_cast<const UTF8 *>(csStart + csLen);
4460 ConversionResult Result =
4461 llvm::convertUTF8Sequence(B, E, &CodePoint, strictConversion);
4462
4463 if (Result != conversionOK) {
4464 unsigned char FirstChar = *csStart;
4465 CodePoint = (UTF32)FirstChar;
4466 }
4467
4468 llvm::raw_string_ostream OS(CodePointStr);
4469 if (CodePoint < 256)
4470 OS << "\\x" << llvm::format("%02x", CodePoint);
4471 else if (CodePoint <= 0xFFFF)
4472 OS << "\\u" << llvm::format("%04x", CodePoint);
4473 else
4474 OS << "\\U" << llvm::format("%08x", CodePoint);
4475 OS.flush();
4476 Specifier = CodePointStr;
4477 }
4478
4479 EmitFormatDiagnostic(
4480 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
4481 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
4482
Ted Kremenekce815422010-07-19 21:25:57 +00004483 return keepGoing;
4484}
4485
Richard Trieu03cf7b72011-10-28 00:41:25 +00004486void
4487CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
4488 const char *startSpec,
4489 unsigned specifierLen) {
4490 EmitFormatDiagnostic(
4491 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
4492 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
4493}
4494
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004495bool
4496CheckFormatHandler::CheckNumArgs(
4497 const analyze_format_string::FormatSpecifier &FS,
4498 const analyze_format_string::ConversionSpecifier &CS,
4499 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
4500
4501 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004502 PartialDiagnostic PDiag = FS.usesPositionalArg()
4503 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
4504 << (argIndex+1) << NumDataArgs)
4505 : S.PDiag(diag::warn_printf_insufficient_data_args);
4506 EmitFormatDiagnostic(
4507 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
4508 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004509
4510 // Since more arguments than conversion tokens are given, by extension
4511 // all arguments are covered, so mark this as so.
4512 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004513 return false;
4514 }
4515 return true;
4516}
4517
Richard Trieu03cf7b72011-10-28 00:41:25 +00004518template<typename Range>
4519void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
4520 SourceLocation Loc,
4521 bool IsStringLocation,
4522 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00004523 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004524 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00004525 Loc, IsStringLocation, StringRange, FixIt);
4526}
4527
4528/// \brief If the format string is not within the funcion call, emit a note
4529/// so that the function call and string are in diagnostic messages.
4530///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00004531/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00004532/// call and only one diagnostic message will be produced. Otherwise, an
4533/// extra note will be emitted pointing to location of the format string.
4534///
4535/// \param ArgumentExpr the expression that is passed as the format string
4536/// argument in the function call. Used for getting locations when two
4537/// diagnostics are emitted.
4538///
4539/// \param PDiag the callee should already have provided any strings for the
4540/// diagnostic message. This function only adds locations and fixits
4541/// to diagnostics.
4542///
4543/// \param Loc primary location for diagnostic. If two diagnostics are
4544/// required, one will be at Loc and a new SourceLocation will be created for
4545/// the other one.
4546///
4547/// \param IsStringLocation if true, Loc points to the format string should be
4548/// used for the note. Otherwise, Loc points to the argument list and will
4549/// be used with PDiag.
4550///
4551/// \param StringRange some or all of the string to highlight. This is
4552/// templated so it can accept either a CharSourceRange or a SourceRange.
4553///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00004554/// \param FixIt optional fix it hint for the format string.
Benjamin Kramer7320b992016-06-15 14:20:56 +00004555template <typename Range>
4556void CheckFormatHandler::EmitFormatDiagnostic(
4557 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
4558 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
4559 Range StringRange, ArrayRef<FixItHint> FixIt) {
Jordan Roseaee34382012-09-05 22:56:26 +00004560 if (InFunctionCall) {
4561 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
4562 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00004563 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00004564 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004565 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
4566 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00004567
4568 const Sema::SemaDiagnosticBuilder &Note =
4569 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
4570 diag::note_format_string_defined);
4571
4572 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00004573 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00004574 }
4575}
4576
Ted Kremenek02087932010-07-16 02:11:22 +00004577//===--- CHECK: Printf format string checking ------------------------------===//
4578
4579namespace {
4580class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004581 bool ObjCContext;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004582
Ted Kremenek02087932010-07-16 02:11:22 +00004583public:
4584 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
4585 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004586 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00004587 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004588 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004589 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00004590 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004591 llvm::SmallBitVector &CheckedVarArgs,
4592 UncoveredArgHandler &UncoveredArg)
Richard Smithd7293d72013-08-05 18:49:43 +00004593 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
4594 numDataArgs, beg, hasVAListArg, Args,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004595 formatIdx, inFunctionCall, CallType, CheckedVarArgs,
4596 UncoveredArg),
Richard Smithd7293d72013-08-05 18:49:43 +00004597 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00004598 {}
4599
Ted Kremenek02087932010-07-16 02:11:22 +00004600 bool HandleInvalidPrintfConversionSpecifier(
4601 const analyze_printf::PrintfSpecifier &FS,
4602 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004603 unsigned specifierLen) override;
4604
Ted Kremenek02087932010-07-16 02:11:22 +00004605 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
4606 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004607 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00004608 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
4609 const char *StartSpecifier,
4610 unsigned SpecifierLen,
4611 const Expr *E);
4612
Ted Kremenek02087932010-07-16 02:11:22 +00004613 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
4614 const char *startSpecifier, unsigned specifierLen);
4615 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
4616 const analyze_printf::OptionalAmount &Amt,
4617 unsigned type,
4618 const char *startSpecifier, unsigned specifierLen);
4619 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
4620 const analyze_printf::OptionalFlag &flag,
4621 const char *startSpecifier, unsigned specifierLen);
4622 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
4623 const analyze_printf::OptionalFlag &ignoredFlag,
4624 const analyze_printf::OptionalFlag &flag,
4625 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004626 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00004627 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00004628
4629 void HandleEmptyObjCModifierFlag(const char *startFlag,
4630 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00004631
Ted Kremenek2b417712015-07-02 05:39:16 +00004632 void HandleInvalidObjCModifierFlag(const char *startFlag,
4633 unsigned flagLen) override;
4634
4635 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
4636 const char *flagsEnd,
4637 const char *conversionPosition)
4638 override;
4639};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004640} // end anonymous namespace
Ted Kremenek02087932010-07-16 02:11:22 +00004641
4642bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
4643 const analyze_printf::PrintfSpecifier &FS,
4644 const char *startSpecifier,
4645 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004646 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00004647 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00004648
Ted Kremenekce815422010-07-19 21:25:57 +00004649 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
4650 getLocationOfByte(CS.getStart()),
4651 startSpecifier, specifierLen,
4652 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00004653}
4654
Ted Kremenek02087932010-07-16 02:11:22 +00004655bool CheckPrintfHandler::HandleAmount(
4656 const analyze_format_string::OptionalAmount &Amt,
4657 unsigned k, const char *startSpecifier,
4658 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004659 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004660 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00004661 unsigned argIndex = Amt.getArgIndex();
4662 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004663 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
4664 << k,
4665 getLocationOfByte(Amt.getStart()),
4666 /*IsStringLocation*/true,
4667 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00004668 // Don't do any more checking. We will just emit
4669 // spurious errors.
4670 return false;
4671 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004672
Ted Kremenek5739de72010-01-29 01:06:55 +00004673 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00004674 // Although not in conformance with C99, we also allow the argument to be
4675 // an 'unsigned int' as that is a reasonably safe case. GCC also
4676 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00004677 CoveredArgs.set(argIndex);
4678 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00004679 if (!Arg)
4680 return false;
4681
Ted Kremenek5739de72010-01-29 01:06:55 +00004682 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004683
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004684 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
4685 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004686
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004687 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004688 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004689 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00004690 << T << Arg->getSourceRange(),
4691 getLocationOfByte(Amt.getStart()),
4692 /*IsStringLocation*/true,
4693 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00004694 // Don't do any more checking. We will just emit
4695 // spurious errors.
4696 return false;
4697 }
4698 }
4699 }
4700 return true;
4701}
Ted Kremenek5739de72010-01-29 01:06:55 +00004702
Tom Careb49ec692010-06-17 19:00:27 +00004703void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00004704 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004705 const analyze_printf::OptionalAmount &Amt,
4706 unsigned type,
4707 const char *startSpecifier,
4708 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004709 const analyze_printf::PrintfConversionSpecifier &CS =
4710 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00004711
Richard Trieu03cf7b72011-10-28 00:41:25 +00004712 FixItHint fixit =
4713 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
4714 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
4715 Amt.getConstantLength()))
4716 : FixItHint();
4717
4718 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
4719 << type << CS.toString(),
4720 getLocationOfByte(Amt.getStart()),
4721 /*IsStringLocation*/true,
4722 getSpecifierRange(startSpecifier, specifierLen),
4723 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00004724}
4725
Ted Kremenek02087932010-07-16 02:11:22 +00004726void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004727 const analyze_printf::OptionalFlag &flag,
4728 const char *startSpecifier,
4729 unsigned specifierLen) {
4730 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004731 const analyze_printf::PrintfConversionSpecifier &CS =
4732 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00004733 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
4734 << flag.toString() << CS.toString(),
4735 getLocationOfByte(flag.getPosition()),
4736 /*IsStringLocation*/true,
4737 getSpecifierRange(startSpecifier, specifierLen),
4738 FixItHint::CreateRemoval(
4739 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00004740}
4741
4742void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00004743 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004744 const analyze_printf::OptionalFlag &ignoredFlag,
4745 const analyze_printf::OptionalFlag &flag,
4746 const char *startSpecifier,
4747 unsigned specifierLen) {
4748 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00004749 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
4750 << ignoredFlag.toString() << flag.toString(),
4751 getLocationOfByte(ignoredFlag.getPosition()),
4752 /*IsStringLocation*/true,
4753 getSpecifierRange(startSpecifier, specifierLen),
4754 FixItHint::CreateRemoval(
4755 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00004756}
4757
Ted Kremenek2b417712015-07-02 05:39:16 +00004758// void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
4759// bool IsStringLocation, Range StringRange,
4760// ArrayRef<FixItHint> Fixit = None);
4761
4762void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
4763 unsigned flagLen) {
4764 // Warn about an empty flag.
4765 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
4766 getLocationOfByte(startFlag),
4767 /*IsStringLocation*/true,
4768 getSpecifierRange(startFlag, flagLen));
4769}
4770
4771void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
4772 unsigned flagLen) {
4773 // Warn about an invalid flag.
4774 auto Range = getSpecifierRange(startFlag, flagLen);
4775 StringRef flag(startFlag, flagLen);
4776 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
4777 getLocationOfByte(startFlag),
4778 /*IsStringLocation*/true,
4779 Range, FixItHint::CreateRemoval(Range));
4780}
4781
4782void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
4783 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
4784 // Warn about using '[...]' without a '@' conversion.
4785 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
4786 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
4787 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
4788 getLocationOfByte(conversionPosition),
4789 /*IsStringLocation*/true,
4790 Range, FixItHint::CreateRemoval(Range));
4791}
4792
Richard Smith55ce3522012-06-25 20:30:08 +00004793// Determines if the specified is a C++ class or struct containing
4794// a member with the specified name and kind (e.g. a CXXMethodDecl named
4795// "c_str()").
4796template<typename MemberKind>
4797static llvm::SmallPtrSet<MemberKind*, 1>
4798CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
4799 const RecordType *RT = Ty->getAs<RecordType>();
4800 llvm::SmallPtrSet<MemberKind*, 1> Results;
4801
4802 if (!RT)
4803 return Results;
4804 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00004805 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00004806 return Results;
4807
Alp Tokerb6cc5922014-05-03 03:45:55 +00004808 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00004809 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00004810 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00004811
4812 // We just need to include all members of the right kind turned up by the
4813 // filter, at this point.
4814 if (S.LookupQualifiedName(R, RT->getDecl()))
4815 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
4816 NamedDecl *decl = (*I)->getUnderlyingDecl();
4817 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
4818 Results.insert(FK);
4819 }
4820 return Results;
4821}
4822
Richard Smith2868a732014-02-28 01:36:39 +00004823/// Check if we could call '.c_str()' on an object.
4824///
4825/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
4826/// allow the call, or if it would be ambiguous).
4827bool Sema::hasCStrMethod(const Expr *E) {
4828 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
4829 MethodSet Results =
4830 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
4831 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
4832 MI != ME; ++MI)
4833 if ((*MI)->getMinRequiredArguments() == 0)
4834 return true;
4835 return false;
4836}
4837
Richard Smith55ce3522012-06-25 20:30:08 +00004838// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004839// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00004840// Returns true when a c_str() conversion method is found.
4841bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00004842 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00004843 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
4844
4845 MethodSet Results =
4846 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
4847
4848 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
4849 MI != ME; ++MI) {
4850 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00004851 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00004852 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00004853 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00004854 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00004855 S.Diag(E->getLocStart(), diag::note_printf_c_str)
4856 << "c_str()"
4857 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
4858 return true;
4859 }
4860 }
4861
4862 return false;
4863}
4864
Ted Kremenekab278de2010-01-28 23:39:18 +00004865bool
Ted Kremenek02087932010-07-16 02:11:22 +00004866CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00004867 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00004868 const char *startSpecifier,
4869 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004870 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00004871 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004872 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00004873
Ted Kremenek6cd69422010-07-19 22:01:06 +00004874 if (FS.consumesDataArgument()) {
4875 if (atFirstArg) {
4876 atFirstArg = false;
4877 usesPositionalArgs = FS.usesPositionalArg();
4878 }
4879 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004880 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
4881 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00004882 return false;
4883 }
Ted Kremenek5739de72010-01-29 01:06:55 +00004884 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004885
Ted Kremenekd1668192010-02-27 01:41:03 +00004886 // First check if the field width, precision, and conversion specifier
4887 // have matching data arguments.
4888 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
4889 startSpecifier, specifierLen)) {
4890 return false;
4891 }
4892
4893 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
4894 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004895 return false;
4896 }
4897
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004898 if (!CS.consumesDataArgument()) {
4899 // FIXME: Technically specifying a precision or field width here
4900 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00004901 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004902 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004903
Ted Kremenek4a49d982010-02-26 19:18:41 +00004904 // Consume the argument.
4905 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00004906 if (argIndex < NumDataArgs) {
4907 // The check to see if the argIndex is valid will come later.
4908 // We set the bit here because we may exit early from this
4909 // function if we encounter some other error.
4910 CoveredArgs.set(argIndex);
4911 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00004912
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004913 // FreeBSD kernel extensions.
4914 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
4915 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
4916 // We need at least two arguments.
4917 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
4918 return false;
4919
4920 // Claim the second argument.
4921 CoveredArgs.set(argIndex + 1);
4922
4923 // Type check the first argument (int for %b, pointer for %D)
4924 const Expr *Ex = getDataArg(argIndex);
4925 const analyze_printf::ArgType &AT =
4926 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
4927 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
4928 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
4929 EmitFormatDiagnostic(
4930 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4931 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
4932 << false << Ex->getSourceRange(),
4933 Ex->getLocStart(), /*IsStringLocation*/false,
4934 getSpecifierRange(startSpecifier, specifierLen));
4935
4936 // Type check the second argument (char * for both %b and %D)
4937 Ex = getDataArg(argIndex + 1);
4938 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
4939 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
4940 EmitFormatDiagnostic(
4941 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4942 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
4943 << false << Ex->getSourceRange(),
4944 Ex->getLocStart(), /*IsStringLocation*/false,
4945 getSpecifierRange(startSpecifier, specifierLen));
4946
4947 return true;
4948 }
4949
Ted Kremenek4a49d982010-02-26 19:18:41 +00004950 // Check for using an Objective-C specific conversion specifier
4951 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004952 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00004953 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
4954 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00004955 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004956
Tom Careb49ec692010-06-17 19:00:27 +00004957 // Check for invalid use of field width
4958 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00004959 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00004960 startSpecifier, specifierLen);
4961 }
4962
4963 // Check for invalid use of precision
4964 if (!FS.hasValidPrecision()) {
4965 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
4966 startSpecifier, specifierLen);
4967 }
4968
4969 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00004970 if (!FS.hasValidThousandsGroupingPrefix())
4971 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004972 if (!FS.hasValidLeadingZeros())
4973 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
4974 if (!FS.hasValidPlusPrefix())
4975 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00004976 if (!FS.hasValidSpacePrefix())
4977 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004978 if (!FS.hasValidAlternativeForm())
4979 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
4980 if (!FS.hasValidLeftJustified())
4981 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
4982
4983 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00004984 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
4985 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
4986 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004987 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
4988 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
4989 startSpecifier, specifierLen);
4990
4991 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00004992 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00004993 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4994 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00004995 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004996 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00004997 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004998 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4999 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00005000
Jordan Rose92303592012-09-08 04:00:03 +00005001 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
5002 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5003
Ted Kremenek9fcd8302010-01-29 01:43:31 +00005004 // The remaining checks depend on the data arguments.
5005 if (HasVAListArg)
5006 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005007
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005008 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00005009 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005010
Jordan Rose58bbe422012-07-19 18:10:08 +00005011 const Expr *Arg = getDataArg(argIndex);
5012 if (!Arg)
5013 return true;
5014
5015 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00005016}
5017
Jordan Roseaee34382012-09-05 22:56:26 +00005018static bool requiresParensToAddCast(const Expr *E) {
5019 // FIXME: We should have a general way to reason about operator
5020 // precedence and whether parens are actually needed here.
5021 // Take care of a few common cases where they aren't.
5022 const Expr *Inside = E->IgnoreImpCasts();
5023 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
5024 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
5025
5026 switch (Inside->getStmtClass()) {
5027 case Stmt::ArraySubscriptExprClass:
5028 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005029 case Stmt::CharacterLiteralClass:
5030 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005031 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005032 case Stmt::FloatingLiteralClass:
5033 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005034 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005035 case Stmt::ObjCArrayLiteralClass:
5036 case Stmt::ObjCBoolLiteralExprClass:
5037 case Stmt::ObjCBoxedExprClass:
5038 case Stmt::ObjCDictionaryLiteralClass:
5039 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005040 case Stmt::ObjCIvarRefExprClass:
5041 case Stmt::ObjCMessageExprClass:
5042 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005043 case Stmt::ObjCStringLiteralClass:
5044 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005045 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005046 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005047 case Stmt::UnaryOperatorClass:
5048 return false;
5049 default:
5050 return true;
5051 }
5052}
5053
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005054static std::pair<QualType, StringRef>
5055shouldNotPrintDirectly(const ASTContext &Context,
5056 QualType IntendedTy,
5057 const Expr *E) {
5058 // Use a 'while' to peel off layers of typedefs.
5059 QualType TyTy = IntendedTy;
5060 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
5061 StringRef Name = UserTy->getDecl()->getName();
5062 QualType CastTy = llvm::StringSwitch<QualType>(Name)
5063 .Case("NSInteger", Context.LongTy)
5064 .Case("NSUInteger", Context.UnsignedLongTy)
5065 .Case("SInt32", Context.IntTy)
5066 .Case("UInt32", Context.UnsignedIntTy)
5067 .Default(QualType());
5068
5069 if (!CastTy.isNull())
5070 return std::make_pair(CastTy, Name);
5071
5072 TyTy = UserTy->desugar();
5073 }
5074
5075 // Strip parens if necessary.
5076 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
5077 return shouldNotPrintDirectly(Context,
5078 PE->getSubExpr()->getType(),
5079 PE->getSubExpr());
5080
5081 // If this is a conditional expression, then its result type is constructed
5082 // via usual arithmetic conversions and thus there might be no necessary
5083 // typedef sugar there. Recurse to operands to check for NSInteger &
5084 // Co. usage condition.
5085 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5086 QualType TrueTy, FalseTy;
5087 StringRef TrueName, FalseName;
5088
5089 std::tie(TrueTy, TrueName) =
5090 shouldNotPrintDirectly(Context,
5091 CO->getTrueExpr()->getType(),
5092 CO->getTrueExpr());
5093 std::tie(FalseTy, FalseName) =
5094 shouldNotPrintDirectly(Context,
5095 CO->getFalseExpr()->getType(),
5096 CO->getFalseExpr());
5097
5098 if (TrueTy == FalseTy)
5099 return std::make_pair(TrueTy, TrueName);
5100 else if (TrueTy.isNull())
5101 return std::make_pair(FalseTy, FalseName);
5102 else if (FalseTy.isNull())
5103 return std::make_pair(TrueTy, TrueName);
5104 }
5105
5106 return std::make_pair(QualType(), StringRef());
5107}
5108
Richard Smith55ce3522012-06-25 20:30:08 +00005109bool
5110CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5111 const char *StartSpecifier,
5112 unsigned SpecifierLen,
5113 const Expr *E) {
5114 using namespace analyze_format_string;
5115 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005116 // Now type check the data expression that matches the
5117 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005118 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
5119 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00005120 if (!AT.isValid())
5121 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00005122
Jordan Rose598ec092012-12-05 18:44:40 +00005123 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00005124 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
5125 ExprTy = TET->getUnderlyingExpr()->getType();
5126 }
5127
Seth Cantrellb4802962015-03-04 03:12:10 +00005128 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
5129
5130 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00005131 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00005132 }
Jordan Rose98709982012-06-04 22:48:57 +00005133
Jordan Rose22b74712012-09-05 22:56:19 +00005134 // Look through argument promotions for our error message's reported type.
5135 // This includes the integral and floating promotions, but excludes array
5136 // and function pointer decay; seeing that an argument intended to be a
5137 // string has type 'char [6]' is probably more confusing than 'char *'.
5138 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5139 if (ICE->getCastKind() == CK_IntegralCast ||
5140 ICE->getCastKind() == CK_FloatingCast) {
5141 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00005142 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00005143
5144 // Check if we didn't match because of an implicit cast from a 'char'
5145 // or 'short' to an 'int'. This is done because printf is a varargs
5146 // function.
5147 if (ICE->getType() == S.Context.IntTy ||
5148 ICE->getType() == S.Context.UnsignedIntTy) {
5149 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00005150 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00005151 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00005152 }
Jordan Rose98709982012-06-04 22:48:57 +00005153 }
Jordan Rose598ec092012-12-05 18:44:40 +00005154 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
5155 // Special case for 'a', which has type 'int' in C.
5156 // Note, however, that we do /not/ want to treat multibyte constants like
5157 // 'MooV' as characters! This form is deprecated but still exists.
5158 if (ExprTy == S.Context.IntTy)
5159 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
5160 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00005161 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005162
Jordan Rosebc53ed12014-05-31 04:12:14 +00005163 // Look through enums to their underlying type.
5164 bool IsEnum = false;
5165 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
5166 ExprTy = EnumTy->getDecl()->getIntegerType();
5167 IsEnum = true;
5168 }
5169
Jordan Rose0e5badd2012-12-05 18:44:49 +00005170 // %C in an Objective-C context prints a unichar, not a wchar_t.
5171 // If the argument is an integer of some kind, believe the %C and suggest
5172 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00005173 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00005174 if (ObjCContext &&
5175 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
5176 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
5177 !ExprTy->isCharType()) {
5178 // 'unichar' is defined as a typedef of unsigned short, but we should
5179 // prefer using the typedef if it is visible.
5180 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00005181
5182 // While we are here, check if the value is an IntegerLiteral that happens
5183 // to be within the valid range.
5184 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
5185 const llvm::APInt &V = IL->getValue();
5186 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
5187 return true;
5188 }
5189
Jordan Rose0e5badd2012-12-05 18:44:49 +00005190 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
5191 Sema::LookupOrdinaryName);
5192 if (S.LookupName(Result, S.getCurScope())) {
5193 NamedDecl *ND = Result.getFoundDecl();
5194 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
5195 if (TD->getUnderlyingType() == IntendedTy)
5196 IntendedTy = S.Context.getTypedefType(TD);
5197 }
5198 }
5199 }
5200
5201 // Special-case some of Darwin's platform-independence types by suggesting
5202 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005203 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00005204 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005205 QualType CastTy;
5206 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
5207 if (!CastTy.isNull()) {
5208 IntendedTy = CastTy;
5209 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00005210 }
5211 }
5212
Jordan Rose22b74712012-09-05 22:56:19 +00005213 // We may be able to offer a FixItHint if it is a supported type.
5214 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00005215 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00005216 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005217
Jordan Rose22b74712012-09-05 22:56:19 +00005218 if (success) {
5219 // Get the fix string from the fixed format specifier
5220 SmallString<16> buf;
5221 llvm::raw_svector_ostream os(buf);
5222 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005223
Jordan Roseaee34382012-09-05 22:56:26 +00005224 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
5225
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005226 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00005227 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5228 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
5229 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5230 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00005231 // In this case, the specifier is wrong and should be changed to match
5232 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00005233 EmitFormatDiagnostic(S.PDiag(diag)
5234 << AT.getRepresentativeTypeName(S.Context)
5235 << IntendedTy << IsEnum << E->getSourceRange(),
5236 E->getLocStart(),
5237 /*IsStringLocation*/ false, SpecRange,
5238 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00005239 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00005240 // The canonical type for formatting this value is different from the
5241 // actual type of the expression. (This occurs, for example, with Darwin's
5242 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
5243 // should be printed as 'long' for 64-bit compatibility.)
5244 // Rather than emitting a normal format/argument mismatch, we want to
5245 // add a cast to the recommended type (and correct the format string
5246 // if necessary).
5247 SmallString<16> CastBuf;
5248 llvm::raw_svector_ostream CastFix(CastBuf);
5249 CastFix << "(";
5250 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
5251 CastFix << ")";
5252
5253 SmallVector<FixItHint,4> Hints;
5254 if (!AT.matchesType(S.Context, IntendedTy))
5255 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
5256
5257 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
5258 // If there's already a cast present, just replace it.
5259 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
5260 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
5261
5262 } else if (!requiresParensToAddCast(E)) {
5263 // If the expression has high enough precedence,
5264 // just write the C-style cast.
5265 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
5266 CastFix.str()));
5267 } else {
5268 // Otherwise, add parens around the expression as well as the cast.
5269 CastFix << "(";
5270 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
5271 CastFix.str()));
5272
Alp Tokerb6cc5922014-05-03 03:45:55 +00005273 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00005274 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
5275 }
5276
Jordan Rose0e5badd2012-12-05 18:44:49 +00005277 if (ShouldNotPrintDirectly) {
5278 // The expression has a type that should not be printed directly.
5279 // We extract the name from the typedef because we don't want to show
5280 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005281 StringRef Name;
5282 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
5283 Name = TypedefTy->getDecl()->getName();
5284 else
5285 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00005286 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00005287 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00005288 << E->getSourceRange(),
5289 E->getLocStart(), /*IsStringLocation=*/false,
5290 SpecRange, Hints);
5291 } else {
5292 // In this case, the expression could be printed using a different
5293 // specifier, but we've decided that the specifier is probably correct
5294 // and we should cast instead. Just use the normal warning message.
5295 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00005296 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5297 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00005298 << E->getSourceRange(),
5299 E->getLocStart(), /*IsStringLocation*/false,
5300 SpecRange, Hints);
5301 }
Jordan Roseaee34382012-09-05 22:56:26 +00005302 }
Jordan Rose22b74712012-09-05 22:56:19 +00005303 } else {
5304 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
5305 SpecifierLen);
5306 // Since the warning for passing non-POD types to variadic functions
5307 // was deferred until now, we emit a warning for non-POD
5308 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00005309 switch (S.isValidVarArgType(ExprTy)) {
5310 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00005311 case Sema::VAK_ValidInCXX11: {
5312 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5313 if (match == analyze_printf::ArgType::NoMatchPedantic) {
5314 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5315 }
Richard Smithd7293d72013-08-05 18:49:43 +00005316
Seth Cantrellb4802962015-03-04 03:12:10 +00005317 EmitFormatDiagnostic(
5318 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
5319 << IsEnum << CSR << E->getSourceRange(),
5320 E->getLocStart(), /*IsStringLocation*/ false, CSR);
5321 break;
5322 }
Richard Smithd7293d72013-08-05 18:49:43 +00005323 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00005324 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00005325 EmitFormatDiagnostic(
5326 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005327 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00005328 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00005329 << CallType
5330 << AT.getRepresentativeTypeName(S.Context)
5331 << CSR
5332 << E->getSourceRange(),
5333 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00005334 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00005335 break;
5336
5337 case Sema::VAK_Invalid:
5338 if (ExprTy->isObjCObjectType())
5339 EmitFormatDiagnostic(
5340 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
5341 << S.getLangOpts().CPlusPlus11
5342 << ExprTy
5343 << CallType
5344 << AT.getRepresentativeTypeName(S.Context)
5345 << CSR
5346 << E->getSourceRange(),
5347 E->getLocStart(), /*IsStringLocation*/false, CSR);
5348 else
5349 // FIXME: If this is an initializer list, suggest removing the braces
5350 // or inserting a cast to the target type.
5351 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
5352 << isa<InitListExpr>(E) << ExprTy << CallType
5353 << AT.getRepresentativeTypeName(S.Context)
5354 << E->getSourceRange();
5355 break;
5356 }
5357
5358 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
5359 "format string specifier index out of range");
5360 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005361 }
5362
Ted Kremenekab278de2010-01-28 23:39:18 +00005363 return true;
5364}
5365
Ted Kremenek02087932010-07-16 02:11:22 +00005366//===--- CHECK: Scanf format string checking ------------------------------===//
5367
5368namespace {
5369class CheckScanfHandler : public CheckFormatHandler {
5370public:
5371 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
5372 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005373 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005374 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005375 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00005376 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005377 llvm::SmallBitVector &CheckedVarArgs,
5378 UncoveredArgHandler &UncoveredArg)
Richard Smithd7293d72013-08-05 18:49:43 +00005379 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
5380 numDataArgs, beg, hasVAListArg,
5381 Args, formatIdx, inFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005382 CheckedVarArgs, UncoveredArg)
Jordan Rose3e0ec582012-07-19 18:10:23 +00005383 {}
Ted Kremenek02087932010-07-16 02:11:22 +00005384
5385 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
5386 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005387 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00005388
5389 bool HandleInvalidScanfConversionSpecifier(
5390 const analyze_scanf::ScanfSpecifier &FS,
5391 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005392 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00005393
Craig Toppere14c0f82014-03-12 04:55:44 +00005394 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00005395};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005396} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00005397
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00005398void CheckScanfHandler::HandleIncompleteScanList(const char *start,
5399 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005400 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
5401 getLocationOfByte(end), /*IsStringLocation*/true,
5402 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00005403}
5404
Ted Kremenekce815422010-07-19 21:25:57 +00005405bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
5406 const analyze_scanf::ScanfSpecifier &FS,
5407 const char *startSpecifier,
5408 unsigned specifierLen) {
5409
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005410 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00005411 FS.getConversionSpecifier();
5412
5413 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5414 getLocationOfByte(CS.getStart()),
5415 startSpecifier, specifierLen,
5416 CS.getStart(), CS.getLength());
5417}
5418
Ted Kremenek02087932010-07-16 02:11:22 +00005419bool CheckScanfHandler::HandleScanfSpecifier(
5420 const analyze_scanf::ScanfSpecifier &FS,
5421 const char *startSpecifier,
5422 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00005423 using namespace analyze_scanf;
5424 using namespace analyze_format_string;
5425
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005426 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00005427
Ted Kremenek6cd69422010-07-19 22:01:06 +00005428 // Handle case where '%' and '*' don't consume an argument. These shouldn't
5429 // be used to decide if we are using positional arguments consistently.
5430 if (FS.consumesDataArgument()) {
5431 if (atFirstArg) {
5432 atFirstArg = false;
5433 usesPositionalArgs = FS.usesPositionalArg();
5434 }
5435 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005436 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5437 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00005438 return false;
5439 }
Ted Kremenek02087932010-07-16 02:11:22 +00005440 }
5441
5442 // Check if the field with is non-zero.
5443 const OptionalAmount &Amt = FS.getFieldWidth();
5444 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
5445 if (Amt.getConstantAmount() == 0) {
5446 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
5447 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00005448 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
5449 getLocationOfByte(Amt.getStart()),
5450 /*IsStringLocation*/true, R,
5451 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00005452 }
5453 }
Seth Cantrellb4802962015-03-04 03:12:10 +00005454
Ted Kremenek02087932010-07-16 02:11:22 +00005455 if (!FS.consumesDataArgument()) {
5456 // FIXME: Technically specifying a precision or field width here
5457 // makes no sense. Worth issuing a warning at some point.
5458 return true;
5459 }
Seth Cantrellb4802962015-03-04 03:12:10 +00005460
Ted Kremenek02087932010-07-16 02:11:22 +00005461 // Consume the argument.
5462 unsigned argIndex = FS.getArgIndex();
5463 if (argIndex < NumDataArgs) {
5464 // The check to see if the argIndex is valid will come later.
5465 // We set the bit here because we may exit early from this
5466 // function if we encounter some other error.
5467 CoveredArgs.set(argIndex);
5468 }
Seth Cantrellb4802962015-03-04 03:12:10 +00005469
Ted Kremenek4407ea42010-07-20 20:04:47 +00005470 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00005471 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00005472 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5473 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00005474 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005475 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00005476 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005477 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5478 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005479
Jordan Rose92303592012-09-08 04:00:03 +00005480 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
5481 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5482
Ted Kremenek02087932010-07-16 02:11:22 +00005483 // The remaining checks depend on the data arguments.
5484 if (HasVAListArg)
5485 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00005486
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005487 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00005488 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00005489
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005490 // Check that the argument type matches the format specifier.
5491 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00005492 if (!Ex)
5493 return true;
5494
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00005495 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00005496
5497 if (!AT.isValid()) {
5498 return true;
5499 }
5500
Seth Cantrellb4802962015-03-04 03:12:10 +00005501 analyze_format_string::ArgType::MatchKind match =
5502 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00005503 if (match == analyze_format_string::ArgType::Match) {
5504 return true;
5505 }
Seth Cantrellb4802962015-03-04 03:12:10 +00005506
Seth Cantrell79340072015-03-04 05:58:08 +00005507 ScanfSpecifier fixedFS = FS;
5508 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
5509 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005510
Seth Cantrell79340072015-03-04 05:58:08 +00005511 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5512 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
5513 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5514 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005515
Seth Cantrell79340072015-03-04 05:58:08 +00005516 if (success) {
5517 // Get the fix string from the fixed format specifier.
5518 SmallString<128> buf;
5519 llvm::raw_svector_ostream os(buf);
5520 fixedFS.toString(os);
5521
5522 EmitFormatDiagnostic(
5523 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
5524 << Ex->getType() << false << Ex->getSourceRange(),
5525 Ex->getLocStart(),
5526 /*IsStringLocation*/ false,
5527 getSpecifierRange(startSpecifier, specifierLen),
5528 FixItHint::CreateReplacement(
5529 getSpecifierRange(startSpecifier, specifierLen), os.str()));
5530 } else {
5531 EmitFormatDiagnostic(S.PDiag(diag)
5532 << AT.getRepresentativeTypeName(S.Context)
5533 << Ex->getType() << false << Ex->getSourceRange(),
5534 Ex->getLocStart(),
5535 /*IsStringLocation*/ false,
5536 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005537 }
5538
Ted Kremenek02087932010-07-16 02:11:22 +00005539 return true;
5540}
5541
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005542static void CheckFormatString(Sema &S, const StringLiteral *FExpr,
5543 const Expr *OrigFormatExpr,
5544 ArrayRef<const Expr *> Args,
5545 bool HasVAListArg, unsigned format_idx,
5546 unsigned firstDataArg,
5547 Sema::FormatStringType Type,
5548 bool inFunctionCall,
5549 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005550 llvm::SmallBitVector &CheckedVarArgs,
5551 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00005552 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00005553 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005554 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005555 S, inFunctionCall, Args[format_idx],
5556 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00005557 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00005558 return;
5559 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005560
Ted Kremenekab278de2010-01-28 23:39:18 +00005561 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005562 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00005563 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005564 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005565 const ConstantArrayType *T =
5566 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005567 assert(T && "String literal not of constant array type!");
5568 size_t TypeSize = T->getSize().getZExtValue();
5569 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005570 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005571
5572 // Emit a warning if the string literal is truncated and does not contain an
5573 // embedded null character.
5574 if (TypeSize <= StrRef.size() &&
5575 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
5576 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005577 S, inFunctionCall, Args[format_idx],
5578 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005579 FExpr->getLocStart(),
5580 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
5581 return;
5582 }
5583
Ted Kremenekab278de2010-01-28 23:39:18 +00005584 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00005585 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005586 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005587 S, inFunctionCall, Args[format_idx],
5588 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00005589 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00005590 return;
5591 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005592
5593 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
5594 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSTrace) {
5595 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, firstDataArg,
5596 numDataArgs, (Type == Sema::FST_NSString ||
5597 Type == Sema::FST_OSTrace),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005598 Str, HasVAListArg, Args, format_idx,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005599 inFunctionCall, CallType, CheckedVarArgs,
5600 UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005601
Hans Wennborg23926bd2011-12-15 10:25:47 +00005602 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005603 S.getLangOpts(),
5604 S.Context.getTargetInfo(),
5605 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00005606 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005607 } else if (Type == Sema::FST_Scanf) {
5608 CheckScanfHandler H(S, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005609 Str, HasVAListArg, Args, format_idx,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005610 inFunctionCall, CallType, CheckedVarArgs,
5611 UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005612
Hans Wennborg23926bd2011-12-15 10:25:47 +00005613 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005614 S.getLangOpts(),
5615 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00005616 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005617 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00005618}
5619
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00005620bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
5621 // Str - The format string. NOTE: this is NOT null-terminated!
5622 StringRef StrRef = FExpr->getString();
5623 const char *Str = StrRef.data();
5624 // Account for cases where the string literal is truncated in a declaration.
5625 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
5626 assert(T && "String literal not of constant array type!");
5627 size_t TypeSize = T->getSize().getZExtValue();
5628 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
5629 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
5630 getLangOpts(),
5631 Context.getTargetInfo());
5632}
5633
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005634//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
5635
5636// Returns the related absolute value function that is larger, of 0 if one
5637// does not exist.
5638static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
5639 switch (AbsFunction) {
5640 default:
5641 return 0;
5642
5643 case Builtin::BI__builtin_abs:
5644 return Builtin::BI__builtin_labs;
5645 case Builtin::BI__builtin_labs:
5646 return Builtin::BI__builtin_llabs;
5647 case Builtin::BI__builtin_llabs:
5648 return 0;
5649
5650 case Builtin::BI__builtin_fabsf:
5651 return Builtin::BI__builtin_fabs;
5652 case Builtin::BI__builtin_fabs:
5653 return Builtin::BI__builtin_fabsl;
5654 case Builtin::BI__builtin_fabsl:
5655 return 0;
5656
5657 case Builtin::BI__builtin_cabsf:
5658 return Builtin::BI__builtin_cabs;
5659 case Builtin::BI__builtin_cabs:
5660 return Builtin::BI__builtin_cabsl;
5661 case Builtin::BI__builtin_cabsl:
5662 return 0;
5663
5664 case Builtin::BIabs:
5665 return Builtin::BIlabs;
5666 case Builtin::BIlabs:
5667 return Builtin::BIllabs;
5668 case Builtin::BIllabs:
5669 return 0;
5670
5671 case Builtin::BIfabsf:
5672 return Builtin::BIfabs;
5673 case Builtin::BIfabs:
5674 return Builtin::BIfabsl;
5675 case Builtin::BIfabsl:
5676 return 0;
5677
5678 case Builtin::BIcabsf:
5679 return Builtin::BIcabs;
5680 case Builtin::BIcabs:
5681 return Builtin::BIcabsl;
5682 case Builtin::BIcabsl:
5683 return 0;
5684 }
5685}
5686
5687// Returns the argument type of the absolute value function.
5688static QualType getAbsoluteValueArgumentType(ASTContext &Context,
5689 unsigned AbsType) {
5690 if (AbsType == 0)
5691 return QualType();
5692
5693 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
5694 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
5695 if (Error != ASTContext::GE_None)
5696 return QualType();
5697
5698 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
5699 if (!FT)
5700 return QualType();
5701
5702 if (FT->getNumParams() != 1)
5703 return QualType();
5704
5705 return FT->getParamType(0);
5706}
5707
5708// Returns the best absolute value function, or zero, based on type and
5709// current absolute value function.
5710static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
5711 unsigned AbsFunctionKind) {
5712 unsigned BestKind = 0;
5713 uint64_t ArgSize = Context.getTypeSize(ArgType);
5714 for (unsigned Kind = AbsFunctionKind; Kind != 0;
5715 Kind = getLargerAbsoluteValueFunction(Kind)) {
5716 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
5717 if (Context.getTypeSize(ParamType) >= ArgSize) {
5718 if (BestKind == 0)
5719 BestKind = Kind;
5720 else if (Context.hasSameType(ParamType, ArgType)) {
5721 BestKind = Kind;
5722 break;
5723 }
5724 }
5725 }
5726 return BestKind;
5727}
5728
5729enum AbsoluteValueKind {
5730 AVK_Integer,
5731 AVK_Floating,
5732 AVK_Complex
5733};
5734
5735static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
5736 if (T->isIntegralOrEnumerationType())
5737 return AVK_Integer;
5738 if (T->isRealFloatingType())
5739 return AVK_Floating;
5740 if (T->isAnyComplexType())
5741 return AVK_Complex;
5742
5743 llvm_unreachable("Type not integer, floating, or complex");
5744}
5745
5746// Changes the absolute value function to a different type. Preserves whether
5747// the function is a builtin.
5748static unsigned changeAbsFunction(unsigned AbsKind,
5749 AbsoluteValueKind ValueKind) {
5750 switch (ValueKind) {
5751 case AVK_Integer:
5752 switch (AbsKind) {
5753 default:
5754 return 0;
5755 case Builtin::BI__builtin_fabsf:
5756 case Builtin::BI__builtin_fabs:
5757 case Builtin::BI__builtin_fabsl:
5758 case Builtin::BI__builtin_cabsf:
5759 case Builtin::BI__builtin_cabs:
5760 case Builtin::BI__builtin_cabsl:
5761 return Builtin::BI__builtin_abs;
5762 case Builtin::BIfabsf:
5763 case Builtin::BIfabs:
5764 case Builtin::BIfabsl:
5765 case Builtin::BIcabsf:
5766 case Builtin::BIcabs:
5767 case Builtin::BIcabsl:
5768 return Builtin::BIabs;
5769 }
5770 case AVK_Floating:
5771 switch (AbsKind) {
5772 default:
5773 return 0;
5774 case Builtin::BI__builtin_abs:
5775 case Builtin::BI__builtin_labs:
5776 case Builtin::BI__builtin_llabs:
5777 case Builtin::BI__builtin_cabsf:
5778 case Builtin::BI__builtin_cabs:
5779 case Builtin::BI__builtin_cabsl:
5780 return Builtin::BI__builtin_fabsf;
5781 case Builtin::BIabs:
5782 case Builtin::BIlabs:
5783 case Builtin::BIllabs:
5784 case Builtin::BIcabsf:
5785 case Builtin::BIcabs:
5786 case Builtin::BIcabsl:
5787 return Builtin::BIfabsf;
5788 }
5789 case AVK_Complex:
5790 switch (AbsKind) {
5791 default:
5792 return 0;
5793 case Builtin::BI__builtin_abs:
5794 case Builtin::BI__builtin_labs:
5795 case Builtin::BI__builtin_llabs:
5796 case Builtin::BI__builtin_fabsf:
5797 case Builtin::BI__builtin_fabs:
5798 case Builtin::BI__builtin_fabsl:
5799 return Builtin::BI__builtin_cabsf;
5800 case Builtin::BIabs:
5801 case Builtin::BIlabs:
5802 case Builtin::BIllabs:
5803 case Builtin::BIfabsf:
5804 case Builtin::BIfabs:
5805 case Builtin::BIfabsl:
5806 return Builtin::BIcabsf;
5807 }
5808 }
5809 llvm_unreachable("Unable to convert function");
5810}
5811
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00005812static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005813 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
5814 if (!FnInfo)
5815 return 0;
5816
5817 switch (FDecl->getBuiltinID()) {
5818 default:
5819 return 0;
5820 case Builtin::BI__builtin_abs:
5821 case Builtin::BI__builtin_fabs:
5822 case Builtin::BI__builtin_fabsf:
5823 case Builtin::BI__builtin_fabsl:
5824 case Builtin::BI__builtin_labs:
5825 case Builtin::BI__builtin_llabs:
5826 case Builtin::BI__builtin_cabs:
5827 case Builtin::BI__builtin_cabsf:
5828 case Builtin::BI__builtin_cabsl:
5829 case Builtin::BIabs:
5830 case Builtin::BIlabs:
5831 case Builtin::BIllabs:
5832 case Builtin::BIfabs:
5833 case Builtin::BIfabsf:
5834 case Builtin::BIfabsl:
5835 case Builtin::BIcabs:
5836 case Builtin::BIcabsf:
5837 case Builtin::BIcabsl:
5838 return FDecl->getBuiltinID();
5839 }
5840 llvm_unreachable("Unknown Builtin type");
5841}
5842
5843// If the replacement is valid, emit a note with replacement function.
5844// Additionally, suggest including the proper header if not already included.
5845static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00005846 unsigned AbsKind, QualType ArgType) {
5847 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00005848 const char *HeaderName = nullptr;
5849 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00005850 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
5851 FunctionName = "std::abs";
5852 if (ArgType->isIntegralOrEnumerationType()) {
5853 HeaderName = "cstdlib";
5854 } else if (ArgType->isRealFloatingType()) {
5855 HeaderName = "cmath";
5856 } else {
5857 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005858 }
Richard Trieubeffb832014-04-15 23:47:53 +00005859
5860 // Lookup all std::abs
5861 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00005862 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00005863 R.suppressDiagnostics();
5864 S.LookupQualifiedName(R, Std);
5865
5866 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005867 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00005868 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
5869 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
5870 } else {
5871 FDecl = dyn_cast<FunctionDecl>(I);
5872 }
5873 if (!FDecl)
5874 continue;
5875
5876 // Found std::abs(), check that they are the right ones.
5877 if (FDecl->getNumParams() != 1)
5878 continue;
5879
5880 // Check that the parameter type can handle the argument.
5881 QualType ParamType = FDecl->getParamDecl(0)->getType();
5882 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
5883 S.Context.getTypeSize(ArgType) <=
5884 S.Context.getTypeSize(ParamType)) {
5885 // Found a function, don't need the header hint.
5886 EmitHeaderHint = false;
5887 break;
5888 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005889 }
Richard Trieubeffb832014-04-15 23:47:53 +00005890 }
5891 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00005892 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00005893 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
5894
5895 if (HeaderName) {
5896 DeclarationName DN(&S.Context.Idents.get(FunctionName));
5897 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
5898 R.suppressDiagnostics();
5899 S.LookupName(R, S.getCurScope());
5900
5901 if (R.isSingleResult()) {
5902 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
5903 if (FD && FD->getBuiltinID() == AbsKind) {
5904 EmitHeaderHint = false;
5905 } else {
5906 return;
5907 }
5908 } else if (!R.empty()) {
5909 return;
5910 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005911 }
5912 }
5913
5914 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00005915 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005916
Richard Trieubeffb832014-04-15 23:47:53 +00005917 if (!HeaderName)
5918 return;
5919
5920 if (!EmitHeaderHint)
5921 return;
5922
Alp Toker5d96e0a2014-07-11 20:53:51 +00005923 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
5924 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00005925}
5926
5927static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
5928 if (!FDecl)
5929 return false;
5930
5931 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
5932 return false;
5933
5934 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
5935
5936 while (ND && ND->isInlineNamespace()) {
5937 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005938 }
Richard Trieubeffb832014-04-15 23:47:53 +00005939
5940 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
5941 return false;
5942
5943 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
5944 return false;
5945
5946 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005947}
5948
5949// Warn when using the wrong abs() function.
5950void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
5951 const FunctionDecl *FDecl,
5952 IdentifierInfo *FnInfo) {
5953 if (Call->getNumArgs() != 1)
5954 return;
5955
5956 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00005957 bool IsStdAbs = IsFunctionStdAbs(FDecl);
5958 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005959 return;
5960
5961 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
5962 QualType ParamType = Call->getArg(0)->getType();
5963
Alp Toker5d96e0a2014-07-11 20:53:51 +00005964 // Unsigned types cannot be negative. Suggest removing the absolute value
5965 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005966 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00005967 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00005968 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005969 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
5970 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00005971 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005972 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
5973 return;
5974 }
5975
David Majnemer7f77eb92015-11-15 03:04:34 +00005976 // Taking the absolute value of a pointer is very suspicious, they probably
5977 // wanted to index into an array, dereference a pointer, call a function, etc.
5978 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
5979 unsigned DiagType = 0;
5980 if (ArgType->isFunctionType())
5981 DiagType = 1;
5982 else if (ArgType->isArrayType())
5983 DiagType = 2;
5984
5985 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
5986 return;
5987 }
5988
Richard Trieubeffb832014-04-15 23:47:53 +00005989 // std::abs has overloads which prevent most of the absolute value problems
5990 // from occurring.
5991 if (IsStdAbs)
5992 return;
5993
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005994 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
5995 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
5996
5997 // The argument and parameter are the same kind. Check if they are the right
5998 // size.
5999 if (ArgValueKind == ParamValueKind) {
6000 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
6001 return;
6002
6003 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
6004 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
6005 << FDecl << ArgType << ParamType;
6006
6007 if (NewAbsKind == 0)
6008 return;
6009
6010 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00006011 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006012 return;
6013 }
6014
6015 // ArgValueKind != ParamValueKind
6016 // The wrong type of absolute value function was used. Attempt to find the
6017 // proper one.
6018 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
6019 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
6020 if (NewAbsKind == 0)
6021 return;
6022
6023 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
6024 << FDecl << ParamValueKind << ArgValueKind;
6025
6026 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00006027 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006028}
6029
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006030//===--- CHECK: Standard memory functions ---------------------------------===//
6031
Nico Weber0e6daef2013-12-26 23:38:39 +00006032/// \brief Takes the expression passed to the size_t parameter of functions
6033/// such as memcmp, strncat, etc and warns if it's a comparison.
6034///
6035/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
6036static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
6037 IdentifierInfo *FnName,
6038 SourceLocation FnLoc,
6039 SourceLocation RParenLoc) {
6040 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
6041 if (!Size)
6042 return false;
6043
6044 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
6045 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
6046 return false;
6047
Nico Weber0e6daef2013-12-26 23:38:39 +00006048 SourceRange SizeRange = Size->getSourceRange();
6049 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
6050 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00006051 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00006052 << FnName << FixItHint::CreateInsertion(
6053 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00006054 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00006055 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00006056 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00006057 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
6058 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00006059
6060 return true;
6061}
6062
Reid Kleckner5fb5b122014-06-27 23:58:21 +00006063/// \brief Determine whether the given type is or contains a dynamic class type
6064/// (e.g., whether it has a vtable).
6065static const CXXRecordDecl *getContainedDynamicClass(QualType T,
6066 bool &IsContained) {
6067 // Look through array types while ignoring qualifiers.
6068 const Type *Ty = T->getBaseElementTypeUnsafe();
6069 IsContained = false;
6070
6071 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
6072 RD = RD ? RD->getDefinition() : nullptr;
Richard Trieu1c7237a2016-03-31 04:18:07 +00006073 if (!RD || RD->isInvalidDecl())
Reid Kleckner5fb5b122014-06-27 23:58:21 +00006074 return nullptr;
6075
6076 if (RD->isDynamicClass())
6077 return RD;
6078
6079 // Check all the fields. If any bases were dynamic, the class is dynamic.
6080 // It's impossible for a class to transitively contain itself by value, so
6081 // infinite recursion is impossible.
6082 for (auto *FD : RD->fields()) {
6083 bool SubContained;
6084 if (const CXXRecordDecl *ContainedRD =
6085 getContainedDynamicClass(FD->getType(), SubContained)) {
6086 IsContained = true;
6087 return ContainedRD;
6088 }
6089 }
6090
6091 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00006092}
6093
Chandler Carruth889ed862011-06-21 23:04:20 +00006094/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006095/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00006096static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00006097 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006098 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6099 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
6100 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00006101
Craig Topperc3ec1492014-05-26 06:22:03 +00006102 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006103}
6104
Chandler Carruth889ed862011-06-21 23:04:20 +00006105/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00006106static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006107 if (const UnaryExprOrTypeTraitExpr *SizeOf =
6108 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6109 if (SizeOf->getKind() == clang::UETT_SizeOf)
6110 return SizeOf->getTypeOfArgument();
6111
6112 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00006113}
6114
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006115/// \brief Check for dangerous or invalid arguments to memset().
6116///
Chandler Carruthac687262011-06-03 06:23:57 +00006117/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00006118/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
6119/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006120///
6121/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00006122void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00006123 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00006124 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00006125 assert(BId != 0);
6126
Ted Kremenekb5fabb22011-04-28 01:38:02 +00006127 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00006128 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00006129 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00006130 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00006131 return;
6132
Anna Zaks22122702012-01-17 00:37:07 +00006133 unsigned LastArg = (BId == Builtin::BImemset ||
6134 BId == Builtin::BIstrndup ? 1 : 2);
6135 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00006136 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006137
Nico Weber0e6daef2013-12-26 23:38:39 +00006138 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
6139 Call->getLocStart(), Call->getRParenLoc()))
6140 return;
6141
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006142 // We have special checking when the length is a sizeof expression.
6143 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
6144 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
6145 llvm::FoldingSetNodeID SizeOfArgID;
6146
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006147 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
6148 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00006149 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006150
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006151 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00006152 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006153 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00006154 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00006155
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006156 // Never warn about void type pointers. This can be used to suppress
6157 // false positives.
6158 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006159 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006160
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006161 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
6162 // actually comparing the expressions for equality. Because computing the
6163 // expression IDs can be expensive, we only do this if the diagnostic is
6164 // enabled.
6165 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006166 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
6167 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006168 // We only compute IDs for expressions if the warning is enabled, and
6169 // cache the sizeof arg's ID.
6170 if (SizeOfArgID == llvm::FoldingSetNodeID())
6171 SizeOfArg->Profile(SizeOfArgID, Context, true);
6172 llvm::FoldingSetNodeID DestID;
6173 Dest->Profile(DestID, Context, true);
6174 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00006175 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
6176 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006177 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00006178 StringRef ReadableName = FnName->getName();
6179
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006180 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00006181 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006182 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00006183 if (!PointeeTy->isIncompleteType() &&
6184 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006185 ActionIdx = 2; // If the pointee's size is sizeof(char),
6186 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00006187
6188 // If the function is defined as a builtin macro, do not show macro
6189 // expansion.
6190 SourceLocation SL = SizeOfArg->getExprLoc();
6191 SourceRange DSR = Dest->getSourceRange();
6192 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00006193 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00006194
6195 if (SM.isMacroArgExpansion(SL)) {
6196 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
6197 SL = SM.getSpellingLoc(SL);
6198 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
6199 SM.getSpellingLoc(DSR.getEnd()));
6200 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
6201 SM.getSpellingLoc(SSR.getEnd()));
6202 }
6203
Anna Zaksd08d9152012-05-30 23:14:52 +00006204 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006205 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00006206 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00006207 << PointeeTy
6208 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00006209 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00006210 << SSR);
6211 DiagRuntimeBehavior(SL, SizeOfArg,
6212 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
6213 << ActionIdx
6214 << SSR);
6215
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006216 break;
6217 }
6218 }
6219
6220 // Also check for cases where the sizeof argument is the exact same
6221 // type as the memory argument, and where it points to a user-defined
6222 // record type.
6223 if (SizeOfArgTy != QualType()) {
6224 if (PointeeTy->isRecordType() &&
6225 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
6226 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
6227 PDiag(diag::warn_sizeof_pointer_type_memaccess)
6228 << FnName << SizeOfArgTy << ArgIdx
6229 << PointeeTy << Dest->getSourceRange()
6230 << LenExpr->getSourceRange());
6231 break;
6232 }
Nico Weberc5e73862011-06-14 16:14:58 +00006233 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00006234 } else if (DestTy->isArrayType()) {
6235 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00006236 }
Nico Weberc5e73862011-06-14 16:14:58 +00006237
Nico Weberc44b35e2015-03-21 17:37:46 +00006238 if (PointeeTy == QualType())
6239 continue;
Anna Zaks22122702012-01-17 00:37:07 +00006240
Nico Weberc44b35e2015-03-21 17:37:46 +00006241 // Always complain about dynamic classes.
6242 bool IsContained;
6243 if (const CXXRecordDecl *ContainedRD =
6244 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00006245
Nico Weberc44b35e2015-03-21 17:37:46 +00006246 unsigned OperationType = 0;
6247 // "overwritten" if we're warning about the destination for any call
6248 // but memcmp; otherwise a verb appropriate to the call.
6249 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
6250 if (BId == Builtin::BImemcpy)
6251 OperationType = 1;
6252 else if(BId == Builtin::BImemmove)
6253 OperationType = 2;
6254 else if (BId == Builtin::BImemcmp)
6255 OperationType = 3;
6256 }
6257
John McCall31168b02011-06-15 23:02:42 +00006258 DiagRuntimeBehavior(
6259 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00006260 PDiag(diag::warn_dyn_class_memaccess)
6261 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
6262 << FnName << IsContained << ContainedRD << OperationType
6263 << Call->getCallee()->getSourceRange());
6264 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
6265 BId != Builtin::BImemset)
6266 DiagRuntimeBehavior(
6267 Dest->getExprLoc(), Dest,
6268 PDiag(diag::warn_arc_object_memaccess)
6269 << ArgIdx << FnName << PointeeTy
6270 << Call->getCallee()->getSourceRange());
6271 else
6272 continue;
6273
6274 DiagRuntimeBehavior(
6275 Dest->getExprLoc(), Dest,
6276 PDiag(diag::note_bad_memaccess_silence)
6277 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
6278 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006279 }
6280}
6281
Ted Kremenek6865f772011-08-18 20:55:45 +00006282// A little helper routine: ignore addition and subtraction of integer literals.
6283// This intentionally does not ignore all integer constant expressions because
6284// we don't want to remove sizeof().
6285static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
6286 Ex = Ex->IgnoreParenCasts();
6287
6288 for (;;) {
6289 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
6290 if (!BO || !BO->isAdditiveOp())
6291 break;
6292
6293 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
6294 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
6295
6296 if (isa<IntegerLiteral>(RHS))
6297 Ex = LHS;
6298 else if (isa<IntegerLiteral>(LHS))
6299 Ex = RHS;
6300 else
6301 break;
6302 }
6303
6304 return Ex;
6305}
6306
Anna Zaks13b08572012-08-08 21:42:23 +00006307static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
6308 ASTContext &Context) {
6309 // Only handle constant-sized or VLAs, but not flexible members.
6310 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
6311 // Only issue the FIXIT for arrays of size > 1.
6312 if (CAT->getSize().getSExtValue() <= 1)
6313 return false;
6314 } else if (!Ty->isVariableArrayType()) {
6315 return false;
6316 }
6317 return true;
6318}
6319
Ted Kremenek6865f772011-08-18 20:55:45 +00006320// Warn if the user has made the 'size' argument to strlcpy or strlcat
6321// be the size of the source, instead of the destination.
6322void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
6323 IdentifierInfo *FnName) {
6324
6325 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00006326 unsigned NumArgs = Call->getNumArgs();
6327 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00006328 return;
6329
6330 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
6331 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00006332 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00006333
6334 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
6335 Call->getLocStart(), Call->getRParenLoc()))
6336 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00006337
6338 // Look for 'strlcpy(dst, x, sizeof(x))'
6339 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
6340 CompareWithSrc = Ex;
6341 else {
6342 // Look for 'strlcpy(dst, x, strlen(x))'
6343 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00006344 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
6345 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00006346 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
6347 }
6348 }
6349
6350 if (!CompareWithSrc)
6351 return;
6352
6353 // Determine if the argument to sizeof/strlen is equal to the source
6354 // argument. In principle there's all kinds of things you could do
6355 // here, for instance creating an == expression and evaluating it with
6356 // EvaluateAsBooleanCondition, but this uses a more direct technique:
6357 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
6358 if (!SrcArgDRE)
6359 return;
6360
6361 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
6362 if (!CompareWithSrcDRE ||
6363 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
6364 return;
6365
6366 const Expr *OriginalSizeArg = Call->getArg(2);
6367 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
6368 << OriginalSizeArg->getSourceRange() << FnName;
6369
6370 // Output a FIXIT hint if the destination is an array (rather than a
6371 // pointer to an array). This could be enhanced to handle some
6372 // pointers if we know the actual size, like if DstArg is 'array+2'
6373 // we could say 'sizeof(array)-2'.
6374 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00006375 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00006376 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00006377
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00006378 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00006379 llvm::raw_svector_ostream OS(sizeString);
6380 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00006381 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00006382 OS << ")";
6383
6384 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
6385 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
6386 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00006387}
6388
Anna Zaks314cd092012-02-01 19:08:57 +00006389/// Check if two expressions refer to the same declaration.
6390static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
6391 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
6392 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
6393 return D1->getDecl() == D2->getDecl();
6394 return false;
6395}
6396
6397static const Expr *getStrlenExprArg(const Expr *E) {
6398 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6399 const FunctionDecl *FD = CE->getDirectCallee();
6400 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00006401 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00006402 return CE->getArg(0)->IgnoreParenCasts();
6403 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006404 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00006405}
6406
6407// Warn on anti-patterns as the 'size' argument to strncat.
6408// The correct size argument should look like following:
6409// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
6410void Sema::CheckStrncatArguments(const CallExpr *CE,
6411 IdentifierInfo *FnName) {
6412 // Don't crash if the user has the wrong number of arguments.
6413 if (CE->getNumArgs() < 3)
6414 return;
6415 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
6416 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
6417 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
6418
Nico Weber0e6daef2013-12-26 23:38:39 +00006419 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
6420 CE->getRParenLoc()))
6421 return;
6422
Anna Zaks314cd092012-02-01 19:08:57 +00006423 // Identify common expressions, which are wrongly used as the size argument
6424 // to strncat and may lead to buffer overflows.
6425 unsigned PatternType = 0;
6426 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
6427 // - sizeof(dst)
6428 if (referToTheSameDecl(SizeOfArg, DstArg))
6429 PatternType = 1;
6430 // - sizeof(src)
6431 else if (referToTheSameDecl(SizeOfArg, SrcArg))
6432 PatternType = 2;
6433 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
6434 if (BE->getOpcode() == BO_Sub) {
6435 const Expr *L = BE->getLHS()->IgnoreParenCasts();
6436 const Expr *R = BE->getRHS()->IgnoreParenCasts();
6437 // - sizeof(dst) - strlen(dst)
6438 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
6439 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
6440 PatternType = 1;
6441 // - sizeof(src) - (anything)
6442 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
6443 PatternType = 2;
6444 }
6445 }
6446
6447 if (PatternType == 0)
6448 return;
6449
Anna Zaks5069aa32012-02-03 01:27:37 +00006450 // Generate the diagnostic.
6451 SourceLocation SL = LenArg->getLocStart();
6452 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00006453 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00006454
6455 // If the function is defined as a builtin macro, do not show macro expansion.
6456 if (SM.isMacroArgExpansion(SL)) {
6457 SL = SM.getSpellingLoc(SL);
6458 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
6459 SM.getSpellingLoc(SR.getEnd()));
6460 }
6461
Anna Zaks13b08572012-08-08 21:42:23 +00006462 // Check if the destination is an array (rather than a pointer to an array).
6463 QualType DstTy = DstArg->getType();
6464 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
6465 Context);
6466 if (!isKnownSizeArray) {
6467 if (PatternType == 1)
6468 Diag(SL, diag::warn_strncat_wrong_size) << SR;
6469 else
6470 Diag(SL, diag::warn_strncat_src_size) << SR;
6471 return;
6472 }
6473
Anna Zaks314cd092012-02-01 19:08:57 +00006474 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00006475 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00006476 else
Anna Zaks5069aa32012-02-03 01:27:37 +00006477 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00006478
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00006479 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00006480 llvm::raw_svector_ostream OS(sizeString);
6481 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00006482 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00006483 OS << ") - ";
6484 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00006485 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00006486 OS << ") - 1";
6487
Anna Zaks5069aa32012-02-03 01:27:37 +00006488 Diag(SL, diag::note_strncat_wrong_size)
6489 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00006490}
6491
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006492//===--- CHECK: Return Address of Stack Variable --------------------------===//
6493
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006494static const Expr *EvalVal(const Expr *E,
6495 SmallVectorImpl<const DeclRefExpr *> &refVars,
6496 const Decl *ParentDecl);
6497static const Expr *EvalAddr(const Expr *E,
6498 SmallVectorImpl<const DeclRefExpr *> &refVars,
6499 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006500
6501/// CheckReturnStackAddr - Check if a return statement returns the address
6502/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006503static void
6504CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
6505 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00006506
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006507 const Expr *stackE = nullptr;
6508 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006509
6510 // Perform checking for returned stack addresses, local blocks,
6511 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00006512 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006513 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006514 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00006515 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006516 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006517 }
6518
Craig Topperc3ec1492014-05-26 06:22:03 +00006519 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006520 return; // Nothing suspicious was found.
6521
6522 SourceLocation diagLoc;
6523 SourceRange diagRange;
6524 if (refVars.empty()) {
6525 diagLoc = stackE->getLocStart();
6526 diagRange = stackE->getSourceRange();
6527 } else {
6528 // We followed through a reference variable. 'stackE' contains the
6529 // problematic expression but we will warn at the return statement pointing
6530 // at the reference variable. We will later display the "trail" of
6531 // reference variables using notes.
6532 diagLoc = refVars[0]->getLocStart();
6533 diagRange = refVars[0]->getSourceRange();
6534 }
6535
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006536 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
6537 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00006538 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006539 << DR->getDecl()->getDeclName() << diagRange;
6540 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006541 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006542 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006543 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006544 } else { // local temporary.
Craig Topperda7b27f2015-11-17 05:40:09 +00006545 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
6546 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006547 }
6548
6549 // Display the "trail" of reference variables that we followed until we
6550 // found the problematic expression using notes.
6551 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006552 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006553 // If this var binds to another reference var, show the range of the next
6554 // var, otherwise the var binds to the problematic expression, in which case
6555 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006556 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
6557 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006558 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
6559 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006560 }
6561}
6562
6563/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
6564/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006565/// to a location on the stack, a local block, an address of a label, or a
6566/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006567/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006568/// encounter a subexpression that (1) clearly does not lead to one of the
6569/// above problematic expressions (2) is something we cannot determine leads to
6570/// a problematic expression based on such local checking.
6571///
6572/// Both EvalAddr and EvalVal follow through reference variables to evaluate
6573/// the expression that they point to. Such variables are added to the
6574/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006575///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00006576/// EvalAddr processes expressions that are pointers that are used as
6577/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006578/// At the base case of the recursion is a check for the above problematic
6579/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006580///
6581/// This implementation handles:
6582///
6583/// * pointer-to-pointer casts
6584/// * implicit conversions from array references to pointers
6585/// * taking the address of fields
6586/// * arbitrary interplay between "&" and "*" operators
6587/// * pointer arithmetic from an address of a stack variable
6588/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006589static const Expr *EvalAddr(const Expr *E,
6590 SmallVectorImpl<const DeclRefExpr *> &refVars,
6591 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006592 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00006593 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006594
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006595 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00006596 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00006597 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006598 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00006599 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00006600
Peter Collingbourne91147592011-04-15 00:35:48 +00006601 E = E->IgnoreParens();
6602
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006603 // Our "symbolic interpreter" is just a dispatch off the currently
6604 // viewed AST node. We then recursively traverse the AST by calling
6605 // EvalAddr and EvalVal appropriately.
6606 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006607 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006608 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006609
Richard Smith40f08eb2014-01-30 22:05:38 +00006610 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00006611 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00006612 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00006613
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006614 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006615 // If this is a reference variable, follow through to the expression that
6616 // it points to.
6617 if (V->hasLocalStorage() &&
6618 V->getType()->isReferenceType() && V->hasInit()) {
6619 // Add the reference variable to the "trail".
6620 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006621 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006622 }
6623
Craig Topperc3ec1492014-05-26 06:22:03 +00006624 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006625 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006626
Chris Lattner934edb22007-12-28 05:31:15 +00006627 case Stmt::UnaryOperatorClass: {
6628 // The only unary operator that make sense to handle here
6629 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006630 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006631
John McCalle3027922010-08-25 11:45:40 +00006632 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006633 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006634 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006635 }
Mike Stump11289f42009-09-09 15:08:12 +00006636
Chris Lattner934edb22007-12-28 05:31:15 +00006637 case Stmt::BinaryOperatorClass: {
6638 // Handle pointer arithmetic. All other binary operators are not valid
6639 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006640 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00006641 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00006642
John McCalle3027922010-08-25 11:45:40 +00006643 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00006644 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006645
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006646 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00006647
6648 // Determine which argument is the real pointer base. It could be
6649 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006650 if (!Base->getType()->isPointerType())
6651 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00006652
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006653 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006654 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00006655 }
Steve Naroff2752a172008-09-10 19:17:48 +00006656
Chris Lattner934edb22007-12-28 05:31:15 +00006657 // For conditional operators we need to see if either the LHS or RHS are
6658 // valid DeclRefExpr*s. If one of them is valid, we return it.
6659 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006660 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006661
Chris Lattner934edb22007-12-28 05:31:15 +00006662 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006663 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006664 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006665 // In C++, we can have a throw-expression, which has 'void' type.
6666 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006667 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006668 return LHS;
6669 }
Chris Lattner934edb22007-12-28 05:31:15 +00006670
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006671 // In C++, we can have a throw-expression, which has 'void' type.
6672 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00006673 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006674
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006675 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00006676 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006677
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006678 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00006679 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006680 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00006681 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006682
6683 case Stmt::AddrLabelExprClass:
6684 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00006685
John McCall28fc7092011-11-10 05:35:25 +00006686 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006687 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
6688 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00006689
Ted Kremenekc3b4c522008-08-07 00:49:01 +00006690 // For casts, we need to handle conversions from arrays to
6691 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00006692 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00006693 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00006694 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00006695 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00006696 case Stmt::CXXStaticCastExprClass:
6697 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00006698 case Stmt::CXXConstCastExprClass:
6699 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006700 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00006701 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00006702 case CK_LValueToRValue:
6703 case CK_NoOp:
6704 case CK_BaseToDerived:
6705 case CK_DerivedToBase:
6706 case CK_UncheckedDerivedToBase:
6707 case CK_Dynamic:
6708 case CK_CPointerToObjCPointerCast:
6709 case CK_BlockPointerToObjCPointerCast:
6710 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006711 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00006712
6713 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006714 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00006715
Richard Trieudadefde2014-07-02 04:39:38 +00006716 case CK_BitCast:
6717 if (SubExpr->getType()->isAnyPointerType() ||
6718 SubExpr->getType()->isBlockPointerType() ||
6719 SubExpr->getType()->isObjCQualifiedIdType())
6720 return EvalAddr(SubExpr, refVars, ParentDecl);
6721 else
6722 return nullptr;
6723
Eli Friedman8195ad72012-02-23 23:04:32 +00006724 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00006725 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00006726 }
Chris Lattner934edb22007-12-28 05:31:15 +00006727 }
Mike Stump11289f42009-09-09 15:08:12 +00006728
Douglas Gregorfe314812011-06-21 17:03:29 +00006729 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006730 if (const Expr *Result =
6731 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
6732 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00006733 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00006734 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006735
Chris Lattner934edb22007-12-28 05:31:15 +00006736 // Everything else: we simply don't reason about them.
6737 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00006738 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00006739 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006740}
Mike Stump11289f42009-09-09 15:08:12 +00006741
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006742/// EvalVal - This function is complements EvalAddr in the mutual recursion.
6743/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006744static const Expr *EvalVal(const Expr *E,
6745 SmallVectorImpl<const DeclRefExpr *> &refVars,
6746 const Decl *ParentDecl) {
6747 do {
6748 // We should only be called for evaluating non-pointer expressions, or
6749 // expressions with a pointer type that are not used as references but
6750 // instead
6751 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00006752
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006753 // Our "symbolic interpreter" is just a dispatch off the currently
6754 // viewed AST node. We then recursively traverse the AST by calling
6755 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00006756
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006757 E = E->IgnoreParens();
6758 switch (E->getStmtClass()) {
6759 case Stmt::ImplicitCastExprClass: {
6760 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
6761 if (IE->getValueKind() == VK_LValue) {
6762 E = IE->getSubExpr();
6763 continue;
6764 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006765 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006766 }
Richard Smith40f08eb2014-01-30 22:05:38 +00006767
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006768 case Stmt::ExprWithCleanupsClass:
6769 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
6770 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006771
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006772 case Stmt::DeclRefExprClass: {
6773 // When we hit a DeclRefExpr we are looking at code that refers to a
6774 // variable's name. If it's not a reference variable we check if it has
6775 // local storage within the function, and if so, return the expression.
6776 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6777
6778 // If we leave the immediate function, the lifetime isn't about to end.
6779 if (DR->refersToEnclosingVariableOrCapture())
6780 return nullptr;
6781
6782 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
6783 // Check if it refers to itself, e.g. "int& i = i;".
6784 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006785 return DR;
6786
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006787 if (V->hasLocalStorage()) {
6788 if (!V->getType()->isReferenceType())
6789 return DR;
6790
6791 // Reference variable, follow through to the expression that
6792 // it points to.
6793 if (V->hasInit()) {
6794 // Add the reference variable to the "trail".
6795 refVars.push_back(DR);
6796 return EvalVal(V->getInit(), refVars, V);
6797 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006798 }
6799 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006800
6801 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006802 }
Mike Stump11289f42009-09-09 15:08:12 +00006803
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006804 case Stmt::UnaryOperatorClass: {
6805 // The only unary operator that make sense to handle here
6806 // is Deref. All others don't resolve to a "name." This includes
6807 // handling all sorts of rvalues passed to a unary operator.
6808 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006809
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006810 if (U->getOpcode() == UO_Deref)
6811 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00006812
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006813 return nullptr;
6814 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006815
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006816 case Stmt::ArraySubscriptExprClass: {
6817 // Array subscripts are potential references to data on the stack. We
6818 // retrieve the DeclRefExpr* for the array variable if it indeed
6819 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00006820 const auto *ASE = cast<ArraySubscriptExpr>(E);
6821 if (ASE->isTypeDependent())
6822 return nullptr;
6823 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006824 }
Mike Stump11289f42009-09-09 15:08:12 +00006825
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006826 case Stmt::OMPArraySectionExprClass: {
6827 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
6828 ParentDecl);
6829 }
Mike Stump11289f42009-09-09 15:08:12 +00006830
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006831 case Stmt::ConditionalOperatorClass: {
6832 // For conditional operators we need to see if either the LHS or RHS are
6833 // non-NULL Expr's. If one is non-NULL, we return it.
6834 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00006835
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006836 // Handle the GNU extension for missing LHS.
6837 if (const Expr *LHSExpr = C->getLHS()) {
6838 // In C++, we can have a throw-expression, which has 'void' type.
6839 if (!LHSExpr->getType()->isVoidType())
6840 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
6841 return LHS;
6842 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006843
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006844 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006845 if (C->getRHS()->getType()->isVoidType())
6846 return nullptr;
6847
6848 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006849 }
6850
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006851 // Accesses to members are potential references to data on the stack.
6852 case Stmt::MemberExprClass: {
6853 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00006854
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006855 // Check for indirect access. We only want direct field accesses.
6856 if (M->isArrow())
6857 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006858
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006859 // Check whether the member type is itself a reference, in which case
6860 // we're not going to refer to the member, but to what the member refers
6861 // to.
6862 if (M->getMemberDecl()->getType()->isReferenceType())
6863 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006864
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006865 return EvalVal(M->getBase(), refVars, ParentDecl);
6866 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00006867
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006868 case Stmt::MaterializeTemporaryExprClass:
6869 if (const Expr *Result =
6870 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
6871 refVars, ParentDecl))
6872 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006873 return E;
6874
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006875 default:
6876 // Check that we don't return or take the address of a reference to a
6877 // temporary. This is only useful in C++.
6878 if (!E->isTypeDependent() && E->isRValue())
6879 return E;
6880
6881 // Everything else: we simply don't reason about them.
6882 return nullptr;
6883 }
6884 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006885}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006886
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006887void
6888Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
6889 SourceLocation ReturnLoc,
6890 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00006891 const AttrVec *Attrs,
6892 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006893 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
6894
6895 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00006896 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
6897 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00006898 CheckNonNullExpr(*this, RetValExp))
6899 Diag(ReturnLoc, diag::warn_null_ret)
6900 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00006901
6902 // C++11 [basic.stc.dynamic.allocation]p4:
6903 // If an allocation function declared with a non-throwing
6904 // exception-specification fails to allocate storage, it shall return
6905 // a null pointer. Any other allocation function that fails to allocate
6906 // storage shall indicate failure only by throwing an exception [...]
6907 if (FD) {
6908 OverloadedOperatorKind Op = FD->getOverloadedOperator();
6909 if (Op == OO_New || Op == OO_Array_New) {
6910 const FunctionProtoType *Proto
6911 = FD->getType()->castAs<FunctionProtoType>();
6912 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
6913 CheckNonNullExpr(*this, RetValExp))
6914 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
6915 << FD << getLangOpts().CPlusPlus11;
6916 }
6917 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006918}
6919
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006920//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
6921
6922/// Check for comparisons of floating point operands using != and ==.
6923/// Issue a warning if these are no self-comparisons, as they are not likely
6924/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00006925void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00006926 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
6927 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006928
6929 // Special case: check for x == x (which is OK).
6930 // Do not emit warnings for such cases.
6931 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
6932 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
6933 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00006934 return;
Mike Stump11289f42009-09-09 15:08:12 +00006935
Ted Kremenekeda40e22007-11-29 00:59:04 +00006936 // Special case: check for comparisons against literals that can be exactly
6937 // represented by APFloat. In such cases, do not emit a warning. This
6938 // is a heuristic: often comparison against such literals are used to
6939 // detect if a value in a variable has not changed. This clearly can
6940 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00006941 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
6942 if (FLL->isExact())
6943 return;
6944 } else
6945 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
6946 if (FLR->isExact())
6947 return;
Mike Stump11289f42009-09-09 15:08:12 +00006948
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006949 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00006950 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00006951 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00006952 return;
Mike Stump11289f42009-09-09 15:08:12 +00006953
David Blaikie1f4ff152012-07-16 20:47:22 +00006954 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00006955 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00006956 return;
Mike Stump11289f42009-09-09 15:08:12 +00006957
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006958 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00006959 Diag(Loc, diag::warn_floatingpoint_eq)
6960 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006961}
John McCallca01b222010-01-04 23:21:16 +00006962
John McCall70aa5392010-01-06 05:24:50 +00006963//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
6964//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00006965
John McCall70aa5392010-01-06 05:24:50 +00006966namespace {
John McCallca01b222010-01-04 23:21:16 +00006967
John McCall70aa5392010-01-06 05:24:50 +00006968/// Structure recording the 'active' range of an integer-valued
6969/// expression.
6970struct IntRange {
6971 /// The number of bits active in the int.
6972 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00006973
John McCall70aa5392010-01-06 05:24:50 +00006974 /// True if the int is known not to have negative values.
6975 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00006976
John McCall70aa5392010-01-06 05:24:50 +00006977 IntRange(unsigned Width, bool NonNegative)
6978 : Width(Width), NonNegative(NonNegative)
6979 {}
John McCallca01b222010-01-04 23:21:16 +00006980
John McCall817d4af2010-11-10 23:38:19 +00006981 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00006982 static IntRange forBoolType() {
6983 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00006984 }
6985
John McCall817d4af2010-11-10 23:38:19 +00006986 /// Returns the range of an opaque value of the given integral type.
6987 static IntRange forValueOfType(ASTContext &C, QualType T) {
6988 return forValueOfCanonicalType(C,
6989 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00006990 }
6991
John McCall817d4af2010-11-10 23:38:19 +00006992 /// Returns the range of an opaque value of a canonical integral type.
6993 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00006994 assert(T->isCanonicalUnqualified());
6995
6996 if (const VectorType *VT = dyn_cast<VectorType>(T))
6997 T = VT->getElementType().getTypePtr();
6998 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
6999 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00007000 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7001 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00007002
David Majnemer6a426652013-06-07 22:07:20 +00007003 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00007004 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00007005 EnumDecl *Enum = ET->getDecl();
7006 if (!Enum->isCompleteDefinition())
7007 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00007008
David Majnemer6a426652013-06-07 22:07:20 +00007009 unsigned NumPositive = Enum->getNumPositiveBits();
7010 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00007011
David Majnemer6a426652013-06-07 22:07:20 +00007012 if (NumNegative == 0)
7013 return IntRange(NumPositive, true/*NonNegative*/);
7014 else
7015 return IntRange(std::max(NumPositive + 1, NumNegative),
7016 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00007017 }
John McCall70aa5392010-01-06 05:24:50 +00007018
7019 const BuiltinType *BT = cast<BuiltinType>(T);
7020 assert(BT->isInteger());
7021
7022 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7023 }
7024
John McCall817d4af2010-11-10 23:38:19 +00007025 /// Returns the "target" range of a canonical integral type, i.e.
7026 /// the range of values expressible in the type.
7027 ///
7028 /// This matches forValueOfCanonicalType except that enums have the
7029 /// full range of their type, not the range of their enumerators.
7030 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
7031 assert(T->isCanonicalUnqualified());
7032
7033 if (const VectorType *VT = dyn_cast<VectorType>(T))
7034 T = VT->getElementType().getTypePtr();
7035 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7036 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00007037 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7038 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00007039 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00007040 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00007041
7042 const BuiltinType *BT = cast<BuiltinType>(T);
7043 assert(BT->isInteger());
7044
7045 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7046 }
7047
7048 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00007049 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00007050 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00007051 L.NonNegative && R.NonNegative);
7052 }
7053
John McCall817d4af2010-11-10 23:38:19 +00007054 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00007055 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00007056 return IntRange(std::min(L.Width, R.Width),
7057 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00007058 }
7059};
7060
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007061IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00007062 if (value.isSigned() && value.isNegative())
7063 return IntRange(value.getMinSignedBits(), false);
7064
7065 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00007066 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00007067
7068 // isNonNegative() just checks the sign bit without considering
7069 // signedness.
7070 return IntRange(value.getActiveBits(), true);
7071}
7072
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007073IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
7074 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00007075 if (result.isInt())
7076 return GetValueRange(C, result.getInt(), MaxWidth);
7077
7078 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00007079 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
7080 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
7081 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
7082 R = IntRange::join(R, El);
7083 }
John McCall70aa5392010-01-06 05:24:50 +00007084 return R;
7085 }
7086
7087 if (result.isComplexInt()) {
7088 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
7089 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
7090 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00007091 }
7092
7093 // This can happen with lossless casts to intptr_t of "based" lvalues.
7094 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00007095 // FIXME: The only reason we need to pass the type in here is to get
7096 // the sign right on this one case. It would be nice if APValue
7097 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007098 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00007099 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00007100}
John McCall70aa5392010-01-06 05:24:50 +00007101
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007102QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00007103 QualType Ty = E->getType();
7104 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
7105 Ty = AtomicRHS->getValueType();
7106 return Ty;
7107}
7108
John McCall70aa5392010-01-06 05:24:50 +00007109/// Pseudo-evaluate the given integer expression, estimating the
7110/// range of values it might take.
7111///
7112/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007113IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00007114 E = E->IgnoreParens();
7115
7116 // Try a full evaluation first.
7117 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00007118 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00007119 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00007120
7121 // I think we only want to look through implicit casts here; if the
7122 // user has an explicit widening cast, we should treat the value as
7123 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007124 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00007125 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00007126 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
7127
Eli Friedmane6d33952013-07-08 20:20:06 +00007128 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00007129
George Burgess IVdf1ed002016-01-13 01:52:39 +00007130 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
7131 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00007132
John McCall70aa5392010-01-06 05:24:50 +00007133 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00007134 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00007135 return OutputTypeRange;
7136
7137 IntRange SubRange
7138 = GetExprRange(C, CE->getSubExpr(),
7139 std::min(MaxWidth, OutputTypeRange.Width));
7140
7141 // Bail out if the subexpr's range is as wide as the cast type.
7142 if (SubRange.Width >= OutputTypeRange.Width)
7143 return OutputTypeRange;
7144
7145 // Otherwise, we take the smaller width, and we're non-negative if
7146 // either the output type or the subexpr is.
7147 return IntRange(SubRange.Width,
7148 SubRange.NonNegative || OutputTypeRange.NonNegative);
7149 }
7150
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007151 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00007152 // If we can fold the condition, just take that operand.
7153 bool CondResult;
7154 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
7155 return GetExprRange(C, CondResult ? CO->getTrueExpr()
7156 : CO->getFalseExpr(),
7157 MaxWidth);
7158
7159 // Otherwise, conservatively merge.
7160 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
7161 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
7162 return IntRange::join(L, R);
7163 }
7164
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007165 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00007166 switch (BO->getOpcode()) {
7167
7168 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00007169 case BO_LAnd:
7170 case BO_LOr:
7171 case BO_LT:
7172 case BO_GT:
7173 case BO_LE:
7174 case BO_GE:
7175 case BO_EQ:
7176 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00007177 return IntRange::forBoolType();
7178
John McCallc3688382011-07-13 06:35:24 +00007179 // The type of the assignments is the type of the LHS, so the RHS
7180 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00007181 case BO_MulAssign:
7182 case BO_DivAssign:
7183 case BO_RemAssign:
7184 case BO_AddAssign:
7185 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00007186 case BO_XorAssign:
7187 case BO_OrAssign:
7188 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00007189 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00007190
John McCallc3688382011-07-13 06:35:24 +00007191 // Simple assignments just pass through the RHS, which will have
7192 // been coerced to the LHS type.
7193 case BO_Assign:
7194 // TODO: bitfields?
7195 return GetExprRange(C, BO->getRHS(), MaxWidth);
7196
John McCall70aa5392010-01-06 05:24:50 +00007197 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00007198 case BO_PtrMemD:
7199 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00007200 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00007201
John McCall2ce81ad2010-01-06 22:07:33 +00007202 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00007203 case BO_And:
7204 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00007205 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
7206 GetExprRange(C, BO->getRHS(), MaxWidth));
7207
John McCall70aa5392010-01-06 05:24:50 +00007208 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00007209 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00007210 // ...except that we want to treat '1 << (blah)' as logically
7211 // positive. It's an important idiom.
7212 if (IntegerLiteral *I
7213 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
7214 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00007215 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00007216 return IntRange(R.Width, /*NonNegative*/ true);
7217 }
7218 }
7219 // fallthrough
7220
John McCalle3027922010-08-25 11:45:40 +00007221 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00007222 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00007223
John McCall2ce81ad2010-01-06 22:07:33 +00007224 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00007225 case BO_Shr:
7226 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00007227 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
7228
7229 // If the shift amount is a positive constant, drop the width by
7230 // that much.
7231 llvm::APSInt shift;
7232 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
7233 shift.isNonNegative()) {
7234 unsigned zext = shift.getZExtValue();
7235 if (zext >= L.Width)
7236 L.Width = (L.NonNegative ? 0 : 1);
7237 else
7238 L.Width -= zext;
7239 }
7240
7241 return L;
7242 }
7243
7244 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00007245 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00007246 return GetExprRange(C, BO->getRHS(), MaxWidth);
7247
John McCall2ce81ad2010-01-06 22:07:33 +00007248 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00007249 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00007250 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00007251 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00007252 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007253
John McCall51431812011-07-14 22:39:48 +00007254 // The width of a division result is mostly determined by the size
7255 // of the LHS.
7256 case BO_Div: {
7257 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00007258 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00007259 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
7260
7261 // If the divisor is constant, use that.
7262 llvm::APSInt divisor;
7263 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
7264 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
7265 if (log2 >= L.Width)
7266 L.Width = (L.NonNegative ? 0 : 1);
7267 else
7268 L.Width = std::min(L.Width - log2, MaxWidth);
7269 return L;
7270 }
7271
7272 // Otherwise, just use the LHS's width.
7273 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
7274 return IntRange(L.Width, L.NonNegative && R.NonNegative);
7275 }
7276
7277 // The result of a remainder can't be larger than the result of
7278 // either side.
7279 case BO_Rem: {
7280 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00007281 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00007282 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
7283 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
7284
7285 IntRange meet = IntRange::meet(L, R);
7286 meet.Width = std::min(meet.Width, MaxWidth);
7287 return meet;
7288 }
7289
7290 // The default behavior is okay for these.
7291 case BO_Mul:
7292 case BO_Add:
7293 case BO_Xor:
7294 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00007295 break;
7296 }
7297
John McCall51431812011-07-14 22:39:48 +00007298 // The default case is to treat the operation as if it were closed
7299 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00007300 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
7301 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
7302 return IntRange::join(L, R);
7303 }
7304
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007305 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00007306 switch (UO->getOpcode()) {
7307 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00007308 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00007309 return IntRange::forBoolType();
7310
7311 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00007312 case UO_Deref:
7313 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00007314 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00007315
7316 default:
7317 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
7318 }
7319 }
7320
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007321 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00007322 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
7323
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007324 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00007325 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00007326 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00007327
Eli Friedmane6d33952013-07-08 20:20:06 +00007328 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00007329}
John McCall263a48b2010-01-04 23:31:57 +00007330
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007331IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00007332 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00007333}
7334
John McCall263a48b2010-01-04 23:31:57 +00007335/// Checks whether the given value, which currently has the given
7336/// source semantics, has the same value when coerced through the
7337/// target semantics.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007338bool IsSameFloatAfterCast(const llvm::APFloat &value,
7339 const llvm::fltSemantics &Src,
7340 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00007341 llvm::APFloat truncated = value;
7342
7343 bool ignored;
7344 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
7345 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
7346
7347 return truncated.bitwiseIsEqual(value);
7348}
7349
7350/// Checks whether the given value, which currently has the given
7351/// source semantics, has the same value when coerced through the
7352/// target semantics.
7353///
7354/// The value might be a vector of floats (or a complex number).
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007355bool IsSameFloatAfterCast(const APValue &value,
7356 const llvm::fltSemantics &Src,
7357 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00007358 if (value.isFloat())
7359 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
7360
7361 if (value.isVector()) {
7362 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
7363 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
7364 return false;
7365 return true;
7366 }
7367
7368 assert(value.isComplexFloat());
7369 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
7370 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
7371}
7372
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007373void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007374
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007375bool IsZero(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00007376 // Suppress cases where we are comparing against an enum constant.
7377 if (const DeclRefExpr *DR =
7378 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
7379 if (isa<EnumConstantDecl>(DR->getDecl()))
7380 return false;
7381
7382 // Suppress cases where the '0' value is expanded from a macro.
7383 if (E->getLocStart().isMacroID())
7384 return false;
7385
John McCallcc7e5bf2010-05-06 08:58:33 +00007386 llvm::APSInt Value;
7387 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
7388}
7389
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007390bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00007391 // Strip off implicit integral promotions.
7392 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00007393 if (ICE->getCastKind() != CK_IntegralCast &&
7394 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00007395 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00007396 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00007397 }
7398
7399 return E->getType()->isEnumeralType();
7400}
7401
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007402void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00007403 // Disable warning in template instantiations.
7404 if (!S.ActiveTemplateInstantiations.empty())
7405 return;
7406
John McCalle3027922010-08-25 11:45:40 +00007407 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00007408 if (E->isValueDependent())
7409 return;
7410
John McCalle3027922010-08-25 11:45:40 +00007411 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007412 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00007413 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00007414 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00007415 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007416 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00007417 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00007418 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00007419 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007420 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00007421 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00007422 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00007423 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007424 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00007425 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00007426 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
7427 }
7428}
7429
Benjamin Kramer7320b992016-06-15 14:20:56 +00007430void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant,
7431 Expr *Other, const llvm::APSInt &Value,
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007432 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00007433 // Disable warning in template instantiations.
7434 if (!S.ActiveTemplateInstantiations.empty())
7435 return;
7436
Richard Trieu0f097742014-04-04 04:13:47 +00007437 // TODO: Investigate using GetExprRange() to get tighter bounds
7438 // on the bit ranges.
7439 QualType OtherT = Other->getType();
David Majnemer7800f1f2015-05-23 01:32:17 +00007440 if (const auto *AT = OtherT->getAs<AtomicType>())
Justin Bogner4f42fc42014-07-21 18:01:53 +00007441 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00007442 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
7443 unsigned OtherWidth = OtherRange.Width;
7444
7445 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
7446
Richard Trieu560910c2012-11-14 22:50:24 +00007447 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00007448 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00007449 return;
7450
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007451 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00007452 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00007453
Richard Trieu0f097742014-04-04 04:13:47 +00007454 // Used for diagnostic printout.
7455 enum {
7456 LiteralConstant = 0,
7457 CXXBoolLiteralTrue,
7458 CXXBoolLiteralFalse
7459 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00007460
Richard Trieu0f097742014-04-04 04:13:47 +00007461 if (!OtherIsBooleanType) {
7462 QualType ConstantT = Constant->getType();
7463 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00007464
Richard Trieu0f097742014-04-04 04:13:47 +00007465 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
7466 return;
7467 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
7468 "comparison with non-integer type");
7469
7470 bool ConstantSigned = ConstantT->isSignedIntegerType();
7471 bool CommonSigned = CommonT->isSignedIntegerType();
7472
7473 bool EqualityOnly = false;
7474
7475 if (CommonSigned) {
7476 // The common type is signed, therefore no signed to unsigned conversion.
7477 if (!OtherRange.NonNegative) {
7478 // Check that the constant is representable in type OtherT.
7479 if (ConstantSigned) {
7480 if (OtherWidth >= Value.getMinSignedBits())
7481 return;
7482 } else { // !ConstantSigned
7483 if (OtherWidth >= Value.getActiveBits() + 1)
7484 return;
7485 }
7486 } else { // !OtherSigned
7487 // Check that the constant is representable in type OtherT.
7488 // Negative values are out of range.
7489 if (ConstantSigned) {
7490 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
7491 return;
7492 } else { // !ConstantSigned
7493 if (OtherWidth >= Value.getActiveBits())
7494 return;
7495 }
Richard Trieu560910c2012-11-14 22:50:24 +00007496 }
Richard Trieu0f097742014-04-04 04:13:47 +00007497 } else { // !CommonSigned
7498 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00007499 if (OtherWidth >= Value.getActiveBits())
7500 return;
Craig Toppercf360162014-06-18 05:13:11 +00007501 } else { // OtherSigned
7502 assert(!ConstantSigned &&
7503 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00007504 // Check to see if the constant is representable in OtherT.
7505 if (OtherWidth > Value.getActiveBits())
7506 return;
7507 // Check to see if the constant is equivalent to a negative value
7508 // cast to CommonT.
7509 if (S.Context.getIntWidth(ConstantT) ==
7510 S.Context.getIntWidth(CommonT) &&
7511 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
7512 return;
7513 // The constant value rests between values that OtherT can represent
7514 // after conversion. Relational comparison still works, but equality
7515 // comparisons will be tautological.
7516 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00007517 }
7518 }
Richard Trieu0f097742014-04-04 04:13:47 +00007519
7520 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
7521
7522 if (op == BO_EQ || op == BO_NE) {
7523 IsTrue = op == BO_NE;
7524 } else if (EqualityOnly) {
7525 return;
7526 } else if (RhsConstant) {
7527 if (op == BO_GT || op == BO_GE)
7528 IsTrue = !PositiveConstant;
7529 else // op == BO_LT || op == BO_LE
7530 IsTrue = PositiveConstant;
7531 } else {
7532 if (op == BO_LT || op == BO_LE)
7533 IsTrue = !PositiveConstant;
7534 else // op == BO_GT || op == BO_GE
7535 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00007536 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007537 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00007538 // Other isKnownToHaveBooleanValue
7539 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
7540 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
7541 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
7542
7543 static const struct LinkedConditions {
7544 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
7545 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
7546 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
7547 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
7548 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
7549 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
7550
7551 } TruthTable = {
7552 // Constant on LHS. | Constant on RHS. |
7553 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
7554 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
7555 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
7556 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
7557 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
7558 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
7559 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
7560 };
7561
7562 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
7563
7564 enum ConstantValue ConstVal = Zero;
7565 if (Value.isUnsigned() || Value.isNonNegative()) {
7566 if (Value == 0) {
7567 LiteralOrBoolConstant =
7568 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
7569 ConstVal = Zero;
7570 } else if (Value == 1) {
7571 LiteralOrBoolConstant =
7572 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
7573 ConstVal = One;
7574 } else {
7575 LiteralOrBoolConstant = LiteralConstant;
7576 ConstVal = GT_One;
7577 }
7578 } else {
7579 ConstVal = LT_Zero;
7580 }
7581
7582 CompareBoolWithConstantResult CmpRes;
7583
7584 switch (op) {
7585 case BO_LT:
7586 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
7587 break;
7588 case BO_GT:
7589 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
7590 break;
7591 case BO_LE:
7592 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
7593 break;
7594 case BO_GE:
7595 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
7596 break;
7597 case BO_EQ:
7598 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
7599 break;
7600 case BO_NE:
7601 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
7602 break;
7603 default:
7604 CmpRes = Unkwn;
7605 break;
7606 }
7607
7608 if (CmpRes == AFals) {
7609 IsTrue = false;
7610 } else if (CmpRes == ATrue) {
7611 IsTrue = true;
7612 } else {
7613 return;
7614 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007615 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00007616
7617 // If this is a comparison to an enum constant, include that
7618 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00007619 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00007620 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
7621 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
7622
7623 SmallString<64> PrettySourceValue;
7624 llvm::raw_svector_ostream OS(PrettySourceValue);
7625 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00007626 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00007627 else
7628 OS << Value;
7629
Richard Trieu0f097742014-04-04 04:13:47 +00007630 S.DiagRuntimeBehavior(
7631 E->getOperatorLoc(), E,
7632 S.PDiag(diag::warn_out_of_range_compare)
7633 << OS.str() << LiteralOrBoolConstant
7634 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
7635 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007636}
7637
John McCallcc7e5bf2010-05-06 08:58:33 +00007638/// Analyze the operands of the given comparison. Implements the
7639/// fallback case from AnalyzeComparison.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007640void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00007641 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
7642 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00007643}
John McCall263a48b2010-01-04 23:31:57 +00007644
John McCallca01b222010-01-04 23:21:16 +00007645/// \brief Implements -Wsign-compare.
7646///
Richard Trieu82402a02011-09-15 21:56:47 +00007647/// \param E the binary operator to check for warnings
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007648void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007649 // The type the comparison is being performed in.
7650 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00007651
7652 // Only analyze comparison operators where both sides have been converted to
7653 // the same type.
7654 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
7655 return AnalyzeImpConvsInComparison(S, E);
7656
7657 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00007658 if (E->isValueDependent())
7659 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007660
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007661 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
7662 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007663
7664 bool IsComparisonConstant = false;
7665
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007666 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007667 // of 'true' or 'false'.
7668 if (T->isIntegralType(S.Context)) {
7669 llvm::APSInt RHSValue;
7670 bool IsRHSIntegralLiteral =
7671 RHS->isIntegerConstantExpr(RHSValue, S.Context);
7672 llvm::APSInt LHSValue;
7673 bool IsLHSIntegralLiteral =
7674 LHS->isIntegerConstantExpr(LHSValue, S.Context);
7675 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
7676 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
7677 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
7678 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
7679 else
7680 IsComparisonConstant =
7681 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007682 } else if (!T->hasUnsignedIntegerRepresentation())
7683 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007684
John McCallcc7e5bf2010-05-06 08:58:33 +00007685 // We don't do anything special if this isn't an unsigned integral
7686 // comparison: we're only interested in integral comparisons, and
7687 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00007688 //
7689 // We also don't care about value-dependent expressions or expressions
7690 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007691 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00007692 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007693
John McCallcc7e5bf2010-05-06 08:58:33 +00007694 // Check to see if one of the (unmodified) operands is of different
7695 // signedness.
7696 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00007697 if (LHS->getType()->hasSignedIntegerRepresentation()) {
7698 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00007699 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00007700 signedOperand = LHS;
7701 unsignedOperand = RHS;
7702 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
7703 signedOperand = RHS;
7704 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00007705 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00007706 CheckTrivialUnsignedComparison(S, E);
7707 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007708 }
7709
John McCallcc7e5bf2010-05-06 08:58:33 +00007710 // Otherwise, calculate the effective range of the signed operand.
7711 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00007712
John McCallcc7e5bf2010-05-06 08:58:33 +00007713 // Go ahead and analyze implicit conversions in the operands. Note
7714 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00007715 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
7716 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00007717
John McCallcc7e5bf2010-05-06 08:58:33 +00007718 // If the signed range is non-negative, -Wsign-compare won't fire,
7719 // but we should still check for comparisons which are always true
7720 // or false.
7721 if (signedRange.NonNegative)
7722 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007723
7724 // For (in)equality comparisons, if the unsigned operand is a
7725 // constant which cannot collide with a overflowed signed operand,
7726 // then reinterpreting the signed operand as unsigned will not
7727 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00007728 if (E->isEqualityOp()) {
7729 unsigned comparisonWidth = S.Context.getIntWidth(T);
7730 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00007731
John McCallcc7e5bf2010-05-06 08:58:33 +00007732 // We should never be unable to prove that the unsigned operand is
7733 // non-negative.
7734 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
7735
7736 if (unsignedRange.Width < comparisonWidth)
7737 return;
7738 }
7739
Douglas Gregorbfb4a212012-05-01 01:53:49 +00007740 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
7741 S.PDiag(diag::warn_mixed_sign_comparison)
7742 << LHS->getType() << RHS->getType()
7743 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00007744}
7745
John McCall1f425642010-11-11 03:21:53 +00007746/// Analyzes an attempt to assign the given value to a bitfield.
7747///
7748/// Returns true if there was something fishy about the attempt.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007749bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
7750 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00007751 assert(Bitfield->isBitField());
7752 if (Bitfield->isInvalidDecl())
7753 return false;
7754
John McCalldeebbcf2010-11-11 05:33:51 +00007755 // White-list bool bitfields.
7756 if (Bitfield->getType()->isBooleanType())
7757 return false;
7758
Douglas Gregor789adec2011-02-04 13:09:01 +00007759 // Ignore value- or type-dependent expressions.
7760 if (Bitfield->getBitWidth()->isValueDependent() ||
7761 Bitfield->getBitWidth()->isTypeDependent() ||
7762 Init->isValueDependent() ||
7763 Init->isTypeDependent())
7764 return false;
7765
John McCall1f425642010-11-11 03:21:53 +00007766 Expr *OriginalInit = Init->IgnoreParenImpCasts();
7767
Richard Smith5fab0c92011-12-28 19:48:30 +00007768 llvm::APSInt Value;
7769 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00007770 return false;
7771
John McCall1f425642010-11-11 03:21:53 +00007772 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00007773 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00007774
7775 if (OriginalWidth <= FieldWidth)
7776 return false;
7777
Eli Friedmanc267a322012-01-26 23:11:39 +00007778 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00007779 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00007780 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00007781
Eli Friedmanc267a322012-01-26 23:11:39 +00007782 // Check whether the stored value is equal to the original value.
7783 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00007784 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00007785 return false;
7786
Eli Friedmanc267a322012-01-26 23:11:39 +00007787 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00007788 // therefore don't strictly fit into a signed bitfield of width 1.
7789 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00007790 return false;
7791
John McCall1f425642010-11-11 03:21:53 +00007792 std::string PrettyValue = Value.toString(10);
7793 std::string PrettyTrunc = TruncatedValue.toString(10);
7794
7795 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
7796 << PrettyValue << PrettyTrunc << OriginalInit->getType()
7797 << Init->getSourceRange();
7798
7799 return true;
7800}
7801
John McCalld2a53122010-11-09 23:24:47 +00007802/// Analyze the given simple or compound assignment for warning-worthy
7803/// operations.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007804void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00007805 // Just recurse on the LHS.
7806 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
7807
7808 // We want to recurse on the RHS as normal unless we're assigning to
7809 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00007810 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007811 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00007812 E->getOperatorLoc())) {
7813 // Recurse, ignoring any implicit conversions on the RHS.
7814 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
7815 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00007816 }
7817 }
7818
7819 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
7820}
7821
John McCall263a48b2010-01-04 23:31:57 +00007822/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007823void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
7824 SourceLocation CContext, unsigned diag,
7825 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00007826 if (pruneControlFlow) {
7827 S.DiagRuntimeBehavior(E->getExprLoc(), E,
7828 S.PDiag(diag)
7829 << SourceType << T << E->getSourceRange()
7830 << SourceRange(CContext));
7831 return;
7832 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00007833 S.Diag(E->getExprLoc(), diag)
7834 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
7835}
7836
Chandler Carruth7f3654f2011-04-05 06:47:57 +00007837/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007838void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
7839 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00007840 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00007841}
7842
Richard Trieube234c32016-04-21 21:04:55 +00007843
7844/// Diagnose an implicit cast from a floating point value to an integer value.
7845void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
7846
7847 SourceLocation CContext) {
7848 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
7849 const bool PruneWarnings = !S.ActiveTemplateInstantiations.empty();
7850
7851 Expr *InnerE = E->IgnoreParenImpCasts();
7852 // We also want to warn on, e.g., "int i = -1.234"
7853 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
7854 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
7855 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
7856
7857 const bool IsLiteral =
7858 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
7859
7860 llvm::APFloat Value(0.0);
7861 bool IsConstant =
7862 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
7863 if (!IsConstant) {
Richard Trieu891f0f12016-04-22 22:14:32 +00007864 return DiagnoseImpCast(S, E, T, CContext,
7865 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +00007866 }
7867
Chandler Carruth016ef402011-04-10 08:36:24 +00007868 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +00007869
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00007870 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
7871 T->hasUnsignedIntegerRepresentation());
Richard Trieube234c32016-04-21 21:04:55 +00007872 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
7873 &isExact) == llvm::APFloat::opOK &&
Richard Trieu891f0f12016-04-22 22:14:32 +00007874 isExact) {
Richard Trieube234c32016-04-21 21:04:55 +00007875 if (IsLiteral) return;
7876 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
7877 PruneWarnings);
7878 }
7879
7880 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +00007881 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +00007882 // Warn on floating point literal to integer.
7883 DiagID = diag::warn_impcast_literal_float_to_integer;
7884 } else if (IntegerValue == 0) {
7885 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
7886 return DiagnoseImpCast(S, E, T, CContext,
7887 diag::warn_impcast_float_integer, PruneWarnings);
7888 }
7889 // Warn on non-zero to zero conversion.
7890 DiagID = diag::warn_impcast_float_to_integer_zero;
7891 } else {
7892 if (IntegerValue.isUnsigned()) {
7893 if (!IntegerValue.isMaxValue()) {
7894 return DiagnoseImpCast(S, E, T, CContext,
7895 diag::warn_impcast_float_integer, PruneWarnings);
7896 }
7897 } else { // IntegerValue.isSigned()
7898 if (!IntegerValue.isMaxSignedValue() &&
7899 !IntegerValue.isMinSignedValue()) {
7900 return DiagnoseImpCast(S, E, T, CContext,
7901 diag::warn_impcast_float_integer, PruneWarnings);
7902 }
7903 }
7904 // Warn on evaluatable floating point expression to integer conversion.
7905 DiagID = diag::warn_impcast_float_to_integer;
7906 }
Chandler Carruth016ef402011-04-10 08:36:24 +00007907
Eli Friedman07185912013-08-29 23:44:43 +00007908 // FIXME: Force the precision of the source value down so we don't print
7909 // digits which are usually useless (we don't really care here if we
7910 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
7911 // would automatically print the shortest representation, but it's a bit
7912 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00007913 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00007914 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
7915 precision = (precision * 59 + 195) / 196;
7916 Value.toString(PrettySourceValue, precision);
7917
David Blaikie9b88cc02012-05-15 17:18:27 +00007918 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +00007919 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +00007920 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00007921 else
David Blaikie9b88cc02012-05-15 17:18:27 +00007922 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00007923
Richard Trieube234c32016-04-21 21:04:55 +00007924 if (PruneWarnings) {
7925 S.DiagRuntimeBehavior(E->getExprLoc(), E,
7926 S.PDiag(DiagID)
7927 << E->getType() << T.getUnqualifiedType()
7928 << PrettySourceValue << PrettyTargetValue
7929 << E->getSourceRange() << SourceRange(CContext));
7930 } else {
7931 S.Diag(E->getExprLoc(), DiagID)
7932 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
7933 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
7934 }
Chandler Carruth016ef402011-04-10 08:36:24 +00007935}
7936
John McCall18a2c2c2010-11-09 22:22:12 +00007937std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
7938 if (!Range.Width) return "0";
7939
7940 llvm::APSInt ValueInRange = Value;
7941 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00007942 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00007943 return ValueInRange.toString(10);
7944}
7945
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007946bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007947 if (!isa<ImplicitCastExpr>(Ex))
7948 return false;
7949
7950 Expr *InnerE = Ex->IgnoreParenImpCasts();
7951 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
7952 const Type *Source =
7953 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
7954 if (Target->isDependentType())
7955 return false;
7956
7957 const BuiltinType *FloatCandidateBT =
7958 dyn_cast<BuiltinType>(ToBool ? Source : Target);
7959 const Type *BoolCandidateType = ToBool ? Target : Source;
7960
7961 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
7962 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
7963}
7964
7965void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
7966 SourceLocation CC) {
7967 unsigned NumArgs = TheCall->getNumArgs();
7968 for (unsigned i = 0; i < NumArgs; ++i) {
7969 Expr *CurrA = TheCall->getArg(i);
7970 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
7971 continue;
7972
7973 bool IsSwapped = ((i > 0) &&
7974 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
7975 IsSwapped |= ((i < (NumArgs - 1)) &&
7976 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
7977 if (IsSwapped) {
7978 // Warn on this floating-point to bool conversion.
7979 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
7980 CurrA->getType(), CC,
7981 diag::warn_impcast_floating_point_to_bool);
7982 }
7983 }
7984}
7985
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007986void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00007987 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
7988 E->getExprLoc()))
7989 return;
7990
Richard Trieu09d6b802016-01-08 23:35:06 +00007991 // Don't warn on functions which have return type nullptr_t.
7992 if (isa<CallExpr>(E))
7993 return;
7994
Richard Trieu5b993502014-10-15 03:42:06 +00007995 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
7996 const Expr::NullPointerConstantKind NullKind =
7997 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
7998 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
7999 return;
8000
8001 // Return if target type is a safe conversion.
8002 if (T->isAnyPointerType() || T->isBlockPointerType() ||
8003 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
8004 return;
8005
8006 SourceLocation Loc = E->getSourceRange().getBegin();
8007
Richard Trieu0a5e1662016-02-13 00:58:53 +00008008 // Venture through the macro stacks to get to the source of macro arguments.
8009 // The new location is a better location than the complete location that was
8010 // passed in.
8011 while (S.SourceMgr.isMacroArgExpansion(Loc))
8012 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
8013
8014 while (S.SourceMgr.isMacroArgExpansion(CC))
8015 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
8016
Richard Trieu5b993502014-10-15 03:42:06 +00008017 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +00008018 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
8019 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
8020 Loc, S.SourceMgr, S.getLangOpts());
8021 if (MacroName == "NULL")
8022 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
Richard Trieu5b993502014-10-15 03:42:06 +00008023 }
8024
8025 // Only warn if the null and context location are in the same macro expansion.
8026 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
8027 return;
8028
8029 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
8030 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
8031 << FixItHint::CreateReplacement(Loc,
8032 S.getFixItZeroLiteralForType(T, Loc));
8033}
8034
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008035void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8036 ObjCArrayLiteral *ArrayLiteral);
8037void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8038 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +00008039
8040/// Check a single element within a collection literal against the
8041/// target element type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008042void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
8043 Expr *Element, unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00008044 // Skip a bitcast to 'id' or qualified 'id'.
8045 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
8046 if (ICE->getCastKind() == CK_BitCast &&
8047 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
8048 Element = ICE->getSubExpr();
8049 }
8050
8051 QualType ElementType = Element->getType();
8052 ExprResult ElementResult(Element);
8053 if (ElementType->getAs<ObjCObjectPointerType>() &&
8054 S.CheckSingleAssignmentConstraints(TargetElementType,
8055 ElementResult,
8056 false, false)
8057 != Sema::Compatible) {
8058 S.Diag(Element->getLocStart(),
8059 diag::warn_objc_collection_literal_element)
8060 << ElementType << ElementKind << TargetElementType
8061 << Element->getSourceRange();
8062 }
8063
8064 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
8065 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
8066 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
8067 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
8068}
8069
8070/// Check an Objective-C array literal being converted to the given
8071/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008072void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8073 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00008074 if (!S.NSArrayDecl)
8075 return;
8076
8077 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8078 if (!TargetObjCPtr)
8079 return;
8080
8081 if (TargetObjCPtr->isUnspecialized() ||
8082 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8083 != S.NSArrayDecl->getCanonicalDecl())
8084 return;
8085
8086 auto TypeArgs = TargetObjCPtr->getTypeArgs();
8087 if (TypeArgs.size() != 1)
8088 return;
8089
8090 QualType TargetElementType = TypeArgs[0];
8091 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
8092 checkObjCCollectionLiteralElement(S, TargetElementType,
8093 ArrayLiteral->getElement(I),
8094 0);
8095 }
8096}
8097
8098/// Check an Objective-C dictionary literal being converted to the given
8099/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008100void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8101 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00008102 if (!S.NSDictionaryDecl)
8103 return;
8104
8105 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8106 if (!TargetObjCPtr)
8107 return;
8108
8109 if (TargetObjCPtr->isUnspecialized() ||
8110 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8111 != S.NSDictionaryDecl->getCanonicalDecl())
8112 return;
8113
8114 auto TypeArgs = TargetObjCPtr->getTypeArgs();
8115 if (TypeArgs.size() != 2)
8116 return;
8117
8118 QualType TargetKeyType = TypeArgs[0];
8119 QualType TargetObjectType = TypeArgs[1];
8120 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
8121 auto Element = DictionaryLiteral->getKeyValueElement(I);
8122 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
8123 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
8124 }
8125}
8126
Richard Trieufc404c72016-02-05 23:02:38 +00008127// Helper function to filter out cases for constant width constant conversion.
8128// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008129bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
8130 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +00008131 // If initializing from a constant, and the constant starts with '0',
8132 // then it is a binary, octal, or hexadecimal. Allow these constants
8133 // to fill all the bits, even if there is a sign change.
8134 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
8135 const char FirstLiteralCharacter =
8136 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
8137 if (FirstLiteralCharacter == '0')
8138 return false;
8139 }
8140
8141 // If the CC location points to a '{', and the type is char, then assume
8142 // assume it is an array initialization.
8143 if (CC.isValid() && T->isCharType()) {
8144 const char FirstContextCharacter =
8145 S.getSourceManager().getCharacterData(CC)[0];
8146 if (FirstContextCharacter == '{')
8147 return false;
8148 }
8149
8150 return true;
8151}
8152
John McCallcc7e5bf2010-05-06 08:58:33 +00008153void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00008154 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008155 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00008156
John McCallcc7e5bf2010-05-06 08:58:33 +00008157 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
8158 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
8159 if (Source == Target) return;
8160 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00008161
Chandler Carruthc22845a2011-07-26 05:40:03 +00008162 // If the conversion context location is invalid don't complain. We also
8163 // don't want to emit a warning if the issue occurs from the expansion of
8164 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
8165 // delay this check as long as possible. Once we detect we are in that
8166 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008167 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00008168 return;
8169
Richard Trieu021baa32011-09-23 20:10:00 +00008170 // Diagnose implicit casts to bool.
8171 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
8172 if (isa<StringLiteral>(E))
8173 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00008174 // and expressions, for instance, assert(0 && "error here"), are
8175 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00008176 return DiagnoseImpCast(S, E, T, CC,
8177 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00008178 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
8179 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
8180 // This covers the literal expressions that evaluate to Objective-C
8181 // objects.
8182 return DiagnoseImpCast(S, E, T, CC,
8183 diag::warn_impcast_objective_c_literal_to_bool);
8184 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00008185 if (Source->isPointerType() || Source->canDecayToPointerType()) {
8186 // Warn on pointer to bool conversion that is always true.
8187 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
8188 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00008189 }
Richard Trieu021baa32011-09-23 20:10:00 +00008190 }
John McCall263a48b2010-01-04 23:31:57 +00008191
Douglas Gregor5054cb02015-07-07 03:58:22 +00008192 // Check implicit casts from Objective-C collection literals to specialized
8193 // collection types, e.g., NSArray<NSString *> *.
8194 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
8195 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
8196 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
8197 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
8198
John McCall263a48b2010-01-04 23:31:57 +00008199 // Strip vector types.
8200 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008201 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008202 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008203 return;
John McCallacf0ee52010-10-08 02:01:28 +00008204 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008205 }
Chris Lattneree7286f2011-06-14 04:51:15 +00008206
8207 // If the vector cast is cast between two vectors of the same size, it is
8208 // a bitcast, not a conversion.
8209 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
8210 return;
John McCall263a48b2010-01-04 23:31:57 +00008211
8212 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
8213 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
8214 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00008215 if (auto VecTy = dyn_cast<VectorType>(Target))
8216 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00008217
8218 // Strip complex types.
8219 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008220 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008221 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008222 return;
8223
John McCallacf0ee52010-10-08 02:01:28 +00008224 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008225 }
John McCall263a48b2010-01-04 23:31:57 +00008226
8227 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
8228 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
8229 }
8230
8231 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
8232 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
8233
8234 // If the source is floating point...
8235 if (SourceBT && SourceBT->isFloatingPoint()) {
8236 // ...and the target is floating point...
8237 if (TargetBT && TargetBT->isFloatingPoint()) {
8238 // ...then warn if we're dropping FP rank.
8239
8240 // Builtin FP kinds are ordered by increasing FP rank.
8241 if (SourceBT->getKind() > TargetBT->getKind()) {
8242 // Don't warn about float constants that are precisely
8243 // representable in the target type.
8244 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00008245 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00008246 // Value might be a float, a float vector, or a float complex.
8247 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00008248 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
8249 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00008250 return;
8251 }
8252
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008253 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008254 return;
8255
John McCallacf0ee52010-10-08 02:01:28 +00008256 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +00008257 }
8258 // ... or possibly if we're increasing rank, too
8259 else if (TargetBT->getKind() > SourceBT->getKind()) {
8260 if (S.SourceMgr.isInSystemMacro(CC))
8261 return;
8262
8263 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +00008264 }
8265 return;
8266 }
8267
Richard Trieube234c32016-04-21 21:04:55 +00008268 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00008269 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008270 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008271 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00008272
Richard Trieube234c32016-04-21 21:04:55 +00008273 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00008274 }
John McCall263a48b2010-01-04 23:31:57 +00008275
Richard Smith54894fd2015-12-30 01:06:52 +00008276 // Detect the case where a call result is converted from floating-point to
8277 // to bool, and the final argument to the call is converted from bool, to
8278 // discover this typo:
8279 //
8280 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
8281 //
8282 // FIXME: This is an incredibly special case; is there some more general
8283 // way to detect this class of misplaced-parentheses bug?
8284 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008285 // Check last argument of function call to see if it is an
8286 // implicit cast from a type matching the type the result
8287 // is being cast to.
8288 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +00008289 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008290 Expr *LastA = CEx->getArg(NumArgs - 1);
8291 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +00008292 if (isa<ImplicitCastExpr>(LastA) &&
8293 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008294 // Warn on this floating-point to bool conversion
8295 DiagnoseImpCast(S, E, T, CC,
8296 diag::warn_impcast_floating_point_to_bool);
8297 }
8298 }
8299 }
John McCall263a48b2010-01-04 23:31:57 +00008300 return;
8301 }
8302
Richard Trieu5b993502014-10-15 03:42:06 +00008303 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00008304
David Blaikie9366d2b2012-06-19 21:19:06 +00008305 if (!Source->isIntegerType() || !Target->isIntegerType())
8306 return;
8307
David Blaikie7555b6a2012-05-15 16:56:36 +00008308 // TODO: remove this early return once the false positives for constant->bool
8309 // in templates, macros, etc, are reduced or removed.
8310 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
8311 return;
8312
John McCallcc7e5bf2010-05-06 08:58:33 +00008313 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00008314 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00008315
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008316 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00008317 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008318 // TODO: this should happen for bitfield stores, too.
8319 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +00008320 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008321 if (S.SourceMgr.isInSystemMacro(CC))
8322 return;
8323
John McCall18a2c2c2010-11-09 22:22:12 +00008324 std::string PrettySourceValue = Value.toString(10);
8325 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008326
Ted Kremenek33ba9952011-10-22 02:37:33 +00008327 S.DiagRuntimeBehavior(E->getExprLoc(), E,
8328 S.PDiag(diag::warn_impcast_integer_precision_constant)
8329 << PrettySourceValue << PrettyTargetValue
8330 << E->getType() << T << E->getSourceRange()
8331 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00008332 return;
8333 }
8334
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008335 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
8336 if (S.SourceMgr.isInSystemMacro(CC))
8337 return;
8338
David Blaikie9455da02012-04-12 22:40:54 +00008339 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00008340 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
8341 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00008342 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00008343 }
8344
Richard Trieudcb55572016-01-29 23:51:16 +00008345 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
8346 SourceRange.NonNegative && Source->isSignedIntegerType()) {
8347 // Warn when doing a signed to signed conversion, warn if the positive
8348 // source value is exactly the width of the target type, which will
8349 // cause a negative value to be stored.
8350
8351 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +00008352 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
8353 !S.SourceMgr.isInSystemMacro(CC)) {
8354 if (isSameWidthConstantConversion(S, E, T, CC)) {
8355 std::string PrettySourceValue = Value.toString(10);
8356 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +00008357
Richard Trieufc404c72016-02-05 23:02:38 +00008358 S.DiagRuntimeBehavior(
8359 E->getExprLoc(), E,
8360 S.PDiag(diag::warn_impcast_integer_precision_constant)
8361 << PrettySourceValue << PrettyTargetValue << E->getType() << T
8362 << E->getSourceRange() << clang::SourceRange(CC));
8363 return;
Richard Trieudcb55572016-01-29 23:51:16 +00008364 }
8365 }
Richard Trieufc404c72016-02-05 23:02:38 +00008366
Richard Trieudcb55572016-01-29 23:51:16 +00008367 // Fall through for non-constants to give a sign conversion warning.
8368 }
8369
John McCallcc7e5bf2010-05-06 08:58:33 +00008370 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
8371 (!TargetRange.NonNegative && SourceRange.NonNegative &&
8372 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008373 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008374 return;
8375
John McCallcc7e5bf2010-05-06 08:58:33 +00008376 unsigned DiagID = diag::warn_impcast_integer_sign;
8377
8378 // Traditionally, gcc has warned about this under -Wsign-compare.
8379 // We also want to warn about it in -Wconversion.
8380 // So if -Wconversion is off, use a completely identical diagnostic
8381 // in the sign-compare group.
8382 // The conditional-checking code will
8383 if (ICContext) {
8384 DiagID = diag::warn_impcast_integer_sign_conditional;
8385 *ICContext = true;
8386 }
8387
John McCallacf0ee52010-10-08 02:01:28 +00008388 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00008389 }
8390
Douglas Gregora78f1932011-02-22 02:45:07 +00008391 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00008392 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
8393 // type, to give us better diagnostics.
8394 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00008395 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00008396 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8397 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
8398 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
8399 SourceType = S.Context.getTypeDeclType(Enum);
8400 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
8401 }
8402 }
8403
Douglas Gregora78f1932011-02-22 02:45:07 +00008404 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
8405 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00008406 if (SourceEnum->getDecl()->hasNameForLinkage() &&
8407 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008408 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008409 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008410 return;
8411
Douglas Gregor364f7db2011-03-12 00:14:31 +00008412 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00008413 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008414 }
John McCall263a48b2010-01-04 23:31:57 +00008415}
8416
David Blaikie18e9ac72012-05-15 21:57:38 +00008417void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
8418 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00008419
8420void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00008421 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008422 E = E->IgnoreParenImpCasts();
8423
8424 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00008425 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00008426
John McCallacf0ee52010-10-08 02:01:28 +00008427 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008428 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00008429 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00008430}
8431
David Blaikie18e9ac72012-05-15 21:57:38 +00008432void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
8433 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00008434 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00008435
8436 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00008437 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
8438 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00008439
8440 // If -Wconversion would have warned about either of the candidates
8441 // for a signedness conversion to the context type...
8442 if (!Suspicious) return;
8443
8444 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008445 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00008446 return;
8447
John McCallcc7e5bf2010-05-06 08:58:33 +00008448 // ...then check whether it would have warned about either of the
8449 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00008450 if (E->getType() == T) return;
8451
8452 Suspicious = false;
8453 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
8454 E->getType(), CC, &Suspicious);
8455 if (!Suspicious)
8456 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00008457 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00008458}
8459
Richard Trieu65724892014-11-15 06:37:39 +00008460/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
8461/// Input argument E is a logical expression.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008462void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +00008463 if (S.getLangOpts().Bool)
8464 return;
8465 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
8466}
8467
John McCallcc7e5bf2010-05-06 08:58:33 +00008468/// AnalyzeImplicitConversions - Find and report any interesting
8469/// implicit conversions in the given expression. There are a couple
8470/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00008471void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00008472 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00008473 Expr *E = OrigE->IgnoreParenImpCasts();
8474
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00008475 if (E->isTypeDependent() || E->isValueDependent())
8476 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00008477
John McCallcc7e5bf2010-05-06 08:58:33 +00008478 // For conditional operators, we analyze the arguments as if they
8479 // were being fed directly into the output.
8480 if (isa<ConditionalOperator>(E)) {
8481 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00008482 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00008483 return;
8484 }
8485
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008486 // Check implicit argument conversions for function calls.
8487 if (CallExpr *Call = dyn_cast<CallExpr>(E))
8488 CheckImplicitArgumentConversions(S, Call, CC);
8489
John McCallcc7e5bf2010-05-06 08:58:33 +00008490 // Go ahead and check any implicit conversions we might have skipped.
8491 // The non-canonical typecheck is just an optimization;
8492 // CheckImplicitConversion will filter out dead implicit conversions.
8493 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00008494 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008495
8496 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +00008497
8498 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
8499 // The bound subexpressions in a PseudoObjectExpr are not reachable
8500 // as transitive children.
8501 // FIXME: Use a more uniform representation for this.
8502 for (auto *SE : POE->semantics())
8503 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
8504 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00008505 }
Richard Smithd7bed4d2015-11-22 02:57:17 +00008506
John McCallcc7e5bf2010-05-06 08:58:33 +00008507 // Skip past explicit casts.
8508 if (isa<ExplicitCastExpr>(E)) {
8509 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00008510 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008511 }
8512
John McCalld2a53122010-11-09 23:24:47 +00008513 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8514 // Do a somewhat different check with comparison operators.
8515 if (BO->isComparisonOp())
8516 return AnalyzeComparison(S, BO);
8517
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008518 // And with simple assignments.
8519 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00008520 return AnalyzeAssignment(S, BO);
8521 }
John McCallcc7e5bf2010-05-06 08:58:33 +00008522
8523 // These break the otherwise-useful invariant below. Fortunately,
8524 // we don't really need to recurse into them, because any internal
8525 // expressions should have been analyzed already when they were
8526 // built into statements.
8527 if (isa<StmtExpr>(E)) return;
8528
8529 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00008530 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00008531
8532 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00008533 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00008534 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00008535 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +00008536 for (Stmt *SubStmt : E->children()) {
8537 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00008538 if (!ChildExpr)
8539 continue;
8540
Richard Trieu955231d2014-01-25 01:10:35 +00008541 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00008542 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00008543 // Ignore checking string literals that are in logical and operators.
8544 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00008545 continue;
8546 AnalyzeImplicitConversions(S, ChildExpr, CC);
8547 }
Richard Trieu791b86e2014-11-19 06:08:18 +00008548
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00008549 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00008550 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
8551 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00008552 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00008553
8554 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
8555 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00008556 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00008557 }
Richard Trieu791b86e2014-11-19 06:08:18 +00008558
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00008559 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
8560 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00008561 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008562}
8563
8564} // end anonymous namespace
8565
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00008566static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
8567 unsigned Start, unsigned End) {
8568 bool IllegalParams = false;
8569 for (unsigned I = Start; I <= End; ++I) {
8570 QualType Ty = TheCall->getArg(I)->getType();
8571 // Taking into account implicit conversions,
8572 // allow any integer within 32 bits range
8573 if (!Ty->isIntegerType() ||
8574 S.Context.getTypeSizeInChars(Ty).getQuantity() > 4) {
8575 S.Diag(TheCall->getArg(I)->getLocStart(),
8576 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
8577 IllegalParams = true;
8578 }
8579 // Potentially emit standard warnings for implicit conversions if enabled
8580 // using -Wconversion.
8581 CheckImplicitConversion(S, TheCall->getArg(I), S.Context.UnsignedIntTy,
8582 TheCall->getArg(I)->getLocStart());
8583 }
8584 return IllegalParams;
8585}
8586
Richard Trieuc1888e02014-06-28 23:25:37 +00008587// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
8588// Returns true when emitting a warning about taking the address of a reference.
8589static bool CheckForReference(Sema &SemaRef, const Expr *E,
Benjamin Kramer7320b992016-06-15 14:20:56 +00008590 const PartialDiagnostic &PD) {
Richard Trieuc1888e02014-06-28 23:25:37 +00008591 E = E->IgnoreParenImpCasts();
8592
8593 const FunctionDecl *FD = nullptr;
8594
8595 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8596 if (!DRE->getDecl()->getType()->isReferenceType())
8597 return false;
8598 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
8599 if (!M->getMemberDecl()->getType()->isReferenceType())
8600 return false;
8601 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00008602 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00008603 return false;
8604 FD = Call->getDirectCallee();
8605 } else {
8606 return false;
8607 }
8608
8609 SemaRef.Diag(E->getExprLoc(), PD);
8610
8611 // If possible, point to location of function.
8612 if (FD) {
8613 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
8614 }
8615
8616 return true;
8617}
8618
Richard Trieu4cbff5c2014-08-08 22:41:43 +00008619// Returns true if the SourceLocation is expanded from any macro body.
8620// Returns false if the SourceLocation is invalid, is from not in a macro
8621// expansion, or is from expanded from a top-level macro argument.
8622static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
8623 if (Loc.isInvalid())
8624 return false;
8625
8626 while (Loc.isMacroID()) {
8627 if (SM.isMacroBodyExpansion(Loc))
8628 return true;
8629 Loc = SM.getImmediateMacroCallerLoc(Loc);
8630 }
8631
8632 return false;
8633}
8634
Richard Trieu3bb8b562014-02-26 02:36:06 +00008635/// \brief Diagnose pointers that are always non-null.
8636/// \param E the expression containing the pointer
8637/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
8638/// compared to a null pointer
8639/// \param IsEqual True when the comparison is equal to a null pointer
8640/// \param Range Extra SourceRange to highlight in the diagnostic
8641void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
8642 Expr::NullPointerConstantKind NullKind,
8643 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00008644 if (!E)
8645 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008646
8647 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00008648 if (E->getExprLoc().isMacroID()) {
8649 const SourceManager &SM = getSourceManager();
8650 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
8651 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00008652 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00008653 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00008654 E = E->IgnoreImpCasts();
8655
8656 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
8657
Richard Trieuf7432752014-06-06 21:39:26 +00008658 if (isa<CXXThisExpr>(E)) {
8659 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
8660 : diag::warn_this_bool_conversion;
8661 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
8662 return;
8663 }
8664
Richard Trieu3bb8b562014-02-26 02:36:06 +00008665 bool IsAddressOf = false;
8666
8667 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
8668 if (UO->getOpcode() != UO_AddrOf)
8669 return;
8670 IsAddressOf = true;
8671 E = UO->getSubExpr();
8672 }
8673
Richard Trieuc1888e02014-06-28 23:25:37 +00008674 if (IsAddressOf) {
8675 unsigned DiagID = IsCompare
8676 ? diag::warn_address_of_reference_null_compare
8677 : diag::warn_address_of_reference_bool_conversion;
8678 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
8679 << IsEqual;
8680 if (CheckForReference(*this, E, PD)) {
8681 return;
8682 }
8683 }
8684
Nick Lewyckybc85ec82016-06-15 05:18:39 +00008685 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
8686 bool IsParam = isa<NonNullAttr>(NonnullAttr);
George Burgess IV850269a2015-12-08 22:02:00 +00008687 std::string Str;
8688 llvm::raw_string_ostream S(Str);
8689 E->printPretty(S, nullptr, getPrintingPolicy());
8690 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
8691 : diag::warn_cast_nonnull_to_bool;
8692 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
8693 << E->getSourceRange() << Range << IsEqual;
Nick Lewyckybc85ec82016-06-15 05:18:39 +00008694 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
George Burgess IV850269a2015-12-08 22:02:00 +00008695 };
8696
8697 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
8698 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
8699 if (auto *Callee = Call->getDirectCallee()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00008700 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
8701 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00008702 return;
8703 }
8704 }
8705 }
8706
Richard Trieu3bb8b562014-02-26 02:36:06 +00008707 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00008708 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008709 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
8710 D = R->getDecl();
8711 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
8712 D = M->getMemberDecl();
8713 }
8714
8715 // Weak Decls can be null.
8716 if (!D || D->isWeak())
8717 return;
George Burgess IV850269a2015-12-08 22:02:00 +00008718
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008719 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +00008720 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
8721 if (getCurFunction() &&
8722 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00008723 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
8724 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00008725 return;
8726 }
8727
8728 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
David Majnemera3debed2016-06-24 05:33:44 +00008729 auto ParamIter = llvm::find(FD->parameters(), PV);
George Burgess IV850269a2015-12-08 22:02:00 +00008730 assert(ParamIter != FD->param_end());
8731 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
8732
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008733 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
8734 if (!NonNull->args_size()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00008735 ComplainAboutNonnullParamOrCall(NonNull);
George Burgess IV850269a2015-12-08 22:02:00 +00008736 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008737 }
George Burgess IV850269a2015-12-08 22:02:00 +00008738
8739 for (unsigned ArgNo : NonNull->args()) {
8740 if (ArgNo == ParamNo) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00008741 ComplainAboutNonnullParamOrCall(NonNull);
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008742 return;
8743 }
George Burgess IV850269a2015-12-08 22:02:00 +00008744 }
8745 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008746 }
8747 }
George Burgess IV850269a2015-12-08 22:02:00 +00008748 }
8749
Richard Trieu3bb8b562014-02-26 02:36:06 +00008750 QualType T = D->getType();
8751 const bool IsArray = T->isArrayType();
8752 const bool IsFunction = T->isFunctionType();
8753
Richard Trieuc1888e02014-06-28 23:25:37 +00008754 // Address of function is used to silence the function warning.
8755 if (IsAddressOf && IsFunction) {
8756 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008757 }
8758
8759 // Found nothing.
8760 if (!IsAddressOf && !IsFunction && !IsArray)
8761 return;
8762
8763 // Pretty print the expression for the diagnostic.
8764 std::string Str;
8765 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00008766 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00008767
8768 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
8769 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +00008770 enum {
8771 AddressOf,
8772 FunctionPointer,
8773 ArrayPointer
8774 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008775 if (IsAddressOf)
8776 DiagType = AddressOf;
8777 else if (IsFunction)
8778 DiagType = FunctionPointer;
8779 else if (IsArray)
8780 DiagType = ArrayPointer;
8781 else
8782 llvm_unreachable("Could not determine diagnostic.");
8783 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
8784 << Range << IsEqual;
8785
8786 if (!IsFunction)
8787 return;
8788
8789 // Suggest '&' to silence the function warning.
8790 Diag(E->getExprLoc(), diag::note_function_warning_silence)
8791 << FixItHint::CreateInsertion(E->getLocStart(), "&");
8792
8793 // Check to see if '()' fixit should be emitted.
8794 QualType ReturnType;
8795 UnresolvedSet<4> NonTemplateOverloads;
8796 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
8797 if (ReturnType.isNull())
8798 return;
8799
8800 if (IsCompare) {
8801 // There are two cases here. If there is null constant, the only suggest
8802 // for a pointer return type. If the null is 0, then suggest if the return
8803 // type is a pointer or an integer type.
8804 if (!ReturnType->isPointerType()) {
8805 if (NullKind == Expr::NPCK_ZeroExpression ||
8806 NullKind == Expr::NPCK_ZeroLiteral) {
8807 if (!ReturnType->isIntegerType())
8808 return;
8809 } else {
8810 return;
8811 }
8812 }
8813 } else { // !IsCompare
8814 // For function to bool, only suggest if the function pointer has bool
8815 // return type.
8816 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
8817 return;
8818 }
8819 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00008820 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00008821}
8822
John McCallcc7e5bf2010-05-06 08:58:33 +00008823/// Diagnoses "dangerous" implicit conversions within the given
8824/// expression (which is a full expression). Implements -Wconversion
8825/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00008826///
8827/// \param CC the "context" location of the implicit conversion, i.e.
8828/// the most location of the syntactic entity requiring the implicit
8829/// conversion
8830void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008831 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00008832 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00008833 return;
8834
8835 // Don't diagnose for value- or type-dependent expressions.
8836 if (E->isTypeDependent() || E->isValueDependent())
8837 return;
8838
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008839 // Check for array bounds violations in cases where the check isn't triggered
8840 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
8841 // ArraySubscriptExpr is on the RHS of a variable initialization.
8842 CheckArrayAccess(E);
8843
John McCallacf0ee52010-10-08 02:01:28 +00008844 // This is not the right CC for (e.g.) a variable initialization.
8845 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008846}
8847
Richard Trieu65724892014-11-15 06:37:39 +00008848/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
8849/// Input argument E is a logical expression.
8850void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
8851 ::CheckBoolLikeConversion(*this, E, CC);
8852}
8853
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008854/// Diagnose when expression is an integer constant expression and its evaluation
8855/// results in integer overflow
8856void Sema::CheckForIntOverflow (Expr *E) {
Akira Hatanakadfe2156f2016-02-10 06:06:06 +00008857 // Use a work list to deal with nested struct initializers.
8858 SmallVector<Expr *, 2> Exprs(1, E);
8859
8860 do {
8861 Expr *E = Exprs.pop_back_val();
8862
8863 if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
8864 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
8865 continue;
8866 }
8867
8868 if (auto InitList = dyn_cast<InitListExpr>(E))
8869 Exprs.append(InitList->inits().begin(), InitList->inits().end());
8870 } while (!Exprs.empty());
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008871}
8872
Richard Smithc406cb72013-01-17 01:17:56 +00008873namespace {
8874/// \brief Visitor for expressions which looks for unsequenced operations on the
8875/// same object.
8876class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00008877 typedef EvaluatedExprVisitor<SequenceChecker> Base;
8878
Richard Smithc406cb72013-01-17 01:17:56 +00008879 /// \brief A tree of sequenced regions within an expression. Two regions are
8880 /// unsequenced if one is an ancestor or a descendent of the other. When we
8881 /// finish processing an expression with sequencing, such as a comma
8882 /// expression, we fold its tree nodes into its parent, since they are
8883 /// unsequenced with respect to nodes we will visit later.
8884 class SequenceTree {
8885 struct Value {
8886 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
8887 unsigned Parent : 31;
Aaron Ballmanaffa1c32016-07-06 18:33:01 +00008888 unsigned Merged : 1;
Richard Smithc406cb72013-01-17 01:17:56 +00008889 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008890 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00008891
8892 public:
8893 /// \brief A region within an expression which may be sequenced with respect
8894 /// to some other region.
8895 class Seq {
8896 explicit Seq(unsigned N) : Index(N) {}
8897 unsigned Index;
8898 friend class SequenceTree;
8899 public:
8900 Seq() : Index(0) {}
8901 };
8902
8903 SequenceTree() { Values.push_back(Value(0)); }
8904 Seq root() const { return Seq(0); }
8905
8906 /// \brief Create a new sequence of operations, which is an unsequenced
8907 /// subset of \p Parent. This sequence of operations is sequenced with
8908 /// respect to other children of \p Parent.
8909 Seq allocate(Seq Parent) {
8910 Values.push_back(Value(Parent.Index));
8911 return Seq(Values.size() - 1);
8912 }
8913
8914 /// \brief Merge a sequence of operations into its parent.
8915 void merge(Seq S) {
8916 Values[S.Index].Merged = true;
8917 }
8918
8919 /// \brief Determine whether two operations are unsequenced. This operation
8920 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
8921 /// should have been merged into its parent as appropriate.
8922 bool isUnsequenced(Seq Cur, Seq Old) {
8923 unsigned C = representative(Cur.Index);
8924 unsigned Target = representative(Old.Index);
8925 while (C >= Target) {
8926 if (C == Target)
8927 return true;
8928 C = Values[C].Parent;
8929 }
8930 return false;
8931 }
8932
8933 private:
8934 /// \brief Pick a representative for a sequence.
8935 unsigned representative(unsigned K) {
8936 if (Values[K].Merged)
8937 // Perform path compression as we go.
8938 return Values[K].Parent = representative(Values[K].Parent);
8939 return K;
8940 }
8941 };
8942
8943 /// An object for which we can track unsequenced uses.
8944 typedef NamedDecl *Object;
8945
8946 /// Different flavors of object usage which we track. We only track the
8947 /// least-sequenced usage of each kind.
8948 enum UsageKind {
8949 /// A read of an object. Multiple unsequenced reads are OK.
8950 UK_Use,
8951 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00008952 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00008953 UK_ModAsValue,
8954 /// A modification of an object which is not sequenced before the value
8955 /// computation of the expression, such as n++.
8956 UK_ModAsSideEffect,
8957
8958 UK_Count = UK_ModAsSideEffect + 1
8959 };
8960
8961 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00008962 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00008963 Expr *Use;
8964 SequenceTree::Seq Seq;
8965 };
8966
8967 struct UsageInfo {
8968 UsageInfo() : Diagnosed(false) {}
8969 Usage Uses[UK_Count];
8970 /// Have we issued a diagnostic for this variable already?
8971 bool Diagnosed;
8972 };
8973 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
8974
8975 Sema &SemaRef;
8976 /// Sequenced regions within the expression.
8977 SequenceTree Tree;
8978 /// Declaration modifications and references which we have seen.
8979 UsageInfoMap UsageMap;
8980 /// The region we are currently within.
8981 SequenceTree::Seq Region;
8982 /// Filled in with declarations which were modified as a side-effect
8983 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008984 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00008985 /// Expressions to check later. We defer checking these to reduce
8986 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008987 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00008988
8989 /// RAII object wrapping the visitation of a sequenced subexpression of an
8990 /// expression. At the end of this process, the side-effects of the evaluation
8991 /// become sequenced with respect to the value computation of the result, so
8992 /// we downgrade any UK_ModAsSideEffect within the evaluation to
8993 /// UK_ModAsValue.
8994 struct SequencedSubexpression {
8995 SequencedSubexpression(SequenceChecker &Self)
8996 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
8997 Self.ModAsSideEffect = &ModAsSideEffect;
8998 }
8999 ~SequencedSubexpression() {
David Majnemerf7e36092016-06-23 00:15:04 +00009000 for (auto &M : llvm::reverse(ModAsSideEffect)) {
9001 UsageInfo &U = Self.UsageMap[M.first];
Richard Smithe8efd992014-12-03 01:05:50 +00009002 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
David Majnemerf7e36092016-06-23 00:15:04 +00009003 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
9004 SideEffectUsage = M.second;
Richard Smithc406cb72013-01-17 01:17:56 +00009005 }
9006 Self.ModAsSideEffect = OldModAsSideEffect;
9007 }
9008
9009 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009010 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
9011 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00009012 };
9013
Richard Smith40238f02013-06-20 22:21:56 +00009014 /// RAII object wrapping the visitation of a subexpression which we might
9015 /// choose to evaluate as a constant. If any subexpression is evaluated and
9016 /// found to be non-constant, this allows us to suppress the evaluation of
9017 /// the outer expression.
9018 class EvaluationTracker {
9019 public:
9020 EvaluationTracker(SequenceChecker &Self)
9021 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
9022 Self.EvalTracker = this;
9023 }
9024 ~EvaluationTracker() {
9025 Self.EvalTracker = Prev;
9026 if (Prev)
9027 Prev->EvalOK &= EvalOK;
9028 }
9029
9030 bool evaluate(const Expr *E, bool &Result) {
9031 if (!EvalOK || E->isValueDependent())
9032 return false;
9033 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
9034 return EvalOK;
9035 }
9036
9037 private:
9038 SequenceChecker &Self;
9039 EvaluationTracker *Prev;
9040 bool EvalOK;
9041 } *EvalTracker;
9042
Richard Smithc406cb72013-01-17 01:17:56 +00009043 /// \brief Find the object which is produced by the specified expression,
9044 /// if any.
9045 Object getObject(Expr *E, bool Mod) const {
9046 E = E->IgnoreParenCasts();
9047 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9048 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
9049 return getObject(UO->getSubExpr(), Mod);
9050 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9051 if (BO->getOpcode() == BO_Comma)
9052 return getObject(BO->getRHS(), Mod);
9053 if (Mod && BO->isAssignmentOp())
9054 return getObject(BO->getLHS(), Mod);
9055 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9056 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
9057 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
9058 return ME->getMemberDecl();
9059 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9060 // FIXME: If this is a reference, map through to its value.
9061 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00009062 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00009063 }
9064
9065 /// \brief Note that an object was modified or used by an expression.
9066 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
9067 Usage &U = UI.Uses[UK];
9068 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
9069 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
9070 ModAsSideEffect->push_back(std::make_pair(O, U));
9071 U.Use = Ref;
9072 U.Seq = Region;
9073 }
9074 }
9075 /// \brief Check whether a modification or use conflicts with a prior usage.
9076 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
9077 bool IsModMod) {
9078 if (UI.Diagnosed)
9079 return;
9080
9081 const Usage &U = UI.Uses[OtherKind];
9082 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
9083 return;
9084
9085 Expr *Mod = U.Use;
9086 Expr *ModOrUse = Ref;
9087 if (OtherKind == UK_Use)
9088 std::swap(Mod, ModOrUse);
9089
9090 SemaRef.Diag(Mod->getExprLoc(),
9091 IsModMod ? diag::warn_unsequenced_mod_mod
9092 : diag::warn_unsequenced_mod_use)
9093 << O << SourceRange(ModOrUse->getExprLoc());
9094 UI.Diagnosed = true;
9095 }
9096
9097 void notePreUse(Object O, Expr *Use) {
9098 UsageInfo &U = UsageMap[O];
9099 // Uses conflict with other modifications.
9100 checkUsage(O, U, Use, UK_ModAsValue, false);
9101 }
9102 void notePostUse(Object O, Expr *Use) {
9103 UsageInfo &U = UsageMap[O];
9104 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
9105 addUsage(U, O, Use, UK_Use);
9106 }
9107
9108 void notePreMod(Object O, Expr *Mod) {
9109 UsageInfo &U = UsageMap[O];
9110 // Modifications conflict with other modifications and with uses.
9111 checkUsage(O, U, Mod, UK_ModAsValue, true);
9112 checkUsage(O, U, Mod, UK_Use, false);
9113 }
9114 void notePostMod(Object O, Expr *Use, UsageKind UK) {
9115 UsageInfo &U = UsageMap[O];
9116 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
9117 addUsage(U, O, Use, UK);
9118 }
9119
9120public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009121 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00009122 : Base(S.Context), SemaRef(S), Region(Tree.root()),
9123 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00009124 Visit(E);
9125 }
9126
9127 void VisitStmt(Stmt *S) {
9128 // Skip all statements which aren't expressions for now.
9129 }
9130
9131 void VisitExpr(Expr *E) {
9132 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00009133 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00009134 }
9135
9136 void VisitCastExpr(CastExpr *E) {
9137 Object O = Object();
9138 if (E->getCastKind() == CK_LValueToRValue)
9139 O = getObject(E->getSubExpr(), false);
9140
9141 if (O)
9142 notePreUse(O, E);
9143 VisitExpr(E);
9144 if (O)
9145 notePostUse(O, E);
9146 }
9147
9148 void VisitBinComma(BinaryOperator *BO) {
9149 // C++11 [expr.comma]p1:
9150 // Every value computation and side effect associated with the left
9151 // expression is sequenced before every value computation and side
9152 // effect associated with the right expression.
9153 SequenceTree::Seq LHS = Tree.allocate(Region);
9154 SequenceTree::Seq RHS = Tree.allocate(Region);
9155 SequenceTree::Seq OldRegion = Region;
9156
9157 {
9158 SequencedSubexpression SeqLHS(*this);
9159 Region = LHS;
9160 Visit(BO->getLHS());
9161 }
9162
9163 Region = RHS;
9164 Visit(BO->getRHS());
9165
9166 Region = OldRegion;
9167
9168 // Forget that LHS and RHS are sequenced. They are both unsequenced
9169 // with respect to other stuff.
9170 Tree.merge(LHS);
9171 Tree.merge(RHS);
9172 }
9173
9174 void VisitBinAssign(BinaryOperator *BO) {
9175 // The modification is sequenced after the value computation of the LHS
9176 // and RHS, so check it before inspecting the operands and update the
9177 // map afterwards.
9178 Object O = getObject(BO->getLHS(), true);
9179 if (!O)
9180 return VisitExpr(BO);
9181
9182 notePreMod(O, BO);
9183
9184 // C++11 [expr.ass]p7:
9185 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
9186 // only once.
9187 //
9188 // Therefore, for a compound assignment operator, O is considered used
9189 // everywhere except within the evaluation of E1 itself.
9190 if (isa<CompoundAssignOperator>(BO))
9191 notePreUse(O, BO);
9192
9193 Visit(BO->getLHS());
9194
9195 if (isa<CompoundAssignOperator>(BO))
9196 notePostUse(O, BO);
9197
9198 Visit(BO->getRHS());
9199
Richard Smith83e37bee2013-06-26 23:16:51 +00009200 // C++11 [expr.ass]p1:
9201 // the assignment is sequenced [...] before the value computation of the
9202 // assignment expression.
9203 // C11 6.5.16/3 has no such rule.
9204 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
9205 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00009206 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009207
Richard Smithc406cb72013-01-17 01:17:56 +00009208 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
9209 VisitBinAssign(CAO);
9210 }
9211
9212 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
9213 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
9214 void VisitUnaryPreIncDec(UnaryOperator *UO) {
9215 Object O = getObject(UO->getSubExpr(), true);
9216 if (!O)
9217 return VisitExpr(UO);
9218
9219 notePreMod(O, UO);
9220 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00009221 // C++11 [expr.pre.incr]p1:
9222 // the expression ++x is equivalent to x+=1
9223 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
9224 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00009225 }
9226
9227 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
9228 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
9229 void VisitUnaryPostIncDec(UnaryOperator *UO) {
9230 Object O = getObject(UO->getSubExpr(), true);
9231 if (!O)
9232 return VisitExpr(UO);
9233
9234 notePreMod(O, UO);
9235 Visit(UO->getSubExpr());
9236 notePostMod(O, UO, UK_ModAsSideEffect);
9237 }
9238
9239 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
9240 void VisitBinLOr(BinaryOperator *BO) {
9241 // The side-effects of the LHS of an '&&' are sequenced before the
9242 // value computation of the RHS, and hence before the value computation
9243 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
9244 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00009245 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00009246 {
9247 SequencedSubexpression Sequenced(*this);
9248 Visit(BO->getLHS());
9249 }
9250
9251 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00009252 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00009253 if (!Result)
9254 Visit(BO->getRHS());
9255 } else {
9256 // Check for unsequenced operations in the RHS, treating it as an
9257 // entirely separate evaluation.
9258 //
9259 // FIXME: If there are operations in the RHS which are unsequenced
9260 // with respect to operations outside the RHS, and those operations
9261 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00009262 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00009263 }
Richard Smithc406cb72013-01-17 01:17:56 +00009264 }
9265 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00009266 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00009267 {
9268 SequencedSubexpression Sequenced(*this);
9269 Visit(BO->getLHS());
9270 }
9271
9272 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00009273 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00009274 if (Result)
9275 Visit(BO->getRHS());
9276 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00009277 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00009278 }
Richard Smithc406cb72013-01-17 01:17:56 +00009279 }
9280
9281 // Only visit the condition, unless we can be sure which subexpression will
9282 // be chosen.
9283 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00009284 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00009285 {
9286 SequencedSubexpression Sequenced(*this);
9287 Visit(CO->getCond());
9288 }
Richard Smithc406cb72013-01-17 01:17:56 +00009289
9290 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00009291 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00009292 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00009293 else {
Richard Smithd33f5202013-01-17 23:18:09 +00009294 WorkList.push_back(CO->getTrueExpr());
9295 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00009296 }
Richard Smithc406cb72013-01-17 01:17:56 +00009297 }
9298
Richard Smithe3dbfe02013-06-30 10:40:20 +00009299 void VisitCallExpr(CallExpr *CE) {
9300 // C++11 [intro.execution]p15:
9301 // When calling a function [...], every value computation and side effect
9302 // associated with any argument expression, or with the postfix expression
9303 // designating the called function, is sequenced before execution of every
9304 // expression or statement in the body of the function [and thus before
9305 // the value computation of its result].
9306 SequencedSubexpression Sequenced(*this);
9307 Base::VisitCallExpr(CE);
9308
9309 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
9310 }
9311
Richard Smithc406cb72013-01-17 01:17:56 +00009312 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00009313 // This is a call, so all subexpressions are sequenced before the result.
9314 SequencedSubexpression Sequenced(*this);
9315
Richard Smithc406cb72013-01-17 01:17:56 +00009316 if (!CCE->isListInitialization())
9317 return VisitExpr(CCE);
9318
9319 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009320 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00009321 SequenceTree::Seq Parent = Region;
9322 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
9323 E = CCE->arg_end();
9324 I != E; ++I) {
9325 Region = Tree.allocate(Parent);
9326 Elts.push_back(Region);
9327 Visit(*I);
9328 }
9329
9330 // Forget that the initializers are sequenced.
9331 Region = Parent;
9332 for (unsigned I = 0; I < Elts.size(); ++I)
9333 Tree.merge(Elts[I]);
9334 }
9335
9336 void VisitInitListExpr(InitListExpr *ILE) {
9337 if (!SemaRef.getLangOpts().CPlusPlus11)
9338 return VisitExpr(ILE);
9339
9340 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009341 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00009342 SequenceTree::Seq Parent = Region;
9343 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
9344 Expr *E = ILE->getInit(I);
9345 if (!E) continue;
9346 Region = Tree.allocate(Parent);
9347 Elts.push_back(Region);
9348 Visit(E);
9349 }
9350
9351 // Forget that the initializers are sequenced.
9352 Region = Parent;
9353 for (unsigned I = 0; I < Elts.size(); ++I)
9354 Tree.merge(Elts[I]);
9355 }
9356};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009357} // end anonymous namespace
Richard Smithc406cb72013-01-17 01:17:56 +00009358
9359void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009360 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00009361 WorkList.push_back(E);
9362 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00009363 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00009364 SequenceChecker(*this, Item, WorkList);
9365 }
Richard Smithc406cb72013-01-17 01:17:56 +00009366}
9367
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009368void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
9369 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00009370 CheckImplicitConversions(E, CheckLoc);
9371 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009372 if (!IsConstexpr && !E->isValueDependent())
9373 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00009374}
9375
John McCall1f425642010-11-11 03:21:53 +00009376void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
9377 FieldDecl *BitField,
9378 Expr *Init) {
9379 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
9380}
9381
David Majnemer61a5bbf2015-04-07 22:08:51 +00009382static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
9383 SourceLocation Loc) {
9384 if (!PType->isVariablyModifiedType())
9385 return;
9386 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
9387 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
9388 return;
9389 }
David Majnemerdf8f73f2015-04-09 19:53:25 +00009390 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
9391 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
9392 return;
9393 }
David Majnemer61a5bbf2015-04-07 22:08:51 +00009394 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
9395 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
9396 return;
9397 }
9398
9399 const ArrayType *AT = S.Context.getAsArrayType(PType);
9400 if (!AT)
9401 return;
9402
9403 if (AT->getSizeModifier() != ArrayType::Star) {
9404 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
9405 return;
9406 }
9407
9408 S.Diag(Loc, diag::err_array_star_in_function_definition);
9409}
9410
Mike Stump0c2ec772010-01-21 03:59:47 +00009411/// CheckParmsForFunctionDef - Check that the parameters of the given
9412/// function are appropriate for the definition of a function. This
9413/// takes care of any checks that cannot be performed on the
9414/// declaration itself, e.g., that the types of each of the function
9415/// parameters are complete.
David Majnemer59f77922016-06-24 04:05:48 +00009416bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
Douglas Gregorb524d902010-11-01 18:37:59 +00009417 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00009418 bool HasInvalidParm = false;
David Majnemer59f77922016-06-24 04:05:48 +00009419 for (ParmVarDecl *Param : Parameters) {
Mike Stump0c2ec772010-01-21 03:59:47 +00009420 // C99 6.7.5.3p4: the parameters in a parameter type list in a
9421 // function declarator that is part of a function definition of
9422 // that function shall not have incomplete type.
9423 //
9424 // This is also C++ [dcl.fct]p6.
9425 if (!Param->isInvalidDecl() &&
9426 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00009427 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00009428 Param->setInvalidDecl();
9429 HasInvalidParm = true;
9430 }
9431
9432 // C99 6.9.1p5: If the declarator includes a parameter type list, the
9433 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00009434 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00009435 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00009436 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00009437 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00009438 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00009439
9440 // C99 6.7.5.3p12:
9441 // If the function declarator is not part of a definition of that
9442 // function, parameters may have incomplete type and may use the [*]
9443 // notation in their sequences of declarator specifiers to specify
9444 // variable length array types.
9445 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +00009446 // FIXME: This diagnostic should point the '[*]' if source-location
9447 // information is added for it.
9448 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00009449
9450 // MSVC destroys objects passed by value in the callee. Therefore a
9451 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00009452 // object's destructor. However, we don't perform any direct access check
9453 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00009454 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
9455 .getCXXABI()
9456 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00009457 if (!Param->isInvalidDecl()) {
9458 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
9459 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
9460 if (!ClassDecl->isInvalidDecl() &&
9461 !ClassDecl->hasIrrelevantDestructor() &&
9462 !ClassDecl->isDependentContext()) {
9463 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
9464 MarkFunctionReferenced(Param->getLocation(), Destructor);
9465 DiagnoseUseOfDecl(Destructor, Param->getLocation());
9466 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00009467 }
9468 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00009469 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009470
9471 // Parameters with the pass_object_size attribute only need to be marked
9472 // constant at function definitions. Because we lack information about
9473 // whether we're on a declaration or definition when we're instantiating the
9474 // attribute, we need to check for constness here.
9475 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
9476 if (!Param->getType().isConstQualified())
9477 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
9478 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +00009479 }
9480
9481 return HasInvalidParm;
9482}
John McCall2b5c1b22010-08-12 21:44:57 +00009483
9484/// CheckCastAlign - Implements -Wcast-align, which warns when a
9485/// pointer cast increases the alignment requirements.
9486void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
9487 // This is actually a lot of work to potentially be doing on every
9488 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009489 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00009490 return;
9491
9492 // Ignore dependent types.
9493 if (T->isDependentType() || Op->getType()->isDependentType())
9494 return;
9495
9496 // Require that the destination be a pointer type.
9497 const PointerType *DestPtr = T->getAs<PointerType>();
9498 if (!DestPtr) return;
9499
9500 // If the destination has alignment 1, we're done.
9501 QualType DestPointee = DestPtr->getPointeeType();
9502 if (DestPointee->isIncompleteType()) return;
9503 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
9504 if (DestAlign.isOne()) return;
9505
9506 // Require that the source be a pointer type.
9507 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
9508 if (!SrcPtr) return;
9509 QualType SrcPointee = SrcPtr->getPointeeType();
9510
9511 // Whitelist casts from cv void*. We already implicitly
9512 // whitelisted casts to cv void*, since they have alignment 1.
9513 // Also whitelist casts involving incomplete types, which implicitly
9514 // includes 'void'.
9515 if (SrcPointee->isIncompleteType()) return;
9516
9517 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
9518 if (SrcAlign >= DestAlign) return;
9519
9520 Diag(TRange.getBegin(), diag::warn_cast_align)
9521 << Op->getType() << T
9522 << static_cast<unsigned>(SrcAlign.getQuantity())
9523 << static_cast<unsigned>(DestAlign.getQuantity())
9524 << TRange << Op->getSourceRange();
9525}
9526
Chandler Carruth28389f02011-08-05 09:10:50 +00009527/// \brief Check whether this array fits the idiom of a size-one tail padded
9528/// array member of a struct.
9529///
9530/// We avoid emitting out-of-bounds access warnings for such arrays as they are
9531/// commonly used to emulate flexible arrays in C89 code.
Benjamin Kramer7320b992016-06-15 14:20:56 +00009532static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
Chandler Carruth28389f02011-08-05 09:10:50 +00009533 const NamedDecl *ND) {
9534 if (Size != 1 || !ND) return false;
9535
9536 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
9537 if (!FD) return false;
9538
9539 // Don't consider sizes resulting from macro expansions or template argument
9540 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00009541
9542 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00009543 while (TInfo) {
9544 TypeLoc TL = TInfo->getTypeLoc();
9545 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00009546 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
9547 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00009548 TInfo = TDL->getTypeSourceInfo();
9549 continue;
9550 }
David Blaikie6adc78e2013-02-18 22:06:02 +00009551 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
9552 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00009553 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
9554 return false;
9555 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00009556 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00009557 }
Chandler Carruth28389f02011-08-05 09:10:50 +00009558
9559 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00009560 if (!RD) return false;
9561 if (RD->isUnion()) return false;
9562 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
9563 if (!CRD->isStandardLayout()) return false;
9564 }
Chandler Carruth28389f02011-08-05 09:10:50 +00009565
Benjamin Kramer8c543672011-08-06 03:04:42 +00009566 // See if this is the last field decl in the record.
9567 const Decl *D = FD;
9568 while ((D = D->getNextDeclInContext()))
9569 if (isa<FieldDecl>(D))
9570 return false;
9571 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00009572}
9573
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009574void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009575 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00009576 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009577 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009578 if (IndexExpr->isValueDependent())
9579 return;
9580
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009581 const Type *EffectiveType =
9582 BaseExpr->getType()->getPointeeOrArrayElementType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009583 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009584 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009585 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009586 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00009587 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00009588
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009589 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +00009590 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +00009591 return;
Richard Smith13f67182011-12-16 19:31:14 +00009592 if (IndexNegated)
9593 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00009594
Craig Topperc3ec1492014-05-26 06:22:03 +00009595 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00009596 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
9597 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00009598 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00009599 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00009600
Ted Kremeneke4b316c2011-02-23 23:06:04 +00009601 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00009602 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00009603 if (!size.isStrictlyPositive())
9604 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009605
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009606 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
Nico Weber7c299802011-09-17 22:59:41 +00009607 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009608 // Make sure we're comparing apples to apples when comparing index to size
9609 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
9610 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00009611 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00009612 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009613 if (ptrarith_typesize != array_typesize) {
9614 // There's a cast to a different size type involved
9615 uint64_t ratio = array_typesize / ptrarith_typesize;
9616 // TODO: Be smarter about handling cases where array_typesize is not a
9617 // multiple of ptrarith_typesize
9618 if (ptrarith_typesize * ratio == array_typesize)
9619 size *= llvm::APInt(size.getBitWidth(), ratio);
9620 }
9621 }
9622
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009623 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009624 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00009625 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009626 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00009627
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009628 // For array subscripting the index must be less than size, but for pointer
9629 // arithmetic also allow the index (offset) to be equal to size since
9630 // computing the next address after the end of the array is legal and
9631 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009632 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00009633 return;
9634
9635 // Also don't warn for arrays of size 1 which are members of some
9636 // structure. These are often used to approximate flexible arrays in C89
9637 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009638 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00009639 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009640
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009641 // Suppress the warning if the subscript expression (as identified by the
9642 // ']' location) and the index expression are both from macro expansions
9643 // within a system header.
9644 if (ASE) {
9645 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
9646 ASE->getRBracketLoc());
9647 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
9648 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
9649 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00009650 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009651 return;
9652 }
9653 }
9654
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009655 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009656 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009657 DiagID = diag::warn_array_index_exceeds_bounds;
9658
9659 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
9660 PDiag(DiagID) << index.toString(10, true)
9661 << size.toString(10, true)
9662 << (unsigned)size.getLimitedValue(~0U)
9663 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009664 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009665 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009666 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009667 DiagID = diag::warn_ptr_arith_precedes_bounds;
9668 if (index.isNegative()) index = -index;
9669 }
9670
9671 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
9672 PDiag(DiagID) << index.toString(10, true)
9673 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00009674 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00009675
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00009676 if (!ND) {
9677 // Try harder to find a NamedDecl to point at in the note.
9678 while (const ArraySubscriptExpr *ASE =
9679 dyn_cast<ArraySubscriptExpr>(BaseExpr))
9680 BaseExpr = ASE->getBase()->IgnoreParenCasts();
9681 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
9682 ND = dyn_cast<NamedDecl>(DRE->getDecl());
9683 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
9684 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
9685 }
9686
Chandler Carruth1af88f12011-02-17 21:10:52 +00009687 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009688 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
9689 PDiag(diag::note_array_index_out_of_bounds)
9690 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00009691}
9692
Ted Kremenekdf26df72011-03-01 18:41:00 +00009693void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009694 int AllowOnePastEnd = 0;
9695 while (expr) {
9696 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00009697 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009698 case Stmt::ArraySubscriptExprClass: {
9699 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009700 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009701 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00009702 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009703 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +00009704 case Stmt::OMPArraySectionExprClass: {
9705 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
9706 if (ASE->getLowerBound())
9707 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
9708 /*ASE=*/nullptr, AllowOnePastEnd > 0);
9709 return;
9710 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009711 case Stmt::UnaryOperatorClass: {
9712 // Only unwrap the * and & unary operators
9713 const UnaryOperator *UO = cast<UnaryOperator>(expr);
9714 expr = UO->getSubExpr();
9715 switch (UO->getOpcode()) {
9716 case UO_AddrOf:
9717 AllowOnePastEnd++;
9718 break;
9719 case UO_Deref:
9720 AllowOnePastEnd--;
9721 break;
9722 default:
9723 return;
9724 }
9725 break;
9726 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00009727 case Stmt::ConditionalOperatorClass: {
9728 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
9729 if (const Expr *lhs = cond->getLHS())
9730 CheckArrayAccess(lhs);
9731 if (const Expr *rhs = cond->getRHS())
9732 CheckArrayAccess(rhs);
9733 return;
9734 }
9735 default:
9736 return;
9737 }
Peter Collingbourne91147592011-04-15 00:35:48 +00009738 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00009739}
John McCall31168b02011-06-15 23:02:42 +00009740
9741//===--- CHECK: Objective-C retain cycles ----------------------------------//
9742
9743namespace {
9744 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00009745 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00009746 VarDecl *Variable;
9747 SourceRange Range;
9748 SourceLocation Loc;
9749 bool Indirect;
9750
9751 void setLocsFrom(Expr *e) {
9752 Loc = e->getExprLoc();
9753 Range = e->getSourceRange();
9754 }
9755 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009756} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +00009757
9758/// Consider whether capturing the given variable can possibly lead to
9759/// a retain cycle.
9760static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00009761 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00009762 // lifetime. In MRR, it's captured strongly if the variable is
9763 // __block and has an appropriate type.
9764 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
9765 return false;
9766
9767 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009768 if (ref)
9769 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00009770 return true;
9771}
9772
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009773static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00009774 while (true) {
9775 e = e->IgnoreParens();
9776 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
9777 switch (cast->getCastKind()) {
9778 case CK_BitCast:
9779 case CK_LValueBitCast:
9780 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00009781 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00009782 e = cast->getSubExpr();
9783 continue;
9784
John McCall31168b02011-06-15 23:02:42 +00009785 default:
9786 return false;
9787 }
9788 }
9789
9790 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
9791 ObjCIvarDecl *ivar = ref->getDecl();
9792 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
9793 return false;
9794
9795 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009796 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00009797 return false;
9798
9799 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
9800 owner.Indirect = true;
9801 return true;
9802 }
9803
9804 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
9805 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
9806 if (!var) return false;
9807 return considerVariable(var, ref, owner);
9808 }
9809
John McCall31168b02011-06-15 23:02:42 +00009810 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
9811 if (member->isArrow()) return false;
9812
9813 // Don't count this as an indirect ownership.
9814 e = member->getBase();
9815 continue;
9816 }
9817
John McCallfe96e0b2011-11-06 09:01:30 +00009818 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
9819 // Only pay attention to pseudo-objects on property references.
9820 ObjCPropertyRefExpr *pre
9821 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
9822 ->IgnoreParens());
9823 if (!pre) return false;
9824 if (pre->isImplicitProperty()) return false;
9825 ObjCPropertyDecl *property = pre->getExplicitProperty();
9826 if (!property->isRetaining() &&
9827 !(property->getPropertyIvarDecl() &&
9828 property->getPropertyIvarDecl()->getType()
9829 .getObjCLifetime() == Qualifiers::OCL_Strong))
9830 return false;
9831
9832 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009833 if (pre->isSuperReceiver()) {
9834 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
9835 if (!owner.Variable)
9836 return false;
9837 owner.Loc = pre->getLocation();
9838 owner.Range = pre->getSourceRange();
9839 return true;
9840 }
John McCallfe96e0b2011-11-06 09:01:30 +00009841 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
9842 ->getSourceExpr());
9843 continue;
9844 }
9845
John McCall31168b02011-06-15 23:02:42 +00009846 // Array ivars?
9847
9848 return false;
9849 }
9850}
9851
9852namespace {
9853 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
9854 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
9855 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009856 Context(Context), Variable(variable), Capturer(nullptr),
9857 VarWillBeReased(false) {}
9858 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +00009859 VarDecl *Variable;
9860 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009861 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +00009862
9863 void VisitDeclRefExpr(DeclRefExpr *ref) {
9864 if (ref->getDecl() == Variable && !Capturer)
9865 Capturer = ref;
9866 }
9867
John McCall31168b02011-06-15 23:02:42 +00009868 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
9869 if (Capturer) return;
9870 Visit(ref->getBase());
9871 if (Capturer && ref->isFreeIvar())
9872 Capturer = ref;
9873 }
9874
9875 void VisitBlockExpr(BlockExpr *block) {
9876 // Look inside nested blocks
9877 if (block->getBlockDecl()->capturesVariable(Variable))
9878 Visit(block->getBlockDecl()->getBody());
9879 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00009880
9881 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
9882 if (Capturer) return;
9883 if (OVE->getSourceExpr())
9884 Visit(OVE->getSourceExpr());
9885 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009886 void VisitBinaryOperator(BinaryOperator *BinOp) {
9887 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
9888 return;
9889 Expr *LHS = BinOp->getLHS();
9890 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
9891 if (DRE->getDecl() != Variable)
9892 return;
9893 if (Expr *RHS = BinOp->getRHS()) {
9894 RHS = RHS->IgnoreParenCasts();
9895 llvm::APSInt Value;
9896 VarWillBeReased =
9897 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
9898 }
9899 }
9900 }
John McCall31168b02011-06-15 23:02:42 +00009901 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009902} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +00009903
9904/// Check whether the given argument is a block which captures a
9905/// variable.
9906static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
9907 assert(owner.Variable && owner.Loc.isValid());
9908
9909 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00009910
9911 // Look through [^{...} copy] and Block_copy(^{...}).
9912 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
9913 Selector Cmd = ME->getSelector();
9914 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
9915 e = ME->getInstanceReceiver();
9916 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +00009917 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +00009918 e = e->IgnoreParenCasts();
9919 }
9920 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
9921 if (CE->getNumArgs() == 1) {
9922 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00009923 if (Fn) {
9924 const IdentifierInfo *FnI = Fn->getIdentifier();
9925 if (FnI && FnI->isStr("_Block_copy")) {
9926 e = CE->getArg(0)->IgnoreParenCasts();
9927 }
9928 }
Jordan Rose67e887c2012-09-17 17:54:30 +00009929 }
9930 }
9931
John McCall31168b02011-06-15 23:02:42 +00009932 BlockExpr *block = dyn_cast<BlockExpr>(e);
9933 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +00009934 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00009935
9936 FindCaptureVisitor visitor(S.Context, owner.Variable);
9937 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009938 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +00009939}
9940
9941static void diagnoseRetainCycle(Sema &S, Expr *capturer,
9942 RetainCycleOwner &owner) {
9943 assert(capturer);
9944 assert(owner.Variable && owner.Loc.isValid());
9945
9946 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
9947 << owner.Variable << capturer->getSourceRange();
9948 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
9949 << owner.Indirect << owner.Range;
9950}
9951
9952/// Check for a keyword selector that starts with the word 'add' or
9953/// 'set'.
9954static bool isSetterLikeSelector(Selector sel) {
9955 if (sel.isUnarySelector()) return false;
9956
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009957 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00009958 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00009959 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00009960 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00009961 else if (str.startswith("add")) {
9962 // Specially whitelist 'addOperationWithBlock:'.
9963 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
9964 return false;
9965 str = str.substr(3);
9966 }
John McCall31168b02011-06-15 23:02:42 +00009967 else
9968 return false;
9969
9970 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00009971 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00009972}
9973
Benjamin Kramer3a743452015-03-09 15:03:32 +00009974static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
9975 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009976 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
9977 Message->getReceiverInterface(),
9978 NSAPI::ClassId_NSMutableArray);
9979 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009980 return None;
9981 }
9982
9983 Selector Sel = Message->getSelector();
9984
9985 Optional<NSAPI::NSArrayMethodKind> MKOpt =
9986 S.NSAPIObj->getNSArrayMethodKind(Sel);
9987 if (!MKOpt) {
9988 return None;
9989 }
9990
9991 NSAPI::NSArrayMethodKind MK = *MKOpt;
9992
9993 switch (MK) {
9994 case NSAPI::NSMutableArr_addObject:
9995 case NSAPI::NSMutableArr_insertObjectAtIndex:
9996 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
9997 return 0;
9998 case NSAPI::NSMutableArr_replaceObjectAtIndex:
9999 return 1;
10000
10001 default:
10002 return None;
10003 }
10004
10005 return None;
10006}
10007
10008static
10009Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
10010 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010011 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
10012 Message->getReceiverInterface(),
10013 NSAPI::ClassId_NSMutableDictionary);
10014 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010015 return None;
10016 }
10017
10018 Selector Sel = Message->getSelector();
10019
10020 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
10021 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
10022 if (!MKOpt) {
10023 return None;
10024 }
10025
10026 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
10027
10028 switch (MK) {
10029 case NSAPI::NSMutableDict_setObjectForKey:
10030 case NSAPI::NSMutableDict_setValueForKey:
10031 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
10032 return 0;
10033
10034 default:
10035 return None;
10036 }
10037
10038 return None;
10039}
10040
10041static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010042 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
10043 Message->getReceiverInterface(),
10044 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +000010045
Alex Denisov5dfac812015-08-06 04:51:14 +000010046 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
10047 Message->getReceiverInterface(),
10048 NSAPI::ClassId_NSMutableOrderedSet);
10049 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010050 return None;
10051 }
10052
10053 Selector Sel = Message->getSelector();
10054
10055 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
10056 if (!MKOpt) {
10057 return None;
10058 }
10059
10060 NSAPI::NSSetMethodKind MK = *MKOpt;
10061
10062 switch (MK) {
10063 case NSAPI::NSMutableSet_addObject:
10064 case NSAPI::NSOrderedSet_setObjectAtIndex:
10065 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
10066 case NSAPI::NSOrderedSet_insertObjectAtIndex:
10067 return 0;
10068 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
10069 return 1;
10070 }
10071
10072 return None;
10073}
10074
10075void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
10076 if (!Message->isInstanceMessage()) {
10077 return;
10078 }
10079
10080 Optional<int> ArgOpt;
10081
10082 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
10083 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
10084 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
10085 return;
10086 }
10087
10088 int ArgIndex = *ArgOpt;
10089
Alex Denisove1d882c2015-03-04 17:55:52 +000010090 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
10091 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
10092 Arg = OE->getSourceExpr()->IgnoreImpCasts();
10093 }
10094
Alex Denisov5dfac812015-08-06 04:51:14 +000010095 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010096 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010097 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010098 Diag(Message->getSourceRange().getBegin(),
10099 diag::warn_objc_circular_container)
Alex Denisov5dfac812015-08-06 04:51:14 +000010100 << ArgRE->getDecl()->getName() << StringRef("super");
Alex Denisove1d882c2015-03-04 17:55:52 +000010101 }
10102 }
Alex Denisov5dfac812015-08-06 04:51:14 +000010103 } else {
10104 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
10105
10106 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
10107 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
10108 }
10109
10110 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
10111 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
10112 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
10113 ValueDecl *Decl = ReceiverRE->getDecl();
10114 Diag(Message->getSourceRange().getBegin(),
10115 diag::warn_objc_circular_container)
10116 << Decl->getName() << Decl->getName();
10117 if (!ArgRE->isObjCSelfExpr()) {
10118 Diag(Decl->getLocation(),
10119 diag::note_objc_circular_container_declared_here)
10120 << Decl->getName();
10121 }
10122 }
10123 }
10124 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
10125 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
10126 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
10127 ObjCIvarDecl *Decl = IvarRE->getDecl();
10128 Diag(Message->getSourceRange().getBegin(),
10129 diag::warn_objc_circular_container)
10130 << Decl->getName() << Decl->getName();
10131 Diag(Decl->getLocation(),
10132 diag::note_objc_circular_container_declared_here)
10133 << Decl->getName();
10134 }
Alex Denisove1d882c2015-03-04 17:55:52 +000010135 }
10136 }
10137 }
Alex Denisove1d882c2015-03-04 17:55:52 +000010138}
10139
John McCall31168b02011-06-15 23:02:42 +000010140/// Check a message send to see if it's likely to cause a retain cycle.
10141void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
10142 // Only check instance methods whose selector looks like a setter.
10143 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
10144 return;
10145
10146 // Try to find a variable that the receiver is strongly owned by.
10147 RetainCycleOwner owner;
10148 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010149 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +000010150 return;
10151 } else {
10152 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
10153 owner.Variable = getCurMethodDecl()->getSelfDecl();
10154 owner.Loc = msg->getSuperLoc();
10155 owner.Range = msg->getSuperLoc();
10156 }
10157
10158 // Check whether the receiver is captured by any of the arguments.
10159 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
10160 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
10161 return diagnoseRetainCycle(*this, capturer, owner);
10162}
10163
10164/// Check a property assign to see if it's likely to cause a retain cycle.
10165void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
10166 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010167 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +000010168 return;
10169
10170 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
10171 diagnoseRetainCycle(*this, capturer, owner);
10172}
10173
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000010174void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
10175 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +000010176 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000010177 return;
10178
10179 // Because we don't have an expression for the variable, we have to set the
10180 // location explicitly here.
10181 Owner.Loc = Var->getLocation();
10182 Owner.Range = Var->getSourceRange();
10183
10184 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
10185 diagnoseRetainCycle(*this, Capturer, Owner);
10186}
10187
Ted Kremenek9304da92012-12-21 08:04:28 +000010188static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
10189 Expr *RHS, bool isProperty) {
10190 // Check if RHS is an Objective-C object literal, which also can get
10191 // immediately zapped in a weak reference. Note that we explicitly
10192 // allow ObjCStringLiterals, since those are designed to never really die.
10193 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000010194
Ted Kremenek64873352012-12-21 22:46:35 +000010195 // This enum needs to match with the 'select' in
10196 // warn_objc_arc_literal_assign (off-by-1).
10197 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
10198 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
10199 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000010200
10201 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +000010202 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +000010203 << (isProperty ? 0 : 1)
10204 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000010205
10206 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +000010207}
10208
Ted Kremenekc1f014a2012-12-21 19:45:30 +000010209static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
10210 Qualifiers::ObjCLifetime LT,
10211 Expr *RHS, bool isProperty) {
10212 // Strip off any implicit cast added to get to the one ARC-specific.
10213 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
10214 if (cast->getCastKind() == CK_ARCConsumeObject) {
10215 S.Diag(Loc, diag::warn_arc_retained_assign)
10216 << (LT == Qualifiers::OCL_ExplicitNone)
10217 << (isProperty ? 0 : 1)
10218 << RHS->getSourceRange();
10219 return true;
10220 }
10221 RHS = cast->getSubExpr();
10222 }
10223
10224 if (LT == Qualifiers::OCL_Weak &&
10225 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
10226 return true;
10227
10228 return false;
10229}
10230
Ted Kremenekb36234d2012-12-21 08:04:20 +000010231bool Sema::checkUnsafeAssigns(SourceLocation Loc,
10232 QualType LHS, Expr *RHS) {
10233 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
10234
10235 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
10236 return false;
10237
10238 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
10239 return true;
10240
10241 return false;
10242}
10243
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010244void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
10245 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010246 QualType LHSType;
10247 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +000010248 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010249 ObjCPropertyRefExpr *PRE
10250 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
10251 if (PRE && !PRE->isImplicitProperty()) {
10252 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
10253 if (PD)
10254 LHSType = PD->getType();
10255 }
10256
10257 if (LHSType.isNull())
10258 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +000010259
10260 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
10261
10262 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010263 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +000010264 getCurFunction()->markSafeWeakUse(LHS);
10265 }
10266
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010267 if (checkUnsafeAssigns(Loc, LHSType, RHS))
10268 return;
Jordan Rose657b5f42012-09-28 22:21:35 +000010269
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010270 // FIXME. Check for other life times.
10271 if (LT != Qualifiers::OCL_None)
10272 return;
10273
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010274 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010275 if (PRE->isImplicitProperty())
10276 return;
10277 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
10278 if (!PD)
10279 return;
10280
Bill Wendling44426052012-12-20 19:22:21 +000010281 unsigned Attributes = PD->getPropertyAttributes();
10282 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010283 // when 'assign' attribute was not explicitly specified
10284 // by user, ignore it and rely on property type itself
10285 // for lifetime info.
10286 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
10287 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
10288 LHSType->isObjCRetainableType())
10289 return;
10290
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010291 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +000010292 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010293 Diag(Loc, diag::warn_arc_retained_property_assign)
10294 << RHS->getSourceRange();
10295 return;
10296 }
10297 RHS = cast->getSubExpr();
10298 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010299 }
Bill Wendling44426052012-12-20 19:22:21 +000010300 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +000010301 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
10302 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +000010303 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010304 }
10305}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010306
10307//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
10308
10309namespace {
10310bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
10311 SourceLocation StmtLoc,
10312 const NullStmt *Body) {
10313 // Do not warn if the body is a macro that expands to nothing, e.g:
10314 //
10315 // #define CALL(x)
10316 // if (condition)
10317 // CALL(0);
10318 //
10319 if (Body->hasLeadingEmptyMacro())
10320 return false;
10321
10322 // Get line numbers of statement and body.
10323 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +000010324 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010325 &StmtLineInvalid);
10326 if (StmtLineInvalid)
10327 return false;
10328
10329 bool BodyLineInvalid;
10330 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
10331 &BodyLineInvalid);
10332 if (BodyLineInvalid)
10333 return false;
10334
10335 // Warn if null statement and body are on the same line.
10336 if (StmtLine != BodyLine)
10337 return false;
10338
10339 return true;
10340}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010341} // end anonymous namespace
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010342
10343void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
10344 const Stmt *Body,
10345 unsigned DiagID) {
10346 // Since this is a syntactic check, don't emit diagnostic for template
10347 // instantiations, this just adds noise.
10348 if (CurrentInstantiationScope)
10349 return;
10350
10351 // The body should be a null statement.
10352 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
10353 if (!NBody)
10354 return;
10355
10356 // Do the usual checks.
10357 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
10358 return;
10359
10360 Diag(NBody->getSemiLoc(), DiagID);
10361 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
10362}
10363
10364void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
10365 const Stmt *PossibleBody) {
10366 assert(!CurrentInstantiationScope); // Ensured by caller
10367
10368 SourceLocation StmtLoc;
10369 const Stmt *Body;
10370 unsigned DiagID;
10371 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
10372 StmtLoc = FS->getRParenLoc();
10373 Body = FS->getBody();
10374 DiagID = diag::warn_empty_for_body;
10375 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
10376 StmtLoc = WS->getCond()->getSourceRange().getEnd();
10377 Body = WS->getBody();
10378 DiagID = diag::warn_empty_while_body;
10379 } else
10380 return; // Neither `for' nor `while'.
10381
10382 // The body should be a null statement.
10383 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
10384 if (!NBody)
10385 return;
10386
10387 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010388 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010389 return;
10390
10391 // Do the usual checks.
10392 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
10393 return;
10394
10395 // `for(...);' and `while(...);' are popular idioms, so in order to keep
10396 // noise level low, emit diagnostics only if for/while is followed by a
10397 // CompoundStmt, e.g.:
10398 // for (int i = 0; i < n; i++);
10399 // {
10400 // a(i);
10401 // }
10402 // or if for/while is followed by a statement with more indentation
10403 // than for/while itself:
10404 // for (int i = 0; i < n; i++);
10405 // a(i);
10406 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
10407 if (!ProbableTypo) {
10408 bool BodyColInvalid;
10409 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
10410 PossibleBody->getLocStart(),
10411 &BodyColInvalid);
10412 if (BodyColInvalid)
10413 return;
10414
10415 bool StmtColInvalid;
10416 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
10417 S->getLocStart(),
10418 &StmtColInvalid);
10419 if (StmtColInvalid)
10420 return;
10421
10422 if (BodyCol > StmtCol)
10423 ProbableTypo = true;
10424 }
10425
10426 if (ProbableTypo) {
10427 Diag(NBody->getSemiLoc(), DiagID);
10428 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
10429 }
10430}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010431
Richard Trieu36d0b2b2015-01-13 02:32:02 +000010432//===--- CHECK: Warn on self move with std::move. -------------------------===//
10433
10434/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
10435void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
10436 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +000010437 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
10438 return;
10439
10440 if (!ActiveTemplateInstantiations.empty())
10441 return;
10442
10443 // Strip parens and casts away.
10444 LHSExpr = LHSExpr->IgnoreParenImpCasts();
10445 RHSExpr = RHSExpr->IgnoreParenImpCasts();
10446
10447 // Check for a call expression
10448 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
10449 if (!CE || CE->getNumArgs() != 1)
10450 return;
10451
10452 // Check for a call to std::move
10453 const FunctionDecl *FD = CE->getDirectCallee();
10454 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
10455 !FD->getIdentifier()->isStr("move"))
10456 return;
10457
10458 // Get argument from std::move
10459 RHSExpr = CE->getArg(0);
10460
10461 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
10462 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
10463
10464 // Two DeclRefExpr's, check that the decls are the same.
10465 if (LHSDeclRef && RHSDeclRef) {
10466 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
10467 return;
10468 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
10469 RHSDeclRef->getDecl()->getCanonicalDecl())
10470 return;
10471
10472 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10473 << LHSExpr->getSourceRange()
10474 << RHSExpr->getSourceRange();
10475 return;
10476 }
10477
10478 // Member variables require a different approach to check for self moves.
10479 // MemberExpr's are the same if every nested MemberExpr refers to the same
10480 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
10481 // the base Expr's are CXXThisExpr's.
10482 const Expr *LHSBase = LHSExpr;
10483 const Expr *RHSBase = RHSExpr;
10484 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
10485 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
10486 if (!LHSME || !RHSME)
10487 return;
10488
10489 while (LHSME && RHSME) {
10490 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
10491 RHSME->getMemberDecl()->getCanonicalDecl())
10492 return;
10493
10494 LHSBase = LHSME->getBase();
10495 RHSBase = RHSME->getBase();
10496 LHSME = dyn_cast<MemberExpr>(LHSBase);
10497 RHSME = dyn_cast<MemberExpr>(RHSBase);
10498 }
10499
10500 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
10501 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
10502 if (LHSDeclRef && RHSDeclRef) {
10503 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
10504 return;
10505 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
10506 RHSDeclRef->getDecl()->getCanonicalDecl())
10507 return;
10508
10509 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10510 << LHSExpr->getSourceRange()
10511 << RHSExpr->getSourceRange();
10512 return;
10513 }
10514
10515 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
10516 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10517 << LHSExpr->getSourceRange()
10518 << RHSExpr->getSourceRange();
10519}
10520
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010521//===--- Layout compatibility ----------------------------------------------//
10522
10523namespace {
10524
10525bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
10526
10527/// \brief Check if two enumeration types are layout-compatible.
10528bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
10529 // C++11 [dcl.enum] p8:
10530 // Two enumeration types are layout-compatible if they have the same
10531 // underlying type.
10532 return ED1->isComplete() && ED2->isComplete() &&
10533 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
10534}
10535
10536/// \brief Check if two fields are layout-compatible.
10537bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
10538 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
10539 return false;
10540
10541 if (Field1->isBitField() != Field2->isBitField())
10542 return false;
10543
10544 if (Field1->isBitField()) {
10545 // Make sure that the bit-fields are the same length.
10546 unsigned Bits1 = Field1->getBitWidthValue(C);
10547 unsigned Bits2 = Field2->getBitWidthValue(C);
10548
10549 if (Bits1 != Bits2)
10550 return false;
10551 }
10552
10553 return true;
10554}
10555
10556/// \brief Check if two standard-layout structs are layout-compatible.
10557/// (C++11 [class.mem] p17)
10558bool isLayoutCompatibleStruct(ASTContext &C,
10559 RecordDecl *RD1,
10560 RecordDecl *RD2) {
10561 // If both records are C++ classes, check that base classes match.
10562 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
10563 // If one of records is a CXXRecordDecl we are in C++ mode,
10564 // thus the other one is a CXXRecordDecl, too.
10565 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
10566 // Check number of base classes.
10567 if (D1CXX->getNumBases() != D2CXX->getNumBases())
10568 return false;
10569
10570 // Check the base classes.
10571 for (CXXRecordDecl::base_class_const_iterator
10572 Base1 = D1CXX->bases_begin(),
10573 BaseEnd1 = D1CXX->bases_end(),
10574 Base2 = D2CXX->bases_begin();
10575 Base1 != BaseEnd1;
10576 ++Base1, ++Base2) {
10577 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
10578 return false;
10579 }
10580 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
10581 // If only RD2 is a C++ class, it should have zero base classes.
10582 if (D2CXX->getNumBases() > 0)
10583 return false;
10584 }
10585
10586 // Check the fields.
10587 RecordDecl::field_iterator Field2 = RD2->field_begin(),
10588 Field2End = RD2->field_end(),
10589 Field1 = RD1->field_begin(),
10590 Field1End = RD1->field_end();
10591 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
10592 if (!isLayoutCompatible(C, *Field1, *Field2))
10593 return false;
10594 }
10595 if (Field1 != Field1End || Field2 != Field2End)
10596 return false;
10597
10598 return true;
10599}
10600
10601/// \brief Check if two standard-layout unions are layout-compatible.
10602/// (C++11 [class.mem] p18)
10603bool isLayoutCompatibleUnion(ASTContext &C,
10604 RecordDecl *RD1,
10605 RecordDecl *RD2) {
10606 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010607 for (auto *Field2 : RD2->fields())
10608 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010609
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010610 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010611 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
10612 I = UnmatchedFields.begin(),
10613 E = UnmatchedFields.end();
10614
10615 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010616 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010617 bool Result = UnmatchedFields.erase(*I);
10618 (void) Result;
10619 assert(Result);
10620 break;
10621 }
10622 }
10623 if (I == E)
10624 return false;
10625 }
10626
10627 return UnmatchedFields.empty();
10628}
10629
10630bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
10631 if (RD1->isUnion() != RD2->isUnion())
10632 return false;
10633
10634 if (RD1->isUnion())
10635 return isLayoutCompatibleUnion(C, RD1, RD2);
10636 else
10637 return isLayoutCompatibleStruct(C, RD1, RD2);
10638}
10639
10640/// \brief Check if two types are layout-compatible in C++11 sense.
10641bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
10642 if (T1.isNull() || T2.isNull())
10643 return false;
10644
10645 // C++11 [basic.types] p11:
10646 // If two types T1 and T2 are the same type, then T1 and T2 are
10647 // layout-compatible types.
10648 if (C.hasSameType(T1, T2))
10649 return true;
10650
10651 T1 = T1.getCanonicalType().getUnqualifiedType();
10652 T2 = T2.getCanonicalType().getUnqualifiedType();
10653
10654 const Type::TypeClass TC1 = T1->getTypeClass();
10655 const Type::TypeClass TC2 = T2->getTypeClass();
10656
10657 if (TC1 != TC2)
10658 return false;
10659
10660 if (TC1 == Type::Enum) {
10661 return isLayoutCompatible(C,
10662 cast<EnumType>(T1)->getDecl(),
10663 cast<EnumType>(T2)->getDecl());
10664 } else if (TC1 == Type::Record) {
10665 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
10666 return false;
10667
10668 return isLayoutCompatible(C,
10669 cast<RecordType>(T1)->getDecl(),
10670 cast<RecordType>(T2)->getDecl());
10671 }
10672
10673 return false;
10674}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010675} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010676
10677//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
10678
10679namespace {
10680/// \brief Given a type tag expression find the type tag itself.
10681///
10682/// \param TypeExpr Type tag expression, as it appears in user's code.
10683///
10684/// \param VD Declaration of an identifier that appears in a type tag.
10685///
10686/// \param MagicValue Type tag magic value.
10687bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
10688 const ValueDecl **VD, uint64_t *MagicValue) {
10689 while(true) {
10690 if (!TypeExpr)
10691 return false;
10692
10693 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
10694
10695 switch (TypeExpr->getStmtClass()) {
10696 case Stmt::UnaryOperatorClass: {
10697 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
10698 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
10699 TypeExpr = UO->getSubExpr();
10700 continue;
10701 }
10702 return false;
10703 }
10704
10705 case Stmt::DeclRefExprClass: {
10706 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
10707 *VD = DRE->getDecl();
10708 return true;
10709 }
10710
10711 case Stmt::IntegerLiteralClass: {
10712 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
10713 llvm::APInt MagicValueAPInt = IL->getValue();
10714 if (MagicValueAPInt.getActiveBits() <= 64) {
10715 *MagicValue = MagicValueAPInt.getZExtValue();
10716 return true;
10717 } else
10718 return false;
10719 }
10720
10721 case Stmt::BinaryConditionalOperatorClass:
10722 case Stmt::ConditionalOperatorClass: {
10723 const AbstractConditionalOperator *ACO =
10724 cast<AbstractConditionalOperator>(TypeExpr);
10725 bool Result;
10726 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
10727 if (Result)
10728 TypeExpr = ACO->getTrueExpr();
10729 else
10730 TypeExpr = ACO->getFalseExpr();
10731 continue;
10732 }
10733 return false;
10734 }
10735
10736 case Stmt::BinaryOperatorClass: {
10737 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
10738 if (BO->getOpcode() == BO_Comma) {
10739 TypeExpr = BO->getRHS();
10740 continue;
10741 }
10742 return false;
10743 }
10744
10745 default:
10746 return false;
10747 }
10748 }
10749}
10750
10751/// \brief Retrieve the C type corresponding to type tag TypeExpr.
10752///
10753/// \param TypeExpr Expression that specifies a type tag.
10754///
10755/// \param MagicValues Registered magic values.
10756///
10757/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
10758/// kind.
10759///
10760/// \param TypeInfo Information about the corresponding C type.
10761///
10762/// \returns true if the corresponding C type was found.
10763bool GetMatchingCType(
10764 const IdentifierInfo *ArgumentKind,
10765 const Expr *TypeExpr, const ASTContext &Ctx,
10766 const llvm::DenseMap<Sema::TypeTagMagicValue,
10767 Sema::TypeTagData> *MagicValues,
10768 bool &FoundWrongKind,
10769 Sema::TypeTagData &TypeInfo) {
10770 FoundWrongKind = false;
10771
10772 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000010773 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010774
10775 uint64_t MagicValue;
10776
10777 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
10778 return false;
10779
10780 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000010781 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010782 if (I->getArgumentKind() != ArgumentKind) {
10783 FoundWrongKind = true;
10784 return false;
10785 }
10786 TypeInfo.Type = I->getMatchingCType();
10787 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
10788 TypeInfo.MustBeNull = I->getMustBeNull();
10789 return true;
10790 }
10791 return false;
10792 }
10793
10794 if (!MagicValues)
10795 return false;
10796
10797 llvm::DenseMap<Sema::TypeTagMagicValue,
10798 Sema::TypeTagData>::const_iterator I =
10799 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
10800 if (I == MagicValues->end())
10801 return false;
10802
10803 TypeInfo = I->second;
10804 return true;
10805}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010806} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010807
10808void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
10809 uint64_t MagicValue, QualType Type,
10810 bool LayoutCompatible,
10811 bool MustBeNull) {
10812 if (!TypeTagForDatatypeMagicValues)
10813 TypeTagForDatatypeMagicValues.reset(
10814 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
10815
10816 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
10817 (*TypeTagForDatatypeMagicValues)[Magic] =
10818 TypeTagData(Type, LayoutCompatible, MustBeNull);
10819}
10820
10821namespace {
10822bool IsSameCharType(QualType T1, QualType T2) {
10823 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
10824 if (!BT1)
10825 return false;
10826
10827 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
10828 if (!BT2)
10829 return false;
10830
10831 BuiltinType::Kind T1Kind = BT1->getKind();
10832 BuiltinType::Kind T2Kind = BT2->getKind();
10833
10834 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
10835 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
10836 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
10837 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
10838}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010839} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010840
10841void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
10842 const Expr * const *ExprArgs) {
10843 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
10844 bool IsPointerAttr = Attr->getIsPointer();
10845
10846 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
10847 bool FoundWrongKind;
10848 TypeTagData TypeInfo;
10849 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
10850 TypeTagForDatatypeMagicValues.get(),
10851 FoundWrongKind, TypeInfo)) {
10852 if (FoundWrongKind)
10853 Diag(TypeTagExpr->getExprLoc(),
10854 diag::warn_type_tag_for_datatype_wrong_kind)
10855 << TypeTagExpr->getSourceRange();
10856 return;
10857 }
10858
10859 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
10860 if (IsPointerAttr) {
10861 // Skip implicit cast of pointer to `void *' (as a function argument).
10862 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000010863 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000010864 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010865 ArgumentExpr = ICE->getSubExpr();
10866 }
10867 QualType ArgumentType = ArgumentExpr->getType();
10868
10869 // Passing a `void*' pointer shouldn't trigger a warning.
10870 if (IsPointerAttr && ArgumentType->isVoidPointerType())
10871 return;
10872
10873 if (TypeInfo.MustBeNull) {
10874 // Type tag with matching void type requires a null pointer.
10875 if (!ArgumentExpr->isNullPointerConstant(Context,
10876 Expr::NPC_ValueDependentIsNotNull)) {
10877 Diag(ArgumentExpr->getExprLoc(),
10878 diag::warn_type_safety_null_pointer_required)
10879 << ArgumentKind->getName()
10880 << ArgumentExpr->getSourceRange()
10881 << TypeTagExpr->getSourceRange();
10882 }
10883 return;
10884 }
10885
10886 QualType RequiredType = TypeInfo.Type;
10887 if (IsPointerAttr)
10888 RequiredType = Context.getPointerType(RequiredType);
10889
10890 bool mismatch = false;
10891 if (!TypeInfo.LayoutCompatible) {
10892 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
10893
10894 // C++11 [basic.fundamental] p1:
10895 // Plain char, signed char, and unsigned char are three distinct types.
10896 //
10897 // But we treat plain `char' as equivalent to `signed char' or `unsigned
10898 // char' depending on the current char signedness mode.
10899 if (mismatch)
10900 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
10901 RequiredType->getPointeeType())) ||
10902 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
10903 mismatch = false;
10904 } else
10905 if (IsPointerAttr)
10906 mismatch = !isLayoutCompatible(Context,
10907 ArgumentType->getPointeeType(),
10908 RequiredType->getPointeeType());
10909 else
10910 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
10911
10912 if (mismatch)
10913 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000010914 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010915 << TypeInfo.LayoutCompatible << RequiredType
10916 << ArgumentExpr->getSourceRange()
10917 << TypeTagExpr->getSourceRange();
10918}