blob: fd90121bfe34b511724e15df8b4d3af978f2bc4c [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
Chris Lattnerb87b1b32007-08-10 20:18:51 +000015#include "clang/AST/ASTContext.h"
Ken Dyck40775002010-01-11 17:06:35 +000016#include "clang/AST/CharUnits.h"
John McCall28a0cf72010-08-25 07:42:41 +000017#include "clang/AST/DeclCXX.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/AST/EvaluatedExprVisitor.h"
David Blaikie7555b6a2012-05-15 16:56:36 +000020#include "clang/AST/Expr.h"
Ted Kremenekc81614d2007-08-20 16:18:38 +000021#include "clang/AST/ExprCXX.h"
Ted Kremenek34f664d2008-06-16 18:00:42 +000022#include "clang/AST/ExprObjC.h"
Alexey Bataev1a3320e2015-08-25 14:24:04 +000023#include "clang/AST/ExprOpenMP.h"
Mike Stump0c2ec772010-01-21 03:59:47 +000024#include "clang/AST/StmtCXX.h"
25#include "clang/AST/StmtObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/Analysis/Analyses/FormatString.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000027#include "clang/Basic/CharInfo.h"
Eric Christopher8d0c6212010-04-17 02:26:23 +000028#include "clang/Basic/TargetBuiltins.h"
Nate Begeman4904e322010-06-08 02:47:44 +000029#include "clang/Basic/TargetInfo.h"
Alp Tokerb6cc5922014-05-03 03:45:55 +000030#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
Chandler Carruth3a022472012-12-04 09:13:33 +000031#include "clang/Sema/Initialization.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "clang/Sema/Lookup.h"
33#include "clang/Sema/ScopeInfo.h"
34#include "clang/Sema/Sema.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000035#include "clang/Sema/SemaInternal.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"
Mehdi Amini9670f842016-07-18 19:02:11 +000039#include "llvm/Support/ConvertUTF.h"
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +000040#include "llvm/Support/Format.h"
41#include "llvm/Support/Locale.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000042#include "llvm/Support/raw_ostream.h"
Eugene Zelenko1ced5092016-02-12 22:53:10 +000043
Chris Lattnerb87b1b32007-08-10 20:18:51 +000044using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000045using namespace sema;
Chris Lattnerb87b1b32007-08-10 20:18:51 +000046
Chris Lattnera26fb342009-02-18 17:49:48 +000047SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
48 unsigned ByteNo) const {
Alp Tokerb6cc5922014-05-03 03:45:55 +000049 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
50 Context.getTargetInfo());
Chris Lattnera26fb342009-02-18 17:49:48 +000051}
52
John McCallbebede42011-02-26 05:39:39 +000053/// Checks that a call expression's argument count is the desired number.
54/// This is useful when doing custom type-checking. Returns true on error.
55static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
56 unsigned argCount = call->getNumArgs();
57 if (argCount == desiredArgCount) return false;
58
59 if (argCount < desiredArgCount)
60 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
61 << 0 /*function call*/ << desiredArgCount << argCount
62 << call->getSourceRange();
63
64 // Highlight all the excess arguments.
65 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
66 call->getArg(argCount - 1)->getLocEnd());
67
68 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
69 << 0 /*function call*/ << desiredArgCount << argCount
70 << call->getArg(1)->getSourceRange();
71}
72
Julien Lerouge4a5b4442012-04-28 17:39:16 +000073/// Check that the first argument to __builtin_annotation is an integer
74/// and the second argument is a non-wide string literal.
75static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
76 if (checkArgCount(S, TheCall, 2))
77 return true;
78
79 // First argument should be an integer.
80 Expr *ValArg = TheCall->getArg(0);
81 QualType Ty = ValArg->getType();
82 if (!Ty->isIntegerType()) {
83 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
84 << ValArg->getSourceRange();
Julien Lerouge5a6b6982011-09-09 22:41:49 +000085 return true;
86 }
Julien Lerouge4a5b4442012-04-28 17:39:16 +000087
88 // Second argument should be a constant string.
89 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
90 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
91 if (!Literal || !Literal->isAscii()) {
92 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
93 << StrArg->getSourceRange();
94 return true;
95 }
96
97 TheCall->setType(Ty);
Julien Lerouge5a6b6982011-09-09 22:41:49 +000098 return false;
99}
100
Richard Smith6cbd65d2013-07-11 02:27:57 +0000101/// Check that the argument to __builtin_addressof is a glvalue, and set the
102/// result type to the corresponding pointer type.
103static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
104 if (checkArgCount(S, TheCall, 1))
105 return true;
106
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000107 ExprResult Arg(TheCall->getArg(0));
Richard Smith6cbd65d2013-07-11 02:27:57 +0000108 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
109 if (ResultType.isNull())
110 return true;
111
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000112 TheCall->setArg(0, Arg.get());
Richard Smith6cbd65d2013-07-11 02:27:57 +0000113 TheCall->setType(ResultType);
114 return false;
115}
116
John McCall03107a42015-10-29 20:48:01 +0000117static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
118 if (checkArgCount(S, TheCall, 3))
119 return true;
120
121 // First two arguments should be integers.
122 for (unsigned I = 0; I < 2; ++I) {
123 Expr *Arg = TheCall->getArg(I);
124 QualType Ty = Arg->getType();
125 if (!Ty->isIntegerType()) {
126 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
127 << Ty << Arg->getSourceRange();
128 return true;
129 }
130 }
131
132 // Third argument should be a pointer to a non-const integer.
133 // IRGen correctly handles volatile, restrict, and address spaces, and
134 // the other qualifiers aren't possible.
135 {
136 Expr *Arg = TheCall->getArg(2);
137 QualType Ty = Arg->getType();
138 const auto *PtrTy = Ty->getAs<PointerType>();
139 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
140 !PtrTy->getPointeeType().isConstQualified())) {
141 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
142 << Ty << Arg->getSourceRange();
143 return true;
144 }
145 }
146
147 return false;
148}
149
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000150static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
151 CallExpr *TheCall, unsigned SizeIdx,
152 unsigned DstSizeIdx) {
153 if (TheCall->getNumArgs() <= SizeIdx ||
154 TheCall->getNumArgs() <= DstSizeIdx)
155 return;
156
157 const Expr *SizeArg = TheCall->getArg(SizeIdx);
158 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
159
160 llvm::APSInt Size, DstSize;
161
162 // find out if both sizes are known at compile time
163 if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
164 !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
165 return;
166
167 if (Size.ule(DstSize))
168 return;
169
170 // confirmed overflow so generate the diagnostic.
171 IdentifierInfo *FnName = FDecl->getIdentifier();
172 SourceLocation SL = TheCall->getLocStart();
173 SourceRange SR = TheCall->getSourceRange();
174
175 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
176}
177
Peter Collingbournef7706832014-12-12 23:41:25 +0000178static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
179 if (checkArgCount(S, BuiltinCall, 2))
180 return true;
181
182 SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
183 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
184 Expr *Call = BuiltinCall->getArg(0);
185 Expr *Chain = BuiltinCall->getArg(1);
186
187 if (Call->getStmtClass() != Stmt::CallExprClass) {
188 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
189 << Call->getSourceRange();
190 return true;
191 }
192
193 auto CE = cast<CallExpr>(Call);
194 if (CE->getCallee()->getType()->isBlockPointerType()) {
195 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
196 << Call->getSourceRange();
197 return true;
198 }
199
200 const Decl *TargetDecl = CE->getCalleeDecl();
201 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
202 if (FD->getBuiltinID()) {
203 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
204 << Call->getSourceRange();
205 return true;
206 }
207
208 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
209 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
210 << Call->getSourceRange();
211 return true;
212 }
213
214 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
215 if (ChainResult.isInvalid())
216 return true;
217 if (!ChainResult.get()->getType()->isPointerType()) {
218 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
219 << Chain->getSourceRange();
220 return true;
221 }
222
David Majnemerced8bdf2015-02-25 17:36:15 +0000223 QualType ReturnTy = CE->getCallReturnType(S.Context);
Peter Collingbournef7706832014-12-12 23:41:25 +0000224 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
225 QualType BuiltinTy = S.Context.getFunctionType(
226 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
227 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
228
229 Builtin =
230 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
231
232 BuiltinCall->setType(CE->getType());
233 BuiltinCall->setValueKind(CE->getValueKind());
234 BuiltinCall->setObjectKind(CE->getObjectKind());
235 BuiltinCall->setCallee(Builtin);
236 BuiltinCall->setArg(1, ChainResult.get());
237
238 return false;
239}
240
Reid Kleckner1d59f992015-01-22 01:36:17 +0000241static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
242 Scope::ScopeFlags NeededScopeFlags,
243 unsigned DiagID) {
244 // Scopes aren't available during instantiation. Fortunately, builtin
245 // functions cannot be template args so they cannot be formed through template
246 // instantiation. Therefore checking once during the parse is sufficient.
247 if (!SemaRef.ActiveTemplateInstantiations.empty())
248 return false;
249
250 Scope *S = SemaRef.getCurScope();
251 while (S && !S->isSEHExceptScope())
252 S = S->getParent();
253 if (!S || !(S->getFlags() & NeededScopeFlags)) {
254 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
255 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
256 << DRE->getDecl()->getIdentifier();
257 return true;
258 }
259
260 return false;
261}
262
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000263static inline bool isBlockPointer(Expr *Arg) {
264 return Arg->getType()->isBlockPointerType();
265}
266
267/// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
268/// void*, which is a requirement of device side enqueue.
269static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
270 const BlockPointerType *BPT =
271 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
272 ArrayRef<QualType> Params =
273 BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
274 unsigned ArgCounter = 0;
275 bool IllegalParams = false;
276 // Iterate through the block parameters until either one is found that is not
277 // a local void*, or the block is valid.
278 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
279 I != E; ++I, ++ArgCounter) {
280 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
281 (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
282 LangAS::opencl_local) {
283 // Get the location of the error. If a block literal has been passed
284 // (BlockExpr) then we can point straight to the offending argument,
285 // else we just point to the variable reference.
286 SourceLocation ErrorLoc;
287 if (isa<BlockExpr>(BlockArg)) {
288 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
289 ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart();
290 } else if (isa<DeclRefExpr>(BlockArg)) {
291 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart();
292 }
293 S.Diag(ErrorLoc,
294 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
295 IllegalParams = true;
296 }
297 }
298
299 return IllegalParams;
300}
301
302/// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
303/// get_kernel_work_group_size
304/// and get_kernel_preferred_work_group_size_multiple builtin functions.
305static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
306 if (checkArgCount(S, TheCall, 1))
307 return true;
308
309 Expr *BlockArg = TheCall->getArg(0);
310 if (!isBlockPointer(BlockArg)) {
311 S.Diag(BlockArg->getLocStart(),
312 diag::err_opencl_enqueue_kernel_expected_type) << "block";
313 return true;
314 }
315 return checkOpenCLBlockArgs(S, BlockArg);
316}
317
318static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
319 unsigned Start, unsigned End);
320
321/// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
322/// 'local void*' parameter of passed block.
323static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
324 Expr *BlockArg,
325 unsigned NumNonVarArgs) {
326 const BlockPointerType *BPT =
327 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
328 unsigned NumBlockParams =
329 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
330 unsigned TotalNumArgs = TheCall->getNumArgs();
331
332 // For each argument passed to the block, a corresponding uint needs to
333 // be passed to describe the size of the local memory.
334 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
335 S.Diag(TheCall->getLocStart(),
336 diag::err_opencl_enqueue_kernel_local_size_args);
337 return true;
338 }
339
340 // Check that the sizes of the local memory are specified by integers.
341 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
342 TotalNumArgs - 1);
343}
344
345/// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
346/// overload formats specified in Table 6.13.17.1.
347/// int enqueue_kernel(queue_t queue,
348/// kernel_enqueue_flags_t flags,
349/// const ndrange_t ndrange,
350/// void (^block)(void))
351/// int enqueue_kernel(queue_t queue,
352/// kernel_enqueue_flags_t flags,
353/// const ndrange_t ndrange,
354/// uint num_events_in_wait_list,
355/// clk_event_t *event_wait_list,
356/// clk_event_t *event_ret,
357/// void (^block)(void))
358/// int enqueue_kernel(queue_t queue,
359/// kernel_enqueue_flags_t flags,
360/// const ndrange_t ndrange,
361/// void (^block)(local void*, ...),
362/// uint size0, ...)
363/// int enqueue_kernel(queue_t queue,
364/// kernel_enqueue_flags_t flags,
365/// const ndrange_t ndrange,
366/// uint num_events_in_wait_list,
367/// clk_event_t *event_wait_list,
368/// clk_event_t *event_ret,
369/// void (^block)(local void*, ...),
370/// uint size0, ...)
371static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
372 unsigned NumArgs = TheCall->getNumArgs();
373
374 if (NumArgs < 4) {
375 S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args);
376 return true;
377 }
378
379 Expr *Arg0 = TheCall->getArg(0);
380 Expr *Arg1 = TheCall->getArg(1);
381 Expr *Arg2 = TheCall->getArg(2);
382 Expr *Arg3 = TheCall->getArg(3);
383
384 // First argument always needs to be a queue_t type.
385 if (!Arg0->getType()->isQueueT()) {
386 S.Diag(TheCall->getArg(0)->getLocStart(),
387 diag::err_opencl_enqueue_kernel_expected_type)
388 << S.Context.OCLQueueTy;
389 return true;
390 }
391
392 // Second argument always needs to be a kernel_enqueue_flags_t enum value.
393 if (!Arg1->getType()->isIntegerType()) {
394 S.Diag(TheCall->getArg(1)->getLocStart(),
395 diag::err_opencl_enqueue_kernel_expected_type)
396 << "'kernel_enqueue_flags_t' (i.e. uint)";
397 return true;
398 }
399
400 // Third argument is always an ndrange_t type.
401 if (!Arg2->getType()->isNDRangeT()) {
402 S.Diag(TheCall->getArg(2)->getLocStart(),
403 diag::err_opencl_enqueue_kernel_expected_type)
404 << S.Context.OCLNDRangeTy;
405 return true;
406 }
407
408 // With four arguments, there is only one form that the function could be
409 // called in: no events and no variable arguments.
410 if (NumArgs == 4) {
411 // check that the last argument is the right block type.
412 if (!isBlockPointer(Arg3)) {
413 S.Diag(Arg3->getLocStart(), diag::err_opencl_enqueue_kernel_expected_type)
414 << "block";
415 return true;
416 }
417 // we have a block type, check the prototype
418 const BlockPointerType *BPT =
419 cast<BlockPointerType>(Arg3->getType().getCanonicalType());
420 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
421 S.Diag(Arg3->getLocStart(),
422 diag::err_opencl_enqueue_kernel_blocks_no_args);
423 return true;
424 }
425 return false;
426 }
427 // we can have block + varargs.
428 if (isBlockPointer(Arg3))
429 return (checkOpenCLBlockArgs(S, Arg3) ||
430 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
431 // last two cases with either exactly 7 args or 7 args and varargs.
432 if (NumArgs >= 7) {
433 // check common block argument.
434 Expr *Arg6 = TheCall->getArg(6);
435 if (!isBlockPointer(Arg6)) {
436 S.Diag(Arg6->getLocStart(), diag::err_opencl_enqueue_kernel_expected_type)
437 << "block";
438 return true;
439 }
440 if (checkOpenCLBlockArgs(S, Arg6))
441 return true;
442
443 // Forth argument has to be any integer type.
444 if (!Arg3->getType()->isIntegerType()) {
445 S.Diag(TheCall->getArg(3)->getLocStart(),
446 diag::err_opencl_enqueue_kernel_expected_type)
447 << "integer";
448 return true;
449 }
450 // check remaining common arguments.
451 Expr *Arg4 = TheCall->getArg(4);
452 Expr *Arg5 = TheCall->getArg(5);
453
454 // Fith argument is always passed as pointers to clk_event_t.
455 if (!Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
456 S.Diag(TheCall->getArg(4)->getLocStart(),
457 diag::err_opencl_enqueue_kernel_expected_type)
458 << S.Context.getPointerType(S.Context.OCLClkEventTy);
459 return true;
460 }
461
462 // Sixth argument is always passed as pointers to clk_event_t.
463 if (!(Arg5->getType()->isPointerType() &&
464 Arg5->getType()->getPointeeType()->isClkEventT())) {
465 S.Diag(TheCall->getArg(5)->getLocStart(),
466 diag::err_opencl_enqueue_kernel_expected_type)
467 << S.Context.getPointerType(S.Context.OCLClkEventTy);
468 return true;
469 }
470
471 if (NumArgs == 7)
472 return false;
473
474 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
475 }
476
477 // None of the specific case has been detected, give generic error
478 S.Diag(TheCall->getLocStart(),
479 diag::err_opencl_enqueue_kernel_incorrect_args);
480 return true;
481}
482
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000483/// Returns OpenCL access qual.
Xiuli Pan11e13f62016-02-26 03:13:03 +0000484static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
Xiuli Pan11e13f62016-02-26 03:13:03 +0000485 return D->getAttr<OpenCLAccessAttr>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000486}
487
488/// Returns true if pipe element type is different from the pointer.
489static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
490 const Expr *Arg0 = Call->getArg(0);
491 // First argument type should always be pipe.
492 if (!Arg0->getType()->isPipeType()) {
493 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000494 << Call->getDirectCallee() << Arg0->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000495 return true;
496 }
Xiuli Pan11e13f62016-02-26 03:13:03 +0000497 OpenCLAccessAttr *AccessQual =
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000498 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
499 // Validates the access qualifier is compatible with the call.
500 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
501 // read_only and write_only, and assumed to be read_only if no qualifier is
502 // specified.
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000503 switch (Call->getDirectCallee()->getBuiltinID()) {
504 case Builtin::BIread_pipe:
505 case Builtin::BIreserve_read_pipe:
506 case Builtin::BIcommit_read_pipe:
507 case Builtin::BIwork_group_reserve_read_pipe:
508 case Builtin::BIsub_group_reserve_read_pipe:
509 case Builtin::BIwork_group_commit_read_pipe:
510 case Builtin::BIsub_group_commit_read_pipe:
511 if (!(!AccessQual || AccessQual->isReadOnly())) {
512 S.Diag(Arg0->getLocStart(),
513 diag::err_opencl_builtin_pipe_invalid_access_modifier)
514 << "read_only" << Arg0->getSourceRange();
515 return true;
516 }
517 break;
518 case Builtin::BIwrite_pipe:
519 case Builtin::BIreserve_write_pipe:
520 case Builtin::BIcommit_write_pipe:
521 case Builtin::BIwork_group_reserve_write_pipe:
522 case Builtin::BIsub_group_reserve_write_pipe:
523 case Builtin::BIwork_group_commit_write_pipe:
524 case Builtin::BIsub_group_commit_write_pipe:
525 if (!(AccessQual && AccessQual->isWriteOnly())) {
526 S.Diag(Arg0->getLocStart(),
527 diag::err_opencl_builtin_pipe_invalid_access_modifier)
528 << "write_only" << Arg0->getSourceRange();
529 return true;
530 }
531 break;
532 default:
533 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000534 }
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000535 return false;
536}
537
538/// Returns true if pipe element type is different from the pointer.
539static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
540 const Expr *Arg0 = Call->getArg(0);
541 const Expr *ArgIdx = Call->getArg(Idx);
542 const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000543 const QualType EltTy = PipeTy->getElementType();
544 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000545 // The Idx argument should be a pointer and the type of the pointer and
546 // the type of pipe element should also be the same.
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000547 if (!ArgTy ||
548 !S.Context.hasSameType(
549 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000550 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000551 << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000552 << ArgIdx->getType() << ArgIdx->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000553 return true;
554 }
555 return false;
556}
557
558// \brief Performs semantic analysis for the read/write_pipe call.
559// \param S Reference to the semantic analyzer.
560// \param Call A pointer to the builtin call.
561// \return True if a semantic error has been found, false otherwise.
562static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000563 // OpenCL v2.0 s6.13.16.2 - The built-in read/write
564 // functions have two forms.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000565 switch (Call->getNumArgs()) {
566 case 2: {
567 if (checkOpenCLPipeArg(S, Call))
568 return true;
569 // The call with 2 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000570 // read/write_pipe(pipe T, T*).
571 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000572 if (checkOpenCLPipePacketType(S, Call, 1))
573 return true;
574 } break;
575
576 case 4: {
577 if (checkOpenCLPipeArg(S, Call))
578 return true;
579 // The call with 4 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000580 // read/write_pipe(pipe T, reserve_id_t, uint, T*).
581 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000582 if (!Call->getArg(1)->getType()->isReserveIDT()) {
583 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000584 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000585 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000586 return true;
587 }
588
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000589 // Check the index.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000590 const Expr *Arg2 = Call->getArg(2);
591 if (!Arg2->getType()->isIntegerType() &&
592 !Arg2->getType()->isUnsignedIntegerType()) {
593 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000594 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000595 << Arg2->getType() << Arg2->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000596 return true;
597 }
598
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000599 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000600 if (checkOpenCLPipePacketType(S, Call, 3))
601 return true;
602 } break;
603 default:
604 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000605 << Call->getDirectCallee() << Call->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000606 return true;
607 }
608
609 return false;
610}
611
612// \brief Performs a semantic analysis on the {work_group_/sub_group_
613// /_}reserve_{read/write}_pipe
614// \param S Reference to the semantic analyzer.
615// \param Call The call to the builtin function to be analyzed.
616// \return True if a semantic error was found, false otherwise.
617static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
618 if (checkArgCount(S, Call, 2))
619 return true;
620
621 if (checkOpenCLPipeArg(S, Call))
622 return true;
623
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000624 // Check the reserve size.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000625 if (!Call->getArg(1)->getType()->isIntegerType() &&
626 !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
627 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000628 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000629 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000630 return true;
631 }
632
633 return false;
634}
635
636// \brief Performs a semantic analysis on {work_group_/sub_group_
637// /_}commit_{read/write}_pipe
638// \param S Reference to the semantic analyzer.
639// \param Call The call to the builtin function to be analyzed.
640// \return True if a semantic error was found, false otherwise.
641static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
642 if (checkArgCount(S, Call, 2))
643 return true;
644
645 if (checkOpenCLPipeArg(S, Call))
646 return true;
647
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000648 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000649 if (!Call->getArg(1)->getType()->isReserveIDT()) {
650 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000651 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000652 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000653 return true;
654 }
655
656 return false;
657}
658
659// \brief Performs a semantic analysis on the call to built-in Pipe
660// Query Functions.
661// \param S Reference to the semantic analyzer.
662// \param Call The call to the builtin function to be analyzed.
663// \return True if a semantic error was found, false otherwise.
664static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
665 if (checkArgCount(S, Call, 1))
666 return true;
667
668 if (!Call->getArg(0)->getType()->isPipeType()) {
669 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000670 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000671 return true;
672 }
673
674 return false;
675}
Anastasia Stulova7f8d6dc2016-07-04 16:07:18 +0000676// \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions.
Yaxun Liuf7449a12016-05-20 19:54:38 +0000677// \brief Performs semantic analysis for the to_global/local/private call.
678// \param S Reference to the semantic analyzer.
679// \param BuiltinID ID of the builtin function.
680// \param Call A pointer to the builtin call.
681// \return True if a semantic error has been found, false otherwise.
682static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
683 CallExpr *Call) {
Yaxun Liuf7449a12016-05-20 19:54:38 +0000684 if (Call->getNumArgs() != 1) {
685 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
686 << Call->getDirectCallee() << Call->getSourceRange();
687 return true;
688 }
689
690 auto RT = Call->getArg(0)->getType();
691 if (!RT->isPointerType() || RT->getPointeeType()
692 .getAddressSpace() == LangAS::opencl_constant) {
693 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
694 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
695 return true;
696 }
697
698 RT = RT->getPointeeType();
699 auto Qual = RT.getQualifiers();
700 switch (BuiltinID) {
701 case Builtin::BIto_global:
702 Qual.setAddressSpace(LangAS::opencl_global);
703 break;
704 case Builtin::BIto_local:
705 Qual.setAddressSpace(LangAS::opencl_local);
706 break;
707 default:
708 Qual.removeAddressSpace();
709 }
710 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
711 RT.getUnqualifiedType(), Qual)));
712
713 return false;
714}
715
John McCalldadc5752010-08-24 06:29:42 +0000716ExprResult
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000717Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
718 CallExpr *TheCall) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000719 ExprResult TheCallResult(TheCall);
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000720
Chris Lattner3be167f2010-10-01 23:23:24 +0000721 // Find out if any arguments are required to be integer constant expressions.
722 unsigned ICEArguments = 0;
723 ASTContext::GetBuiltinTypeError Error;
724 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
725 if (Error != ASTContext::GE_None)
726 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
727
728 // If any arguments are required to be ICE's, check and diagnose.
729 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
730 // Skip arguments not required to be ICE's.
731 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
732
733 llvm::APSInt Result;
734 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
735 return true;
736 ICEArguments &= ~(1 << ArgNo);
737 }
738
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000739 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000740 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000741 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000742 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000743 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000744 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000745 break;
Ted Kremeneka174c522008-07-09 17:58:53 +0000746 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000747 case Builtin::BI__builtin_va_start:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000748 if (SemaBuiltinVAStart(TheCall))
749 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000750 break;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000751 case Builtin::BI__va_start: {
752 switch (Context.getTargetInfo().getTriple().getArch()) {
753 case llvm::Triple::arm:
754 case llvm::Triple::thumb:
755 if (SemaBuiltinVAStartARM(TheCall))
756 return ExprError();
757 break;
758 default:
759 if (SemaBuiltinVAStart(TheCall))
760 return ExprError();
761 break;
762 }
763 break;
764 }
Chris Lattner2da14fb2007-12-20 00:26:33 +0000765 case Builtin::BI__builtin_isgreater:
766 case Builtin::BI__builtin_isgreaterequal:
767 case Builtin::BI__builtin_isless:
768 case Builtin::BI__builtin_islessequal:
769 case Builtin::BI__builtin_islessgreater:
770 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000771 if (SemaBuiltinUnorderedCompare(TheCall))
772 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000773 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000774 case Builtin::BI__builtin_fpclassify:
775 if (SemaBuiltinFPClassification(TheCall, 6))
776 return ExprError();
777 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000778 case Builtin::BI__builtin_isfinite:
779 case Builtin::BI__builtin_isinf:
780 case Builtin::BI__builtin_isinf_sign:
781 case Builtin::BI__builtin_isnan:
782 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000783 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000784 return ExprError();
785 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000786 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000787 return SemaBuiltinShuffleVector(TheCall);
788 // TheCall will be freed by the smart pointer here, but that's fine, since
789 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000790 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000791 if (SemaBuiltinPrefetch(TheCall))
792 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000793 break;
Hal Finkelf0417332014-07-17 14:25:55 +0000794 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +0000795 case Builtin::BI__builtin_assume:
Hal Finkelf0417332014-07-17 14:25:55 +0000796 if (SemaBuiltinAssume(TheCall))
797 return ExprError();
798 break;
Hal Finkelbcc06082014-09-07 22:58:14 +0000799 case Builtin::BI__builtin_assume_aligned:
800 if (SemaBuiltinAssumeAligned(TheCall))
801 return ExprError();
802 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000803 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000804 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000805 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000806 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000807 case Builtin::BI__builtin_longjmp:
808 if (SemaBuiltinLongjmp(TheCall))
809 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000810 break;
Joerg Sonnenberger27173282015-03-11 23:46:32 +0000811 case Builtin::BI__builtin_setjmp:
812 if (SemaBuiltinSetjmp(TheCall))
813 return ExprError();
814 break;
David Majnemerc403a1c2015-03-20 17:03:35 +0000815 case Builtin::BI_setjmp:
816 case Builtin::BI_setjmpex:
817 if (checkArgCount(*this, TheCall, 1))
818 return true;
819 break;
John McCallbebede42011-02-26 05:39:39 +0000820
821 case Builtin::BI__builtin_classify_type:
822 if (checkArgCount(*this, TheCall, 1)) return true;
823 TheCall->setType(Context.IntTy);
824 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000825 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000826 if (checkArgCount(*this, TheCall, 1)) return true;
827 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000828 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000829 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000830 case Builtin::BI__sync_fetch_and_add_1:
831 case Builtin::BI__sync_fetch_and_add_2:
832 case Builtin::BI__sync_fetch_and_add_4:
833 case Builtin::BI__sync_fetch_and_add_8:
834 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000835 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000836 case Builtin::BI__sync_fetch_and_sub_1:
837 case Builtin::BI__sync_fetch_and_sub_2:
838 case Builtin::BI__sync_fetch_and_sub_4:
839 case Builtin::BI__sync_fetch_and_sub_8:
840 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000841 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000842 case Builtin::BI__sync_fetch_and_or_1:
843 case Builtin::BI__sync_fetch_and_or_2:
844 case Builtin::BI__sync_fetch_and_or_4:
845 case Builtin::BI__sync_fetch_and_or_8:
846 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000847 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000848 case Builtin::BI__sync_fetch_and_and_1:
849 case Builtin::BI__sync_fetch_and_and_2:
850 case Builtin::BI__sync_fetch_and_and_4:
851 case Builtin::BI__sync_fetch_and_and_8:
852 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000853 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000854 case Builtin::BI__sync_fetch_and_xor_1:
855 case Builtin::BI__sync_fetch_and_xor_2:
856 case Builtin::BI__sync_fetch_and_xor_4:
857 case Builtin::BI__sync_fetch_and_xor_8:
858 case Builtin::BI__sync_fetch_and_xor_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000859 case Builtin::BI__sync_fetch_and_nand:
860 case Builtin::BI__sync_fetch_and_nand_1:
861 case Builtin::BI__sync_fetch_and_nand_2:
862 case Builtin::BI__sync_fetch_and_nand_4:
863 case Builtin::BI__sync_fetch_and_nand_8:
864 case Builtin::BI__sync_fetch_and_nand_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000865 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000866 case Builtin::BI__sync_add_and_fetch_1:
867 case Builtin::BI__sync_add_and_fetch_2:
868 case Builtin::BI__sync_add_and_fetch_4:
869 case Builtin::BI__sync_add_and_fetch_8:
870 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000871 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000872 case Builtin::BI__sync_sub_and_fetch_1:
873 case Builtin::BI__sync_sub_and_fetch_2:
874 case Builtin::BI__sync_sub_and_fetch_4:
875 case Builtin::BI__sync_sub_and_fetch_8:
876 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000877 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000878 case Builtin::BI__sync_and_and_fetch_1:
879 case Builtin::BI__sync_and_and_fetch_2:
880 case Builtin::BI__sync_and_and_fetch_4:
881 case Builtin::BI__sync_and_and_fetch_8:
882 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000883 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000884 case Builtin::BI__sync_or_and_fetch_1:
885 case Builtin::BI__sync_or_and_fetch_2:
886 case Builtin::BI__sync_or_and_fetch_4:
887 case Builtin::BI__sync_or_and_fetch_8:
888 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000889 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000890 case Builtin::BI__sync_xor_and_fetch_1:
891 case Builtin::BI__sync_xor_and_fetch_2:
892 case Builtin::BI__sync_xor_and_fetch_4:
893 case Builtin::BI__sync_xor_and_fetch_8:
894 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000895 case Builtin::BI__sync_nand_and_fetch:
896 case Builtin::BI__sync_nand_and_fetch_1:
897 case Builtin::BI__sync_nand_and_fetch_2:
898 case Builtin::BI__sync_nand_and_fetch_4:
899 case Builtin::BI__sync_nand_and_fetch_8:
900 case Builtin::BI__sync_nand_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000901 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000902 case Builtin::BI__sync_val_compare_and_swap_1:
903 case Builtin::BI__sync_val_compare_and_swap_2:
904 case Builtin::BI__sync_val_compare_and_swap_4:
905 case Builtin::BI__sync_val_compare_and_swap_8:
906 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000907 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000908 case Builtin::BI__sync_bool_compare_and_swap_1:
909 case Builtin::BI__sync_bool_compare_and_swap_2:
910 case Builtin::BI__sync_bool_compare_and_swap_4:
911 case Builtin::BI__sync_bool_compare_and_swap_8:
912 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000913 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000914 case Builtin::BI__sync_lock_test_and_set_1:
915 case Builtin::BI__sync_lock_test_and_set_2:
916 case Builtin::BI__sync_lock_test_and_set_4:
917 case Builtin::BI__sync_lock_test_and_set_8:
918 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000919 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000920 case Builtin::BI__sync_lock_release_1:
921 case Builtin::BI__sync_lock_release_2:
922 case Builtin::BI__sync_lock_release_4:
923 case Builtin::BI__sync_lock_release_8:
924 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000925 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000926 case Builtin::BI__sync_swap_1:
927 case Builtin::BI__sync_swap_2:
928 case Builtin::BI__sync_swap_4:
929 case Builtin::BI__sync_swap_8:
930 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000931 return SemaBuiltinAtomicOverloaded(TheCallResult);
Michael Zolotukhin84df1232015-09-08 23:52:33 +0000932 case Builtin::BI__builtin_nontemporal_load:
933 case Builtin::BI__builtin_nontemporal_store:
934 return SemaBuiltinNontemporalOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +0000935#define BUILTIN(ID, TYPE, ATTRS)
936#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
937 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000938 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +0000939#include "clang/Basic/Builtins.def"
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000940 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000941 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000942 return ExprError();
943 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +0000944 case Builtin::BI__builtin_addressof:
945 if (SemaBuiltinAddressof(*this, TheCall))
946 return ExprError();
947 break;
John McCall03107a42015-10-29 20:48:01 +0000948 case Builtin::BI__builtin_add_overflow:
949 case Builtin::BI__builtin_sub_overflow:
950 case Builtin::BI__builtin_mul_overflow:
Craig Toppera86e70d2015-11-07 06:16:14 +0000951 if (SemaBuiltinOverflow(*this, TheCall))
952 return ExprError();
953 break;
Richard Smith760520b2014-06-03 23:27:44 +0000954 case Builtin::BI__builtin_operator_new:
955 case Builtin::BI__builtin_operator_delete:
956 if (!getLangOpts().CPlusPlus) {
957 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
958 << (BuiltinID == Builtin::BI__builtin_operator_new
959 ? "__builtin_operator_new"
960 : "__builtin_operator_delete")
961 << "C++";
962 return ExprError();
963 }
964 // CodeGen assumes it can find the global new and delete to call,
965 // so ensure that they are declared.
966 DeclareGlobalNewDelete();
967 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000968
969 // check secure string manipulation functions where overflows
970 // are detectable at compile time
971 case Builtin::BI__builtin___memcpy_chk:
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000972 case Builtin::BI__builtin___memmove_chk:
973 case Builtin::BI__builtin___memset_chk:
974 case Builtin::BI__builtin___strlcat_chk:
975 case Builtin::BI__builtin___strlcpy_chk:
976 case Builtin::BI__builtin___strncat_chk:
977 case Builtin::BI__builtin___strncpy_chk:
978 case Builtin::BI__builtin___stpncpy_chk:
979 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
980 break;
Steven Wu566c14e2014-09-24 04:37:33 +0000981 case Builtin::BI__builtin___memccpy_chk:
982 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
983 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000984 case Builtin::BI__builtin___snprintf_chk:
985 case Builtin::BI__builtin___vsnprintf_chk:
986 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
987 break;
Peter Collingbournef7706832014-12-12 23:41:25 +0000988 case Builtin::BI__builtin_call_with_static_chain:
989 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
990 return ExprError();
991 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000992 case Builtin::BI__exception_code:
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000993 case Builtin::BI_exception_code:
Reid Kleckner1d59f992015-01-22 01:36:17 +0000994 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
995 diag::err_seh___except_block))
996 return ExprError();
997 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000998 case Builtin::BI__exception_info:
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000999 case Builtin::BI_exception_info:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001000 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1001 diag::err_seh___except_filter))
1002 return ExprError();
1003 break;
David Majnemerba3e5ec2015-03-13 18:26:17 +00001004 case Builtin::BI__GetExceptionInfo:
1005 if (checkArgCount(*this, TheCall, 1))
1006 return ExprError();
1007
1008 if (CheckCXXThrowOperand(
1009 TheCall->getLocStart(),
1010 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1011 TheCall))
1012 return ExprError();
1013
1014 TheCall->setType(Context.VoidPtrTy);
1015 break;
Anastasia Stulova7f8d6dc2016-07-04 16:07:18 +00001016 // OpenCL v2.0, s6.13.16 - Pipe functions
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001017 case Builtin::BIread_pipe:
1018 case Builtin::BIwrite_pipe:
1019 // Since those two functions are declared with var args, we need a semantic
1020 // check for the argument.
1021 if (SemaBuiltinRWPipe(*this, TheCall))
1022 return ExprError();
1023 break;
1024 case Builtin::BIreserve_read_pipe:
1025 case Builtin::BIreserve_write_pipe:
1026 case Builtin::BIwork_group_reserve_read_pipe:
1027 case Builtin::BIwork_group_reserve_write_pipe:
1028 case Builtin::BIsub_group_reserve_read_pipe:
1029 case Builtin::BIsub_group_reserve_write_pipe:
1030 if (SemaBuiltinReserveRWPipe(*this, TheCall))
1031 return ExprError();
1032 // Since return type of reserve_read/write_pipe built-in function is
1033 // reserve_id_t, which is not defined in the builtin def file , we used int
1034 // as return type and need to override the return type of these functions.
1035 TheCall->setType(Context.OCLReserveIDTy);
1036 break;
1037 case Builtin::BIcommit_read_pipe:
1038 case Builtin::BIcommit_write_pipe:
1039 case Builtin::BIwork_group_commit_read_pipe:
1040 case Builtin::BIwork_group_commit_write_pipe:
1041 case Builtin::BIsub_group_commit_read_pipe:
1042 case Builtin::BIsub_group_commit_write_pipe:
1043 if (SemaBuiltinCommitRWPipe(*this, TheCall))
1044 return ExprError();
1045 break;
1046 case Builtin::BIget_pipe_num_packets:
1047 case Builtin::BIget_pipe_max_packets:
1048 if (SemaBuiltinPipePackets(*this, TheCall))
1049 return ExprError();
1050 break;
Yaxun Liuf7449a12016-05-20 19:54:38 +00001051 case Builtin::BIto_global:
1052 case Builtin::BIto_local:
1053 case Builtin::BIto_private:
1054 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1055 return ExprError();
1056 break;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00001057 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1058 case Builtin::BIenqueue_kernel:
1059 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1060 return ExprError();
1061 break;
1062 case Builtin::BIget_kernel_work_group_size:
1063 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1064 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1065 return ExprError();
Nate Begeman4904e322010-06-08 02:47:44 +00001066 }
Richard Smith760520b2014-06-03 23:27:44 +00001067
Nate Begeman4904e322010-06-08 02:47:44 +00001068 // Since the target specific builtins for each arch overlap, only check those
1069 // of the arch we are compiling for.
Artem Belevich9674a642015-09-22 17:23:05 +00001070 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001071 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +00001072 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001073 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001074 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001075 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001076 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1077 return ExprError();
1078 break;
Tim Northover25e8a672014-05-24 12:51:25 +00001079 case llvm::Triple::aarch64:
1080 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +00001081 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +00001082 return ExprError();
1083 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001084 case llvm::Triple::mips:
1085 case llvm::Triple::mipsel:
1086 case llvm::Triple::mips64:
1087 case llvm::Triple::mips64el:
1088 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1089 return ExprError();
1090 break;
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001091 case llvm::Triple::systemz:
1092 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1093 return ExprError();
1094 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001095 case llvm::Triple::x86:
1096 case llvm::Triple::x86_64:
1097 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1098 return ExprError();
1099 break;
Kit Bartone50adcb2015-03-30 19:40:59 +00001100 case llvm::Triple::ppc:
1101 case llvm::Triple::ppc64:
1102 case llvm::Triple::ppc64le:
1103 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1104 return ExprError();
1105 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001106 default:
1107 break;
1108 }
1109 }
1110
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001111 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +00001112}
1113
Nate Begeman91e1fea2010-06-14 05:21:25 +00001114// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +00001115static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +00001116 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +00001117 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +00001118 switch (Type.getEltType()) {
1119 case NeonTypeFlags::Int8:
1120 case NeonTypeFlags::Poly8:
1121 return shift ? 7 : (8 << IsQuad) - 1;
1122 case NeonTypeFlags::Int16:
1123 case NeonTypeFlags::Poly16:
1124 return shift ? 15 : (4 << IsQuad) - 1;
1125 case NeonTypeFlags::Int32:
1126 return shift ? 31 : (2 << IsQuad) - 1;
1127 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +00001128 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +00001129 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001130 case NeonTypeFlags::Poly128:
1131 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +00001132 case NeonTypeFlags::Float16:
1133 assert(!shift && "cannot shift float types!");
1134 return (4 << IsQuad) - 1;
1135 case NeonTypeFlags::Float32:
1136 assert(!shift && "cannot shift float types!");
1137 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001138 case NeonTypeFlags::Float64:
1139 assert(!shift && "cannot shift float types!");
1140 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +00001141 }
David Blaikie8a40f702012-01-17 06:56:22 +00001142 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +00001143}
1144
Bob Wilsone4d77232011-11-08 05:04:11 +00001145/// getNeonEltType - Return the QualType corresponding to the elements of
1146/// the vector type specified by the NeonTypeFlags. This is used to check
1147/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +00001148static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +00001149 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +00001150 switch (Flags.getEltType()) {
1151 case NeonTypeFlags::Int8:
1152 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1153 case NeonTypeFlags::Int16:
1154 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1155 case NeonTypeFlags::Int32:
1156 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1157 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +00001158 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +00001159 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1160 else
1161 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1162 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001163 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +00001164 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001165 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +00001166 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +00001167 case NeonTypeFlags::Poly64:
Kevin Qin78b86532015-05-14 08:18:05 +00001168 if (IsInt64Long)
1169 return Context.UnsignedLongTy;
1170 else
1171 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001172 case NeonTypeFlags::Poly128:
1173 break;
Bob Wilsone4d77232011-11-08 05:04:11 +00001174 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +00001175 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001176 case NeonTypeFlags::Float32:
1177 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +00001178 case NeonTypeFlags::Float64:
1179 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001180 }
David Blaikie8a40f702012-01-17 06:56:22 +00001181 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +00001182}
1183
Tim Northover12670412014-02-19 10:37:05 +00001184bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +00001185 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +00001186 uint64_t mask = 0;
1187 unsigned TV = 0;
1188 int PtrArgNum = -1;
1189 bool HasConstPtr = false;
1190 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +00001191#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001192#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +00001193#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001194 }
1195
1196 // For NEON intrinsics which are overloaded on vector element type, validate
1197 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +00001198 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001199 if (mask) {
1200 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1201 return true;
1202
1203 TV = Result.getLimitedValue(64);
1204 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1205 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +00001206 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +00001207 }
1208
1209 if (PtrArgNum >= 0) {
1210 // Check that pointer arguments have the specified type.
1211 Expr *Arg = TheCall->getArg(PtrArgNum);
1212 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1213 Arg = ICE->getSubExpr();
1214 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1215 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +00001216
Tim Northovera2ee4332014-03-29 15:09:45 +00001217 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Tim Northover40956e62014-07-23 12:32:58 +00001218 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
Tim Northovera2ee4332014-03-29 15:09:45 +00001219 bool IsInt64Long =
1220 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1221 QualType EltTy =
1222 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +00001223 if (HasConstPtr)
1224 EltTy = EltTy.withConst();
1225 QualType LHSTy = Context.getPointerType(EltTy);
1226 AssignConvertType ConvTy;
1227 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1228 if (RHS.isInvalid())
1229 return true;
1230 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1231 RHS.get(), AA_Assigning))
1232 return true;
1233 }
1234
1235 // For NEON intrinsics which take an immediate value as part of the
1236 // instruction, range check them here.
1237 unsigned i = 0, l = 0, u = 0;
1238 switch (BuiltinID) {
1239 default:
1240 return false;
Tim Northover12670412014-02-19 10:37:05 +00001241#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001242#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +00001243#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001244 }
Tim Northover2fe823a2013-08-01 09:23:19 +00001245
Richard Sandiford28940af2014-04-16 08:47:51 +00001246 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +00001247}
1248
Tim Northovera2ee4332014-03-29 15:09:45 +00001249bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1250 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +00001251 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001252 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +00001253 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001254 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +00001255 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001256 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1257 BuiltinID == AArch64::BI__builtin_arm_strex ||
1258 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +00001259 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +00001260 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001261 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1262 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1263 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +00001264
1265 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1266
1267 // Ensure that we have the proper number of arguments.
1268 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1269 return true;
1270
1271 // Inspect the pointer argument of the atomic builtin. This should always be
1272 // a pointer type, whose element is an integral scalar or pointer type.
1273 // Because it is a pointer type, we don't have to worry about any implicit
1274 // casts here.
1275 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1276 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1277 if (PointerArgRes.isInvalid())
1278 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001279 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001280
1281 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1282 if (!pointerType) {
1283 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1284 << PointerArg->getType() << PointerArg->getSourceRange();
1285 return true;
1286 }
1287
1288 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1289 // task is to insert the appropriate casts into the AST. First work out just
1290 // what the appropriate type is.
1291 QualType ValType = pointerType->getPointeeType();
1292 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1293 if (IsLdrex)
1294 AddrType.addConst();
1295
1296 // Issue a warning if the cast is dodgy.
1297 CastKind CastNeeded = CK_NoOp;
1298 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1299 CastNeeded = CK_BitCast;
1300 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1301 << PointerArg->getType()
1302 << Context.getPointerType(AddrType)
1303 << AA_Passing << PointerArg->getSourceRange();
1304 }
1305
1306 // Finally, do the cast and replace the argument with the corrected version.
1307 AddrType = Context.getPointerType(AddrType);
1308 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1309 if (PointerArgRes.isInvalid())
1310 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001311 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001312
1313 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1314
1315 // In general, we allow ints, floats and pointers to be loaded and stored.
1316 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1317 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1318 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1319 << PointerArg->getType() << PointerArg->getSourceRange();
1320 return true;
1321 }
1322
1323 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +00001324 if (Context.getTypeSize(ValType) > MaxWidth) {
1325 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +00001326 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1327 << PointerArg->getType() << PointerArg->getSourceRange();
1328 return true;
1329 }
1330
1331 switch (ValType.getObjCLifetime()) {
1332 case Qualifiers::OCL_None:
1333 case Qualifiers::OCL_ExplicitNone:
1334 // okay
1335 break;
1336
1337 case Qualifiers::OCL_Weak:
1338 case Qualifiers::OCL_Strong:
1339 case Qualifiers::OCL_Autoreleasing:
1340 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1341 << ValType << PointerArg->getSourceRange();
1342 return true;
1343 }
1344
Tim Northover6aacd492013-07-16 09:47:53 +00001345 if (IsLdrex) {
1346 TheCall->setType(ValType);
1347 return false;
1348 }
1349
1350 // Initialize the argument to be stored.
1351 ExprResult ValArg = TheCall->getArg(0);
1352 InitializedEntity Entity = InitializedEntity::InitializeParameter(
1353 Context, ValType, /*consume*/ false);
1354 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1355 if (ValArg.isInvalid())
1356 return true;
Tim Northover6aacd492013-07-16 09:47:53 +00001357 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +00001358
1359 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1360 // but the custom checker bypasses all default analysis.
1361 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +00001362 return false;
1363}
1364
Nate Begeman4904e322010-06-08 02:47:44 +00001365bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +00001366 llvm::APSInt Result;
1367
Tim Northover6aacd492013-07-16 09:47:53 +00001368 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001369 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1370 BuiltinID == ARM::BI__builtin_arm_strex ||
1371 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001372 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +00001373 }
1374
Yi Kong26d104a2014-08-13 19:18:14 +00001375 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1376 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1377 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1378 }
1379
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001380 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1381 BuiltinID == ARM::BI__builtin_arm_wsr64)
1382 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1383
1384 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1385 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1386 BuiltinID == ARM::BI__builtin_arm_wsr ||
1387 BuiltinID == ARM::BI__builtin_arm_wsrp)
1388 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1389
Tim Northover12670412014-02-19 10:37:05 +00001390 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1391 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +00001392
Yi Kong4efadfb2014-07-03 16:01:25 +00001393 // For intrinsics which take an immediate value as part of the instruction,
1394 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +00001395 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +00001396 switch (BuiltinID) {
1397 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +00001398 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
1399 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +00001400 case ARM::BI__builtin_arm_vcvtr_f:
1401 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +00001402 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +00001403 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +00001404 case ARM::BI__builtin_arm_isb:
1405 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001406 }
Nate Begemand773fe62010-06-13 04:47:52 +00001407
Nate Begemanf568b072010-08-03 21:32:34 +00001408 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +00001409 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001410}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001411
Tim Northover573cbee2014-05-24 12:52:07 +00001412bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +00001413 CallExpr *TheCall) {
1414 llvm::APSInt Result;
1415
Tim Northover573cbee2014-05-24 12:52:07 +00001416 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001417 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1418 BuiltinID == AArch64::BI__builtin_arm_strex ||
1419 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001420 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1421 }
1422
Yi Konga5548432014-08-13 19:18:20 +00001423 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1424 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1425 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1426 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1427 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1428 }
1429
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001430 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1431 BuiltinID == AArch64::BI__builtin_arm_wsr64)
Tim Northover54e50002016-04-13 17:08:55 +00001432 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001433
1434 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1435 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1436 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1437 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1438 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1439
Tim Northovera2ee4332014-03-29 15:09:45 +00001440 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1441 return true;
1442
Yi Kong19a29ac2014-07-17 10:52:06 +00001443 // For intrinsics which take an immediate value as part of the instruction,
1444 // range check them here.
1445 unsigned i = 0, l = 0, u = 0;
1446 switch (BuiltinID) {
1447 default: return false;
1448 case AArch64::BI__builtin_arm_dmb:
1449 case AArch64::BI__builtin_arm_dsb:
1450 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1451 }
1452
Yi Kong19a29ac2014-07-17 10:52:06 +00001453 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +00001454}
1455
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001456bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1457 unsigned i = 0, l = 0, u = 0;
1458 switch (BuiltinID) {
1459 default: return false;
1460 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1461 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +00001462 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1463 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1464 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1465 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1466 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001467 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001468
Richard Sandiford28940af2014-04-16 08:47:51 +00001469 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001470}
1471
Kit Bartone50adcb2015-03-30 19:40:59 +00001472bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1473 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00001474 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1475 BuiltinID == PPC::BI__builtin_divdeu ||
1476 BuiltinID == PPC::BI__builtin_bpermd;
1477 bool IsTarget64Bit = Context.getTargetInfo()
1478 .getTypeWidth(Context
1479 .getTargetInfo()
1480 .getIntPtrType()) == 64;
1481 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1482 BuiltinID == PPC::BI__builtin_divweu ||
1483 BuiltinID == PPC::BI__builtin_divde ||
1484 BuiltinID == PPC::BI__builtin_divdeu;
1485
1486 if (Is64BitBltin && !IsTarget64Bit)
1487 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1488 << TheCall->getSourceRange();
1489
1490 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1491 (BuiltinID == PPC::BI__builtin_bpermd &&
1492 !Context.getTargetInfo().hasFeature("bpermd")))
1493 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1494 << TheCall->getSourceRange();
1495
Kit Bartone50adcb2015-03-30 19:40:59 +00001496 switch (BuiltinID) {
1497 default: return false;
1498 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1499 case PPC::BI__builtin_altivec_crypto_vshasigmad:
1500 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1501 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1502 case PPC::BI__builtin_tbegin:
1503 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1504 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1505 case PPC::BI__builtin_tabortwc:
1506 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1507 case PPC::BI__builtin_tabortwci:
1508 case PPC::BI__builtin_tabortdci:
1509 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1510 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1511 }
1512 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1513}
1514
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001515bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1516 CallExpr *TheCall) {
1517 if (BuiltinID == SystemZ::BI__builtin_tabort) {
1518 Expr *Arg = TheCall->getArg(0);
1519 llvm::APSInt AbortCode(32);
1520 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1521 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1522 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1523 << Arg->getSourceRange();
1524 }
1525
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001526 // For intrinsics which take an immediate value as part of the instruction,
1527 // range check them here.
1528 unsigned i = 0, l = 0, u = 0;
1529 switch (BuiltinID) {
1530 default: return false;
1531 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1532 case SystemZ::BI__builtin_s390_verimb:
1533 case SystemZ::BI__builtin_s390_verimh:
1534 case SystemZ::BI__builtin_s390_verimf:
1535 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1536 case SystemZ::BI__builtin_s390_vfaeb:
1537 case SystemZ::BI__builtin_s390_vfaeh:
1538 case SystemZ::BI__builtin_s390_vfaef:
1539 case SystemZ::BI__builtin_s390_vfaebs:
1540 case SystemZ::BI__builtin_s390_vfaehs:
1541 case SystemZ::BI__builtin_s390_vfaefs:
1542 case SystemZ::BI__builtin_s390_vfaezb:
1543 case SystemZ::BI__builtin_s390_vfaezh:
1544 case SystemZ::BI__builtin_s390_vfaezf:
1545 case SystemZ::BI__builtin_s390_vfaezbs:
1546 case SystemZ::BI__builtin_s390_vfaezhs:
1547 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1548 case SystemZ::BI__builtin_s390_vfidb:
1549 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1550 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1551 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1552 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1553 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1554 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1555 case SystemZ::BI__builtin_s390_vstrcb:
1556 case SystemZ::BI__builtin_s390_vstrch:
1557 case SystemZ::BI__builtin_s390_vstrcf:
1558 case SystemZ::BI__builtin_s390_vstrczb:
1559 case SystemZ::BI__builtin_s390_vstrczh:
1560 case SystemZ::BI__builtin_s390_vstrczf:
1561 case SystemZ::BI__builtin_s390_vstrcbs:
1562 case SystemZ::BI__builtin_s390_vstrchs:
1563 case SystemZ::BI__builtin_s390_vstrcfs:
1564 case SystemZ::BI__builtin_s390_vstrczbs:
1565 case SystemZ::BI__builtin_s390_vstrczhs:
1566 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1567 }
1568 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001569}
1570
Craig Topper5ba2c502015-11-07 08:08:31 +00001571/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1572/// This checks that the target supports __builtin_cpu_supports and
1573/// that the string argument is constant and valid.
1574static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1575 Expr *Arg = TheCall->getArg(0);
1576
1577 // Check if the argument is a string literal.
1578 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1579 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1580 << Arg->getSourceRange();
1581
1582 // Check the contents of the string.
1583 StringRef Feature =
1584 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1585 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1586 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1587 << Arg->getSourceRange();
1588 return false;
1589}
1590
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001591bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Craig Topper39c87102016-05-18 03:18:12 +00001592 int i = 0, l = 0, u = 0;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001593 switch (BuiltinID) {
Richard Trieucc3949d2016-02-18 22:34:54 +00001594 default:
1595 return false;
Eric Christopherd9832702015-06-29 21:00:05 +00001596 case X86::BI__builtin_cpu_supports:
Craig Topper5ba2c502015-11-07 08:08:31 +00001597 return SemaBuiltinCpuSupports(*this, TheCall);
Charles Davisc7d5c942015-09-17 20:55:33 +00001598 case X86::BI__builtin_ms_va_start:
1599 return SemaBuiltinMSVAStart(TheCall);
Craig Topperfe22d592016-07-21 07:38:43 +00001600 case X86::BI__builtin_ia32_addcarryx_u64:
1601 case X86::BI__builtin_ia32_addcarry_u64:
1602 case X86::BI__builtin_ia32_subborrow_u64:
1603 case X86::BI__builtin_ia32_readeflags_u64:
1604 case X86::BI__builtin_ia32_writeeflags_u64:
1605 case X86::BI__builtin_ia32_bextr_u64:
1606 case X86::BI__builtin_ia32_bextri_u64:
1607 case X86::BI__builtin_ia32_bzhi_di:
1608 case X86::BI__builtin_ia32_pdep_di:
1609 case X86::BI__builtin_ia32_pext_di:
1610 case X86::BI__builtin_ia32_crc32di:
1611 case X86::BI__builtin_ia32_fxsave64:
1612 case X86::BI__builtin_ia32_fxrstor64:
1613 case X86::BI__builtin_ia32_xsave64:
1614 case X86::BI__builtin_ia32_xrstor64:
1615 case X86::BI__builtin_ia32_xsaveopt64:
1616 case X86::BI__builtin_ia32_xrstors64:
1617 case X86::BI__builtin_ia32_xsavec64:
1618 case X86::BI__builtin_ia32_xsaves64:
1619 case X86::BI__builtin_ia32_rdfsbase64:
1620 case X86::BI__builtin_ia32_rdgsbase64:
1621 case X86::BI__builtin_ia32_wrfsbase64:
1622 case X86::BI__builtin_ia32_wrgsbase64:
Craig Topper351ed422016-07-24 14:58:06 +00001623 case X86::BI__builtin_ia32_pbroadcastq512_gpr_mask:
1624 case X86::BI__builtin_ia32_pbroadcastq256_gpr_mask:
1625 case X86::BI__builtin_ia32_pbroadcastq128_gpr_mask:
Craig Topperfe22d592016-07-21 07:38:43 +00001626 case X86::BI__builtin_ia32_vcvtsd2si64:
1627 case X86::BI__builtin_ia32_vcvtsd2usi64:
1628 case X86::BI__builtin_ia32_vcvtss2si64:
1629 case X86::BI__builtin_ia32_vcvtss2usi64:
1630 case X86::BI__builtin_ia32_vcvttsd2si64:
1631 case X86::BI__builtin_ia32_vcvttsd2usi64:
1632 case X86::BI__builtin_ia32_vcvttss2si64:
1633 case X86::BI__builtin_ia32_vcvttss2usi64:
1634 case X86::BI__builtin_ia32_cvtss2si64:
1635 case X86::BI__builtin_ia32_cvttss2si64:
1636 case X86::BI__builtin_ia32_cvtsd2si64:
1637 case X86::BI__builtin_ia32_cvttsd2si64:
1638 case X86::BI__builtin_ia32_cvtsi2sd64:
1639 case X86::BI__builtin_ia32_cvtsi2ss64:
1640 case X86::BI__builtin_ia32_cvtusi2sd64:
1641 case X86::BI__builtin_ia32_cvtusi2ss64:
1642 case X86::BI__builtin_ia32_rdseed64_step: {
1643 // These builtins only work on x86-64 targets.
1644 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
1645 if (TT.getArch() != llvm::Triple::x86_64)
1646 return Diag(TheCall->getCallee()->getLocStart(),
1647 diag::err_x86_builtin_32_bit_tgt);
1648 return false;
1649 }
Craig Topper39c87102016-05-18 03:18:12 +00001650 case X86::BI__builtin_ia32_extractf64x4_mask:
1651 case X86::BI__builtin_ia32_extracti64x4_mask:
1652 case X86::BI__builtin_ia32_extractf32x8_mask:
1653 case X86::BI__builtin_ia32_extracti32x8_mask:
1654 case X86::BI__builtin_ia32_extractf64x2_256_mask:
1655 case X86::BI__builtin_ia32_extracti64x2_256_mask:
1656 case X86::BI__builtin_ia32_extractf32x4_256_mask:
1657 case X86::BI__builtin_ia32_extracti32x4_256_mask:
1658 i = 1; l = 0; u = 1;
1659 break;
Richard Trieucc3949d2016-02-18 22:34:54 +00001660 case X86::BI_mm_prefetch:
Craig Topper39c87102016-05-18 03:18:12 +00001661 case X86::BI__builtin_ia32_extractf32x4_mask:
1662 case X86::BI__builtin_ia32_extracti32x4_mask:
Craig Topper39c87102016-05-18 03:18:12 +00001663 case X86::BI__builtin_ia32_extractf64x2_512_mask:
1664 case X86::BI__builtin_ia32_extracti64x2_512_mask:
1665 i = 1; l = 0; u = 3;
1666 break;
1667 case X86::BI__builtin_ia32_insertf32x8_mask:
1668 case X86::BI__builtin_ia32_inserti32x8_mask:
1669 case X86::BI__builtin_ia32_insertf64x4_mask:
1670 case X86::BI__builtin_ia32_inserti64x4_mask:
1671 case X86::BI__builtin_ia32_insertf64x2_256_mask:
1672 case X86::BI__builtin_ia32_inserti64x2_256_mask:
1673 case X86::BI__builtin_ia32_insertf32x4_256_mask:
1674 case X86::BI__builtin_ia32_inserti32x4_256_mask:
1675 i = 2; l = 0; u = 1;
Richard Trieucc3949d2016-02-18 22:34:54 +00001676 break;
1677 case X86::BI__builtin_ia32_sha1rnds4:
Craig Topper39c87102016-05-18 03:18:12 +00001678 case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
1679 case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
1680 case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
1681 case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00001682 case X86::BI__builtin_ia32_insertf64x2_512_mask:
1683 case X86::BI__builtin_ia32_inserti64x2_512_mask:
1684 case X86::BI__builtin_ia32_insertf32x4_mask:
1685 case X86::BI__builtin_ia32_inserti32x4_mask:
1686 i = 2; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00001687 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00001688 case X86::BI__builtin_ia32_vpermil2pd:
1689 case X86::BI__builtin_ia32_vpermil2pd256:
1690 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00001691 case X86::BI__builtin_ia32_vpermil2ps256:
Craig Topper39c87102016-05-18 03:18:12 +00001692 i = 3; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00001693 break;
Craig Topper95b0d732015-01-25 23:30:05 +00001694 case X86::BI__builtin_ia32_cmpb128_mask:
1695 case X86::BI__builtin_ia32_cmpw128_mask:
1696 case X86::BI__builtin_ia32_cmpd128_mask:
1697 case X86::BI__builtin_ia32_cmpq128_mask:
1698 case X86::BI__builtin_ia32_cmpb256_mask:
1699 case X86::BI__builtin_ia32_cmpw256_mask:
1700 case X86::BI__builtin_ia32_cmpd256_mask:
1701 case X86::BI__builtin_ia32_cmpq256_mask:
1702 case X86::BI__builtin_ia32_cmpb512_mask:
1703 case X86::BI__builtin_ia32_cmpw512_mask:
1704 case X86::BI__builtin_ia32_cmpd512_mask:
1705 case X86::BI__builtin_ia32_cmpq512_mask:
1706 case X86::BI__builtin_ia32_ucmpb128_mask:
1707 case X86::BI__builtin_ia32_ucmpw128_mask:
1708 case X86::BI__builtin_ia32_ucmpd128_mask:
1709 case X86::BI__builtin_ia32_ucmpq128_mask:
1710 case X86::BI__builtin_ia32_ucmpb256_mask:
1711 case X86::BI__builtin_ia32_ucmpw256_mask:
1712 case X86::BI__builtin_ia32_ucmpd256_mask:
1713 case X86::BI__builtin_ia32_ucmpq256_mask:
1714 case X86::BI__builtin_ia32_ucmpb512_mask:
1715 case X86::BI__builtin_ia32_ucmpw512_mask:
1716 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00001717 case X86::BI__builtin_ia32_ucmpq512_mask:
Craig Topper8dd7d0d2015-02-13 06:04:48 +00001718 case X86::BI__builtin_ia32_vpcomub:
1719 case X86::BI__builtin_ia32_vpcomuw:
1720 case X86::BI__builtin_ia32_vpcomud:
1721 case X86::BI__builtin_ia32_vpcomuq:
1722 case X86::BI__builtin_ia32_vpcomb:
1723 case X86::BI__builtin_ia32_vpcomw:
1724 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00001725 case X86::BI__builtin_ia32_vpcomq:
Craig Topper39c87102016-05-18 03:18:12 +00001726 i = 2; l = 0; u = 7;
1727 break;
1728 case X86::BI__builtin_ia32_roundps:
1729 case X86::BI__builtin_ia32_roundpd:
1730 case X86::BI__builtin_ia32_roundps256:
1731 case X86::BI__builtin_ia32_roundpd256:
Craig Topper39c87102016-05-18 03:18:12 +00001732 i = 1; l = 0; u = 15;
1733 break;
1734 case X86::BI__builtin_ia32_roundss:
1735 case X86::BI__builtin_ia32_roundsd:
1736 case X86::BI__builtin_ia32_rangepd128_mask:
1737 case X86::BI__builtin_ia32_rangepd256_mask:
1738 case X86::BI__builtin_ia32_rangepd512_mask:
1739 case X86::BI__builtin_ia32_rangeps128_mask:
1740 case X86::BI__builtin_ia32_rangeps256_mask:
1741 case X86::BI__builtin_ia32_rangeps512_mask:
1742 case X86::BI__builtin_ia32_getmantsd_round_mask:
1743 case X86::BI__builtin_ia32_getmantss_round_mask:
Craig Topper39c87102016-05-18 03:18:12 +00001744 i = 2; l = 0; u = 15;
1745 break;
1746 case X86::BI__builtin_ia32_cmpps:
1747 case X86::BI__builtin_ia32_cmpss:
1748 case X86::BI__builtin_ia32_cmppd:
1749 case X86::BI__builtin_ia32_cmpsd:
1750 case X86::BI__builtin_ia32_cmpps256:
1751 case X86::BI__builtin_ia32_cmppd256:
1752 case X86::BI__builtin_ia32_cmpps128_mask:
1753 case X86::BI__builtin_ia32_cmppd128_mask:
1754 case X86::BI__builtin_ia32_cmpps256_mask:
1755 case X86::BI__builtin_ia32_cmppd256_mask:
1756 case X86::BI__builtin_ia32_cmpps512_mask:
1757 case X86::BI__builtin_ia32_cmppd512_mask:
1758 case X86::BI__builtin_ia32_cmpsd_mask:
1759 case X86::BI__builtin_ia32_cmpss_mask:
1760 i = 2; l = 0; u = 31;
1761 break;
1762 case X86::BI__builtin_ia32_xabort:
1763 i = 0; l = -128; u = 255;
1764 break;
1765 case X86::BI__builtin_ia32_pshufw:
1766 case X86::BI__builtin_ia32_aeskeygenassist128:
1767 i = 1; l = -128; u = 255;
1768 break;
1769 case X86::BI__builtin_ia32_vcvtps2ph:
1770 case X86::BI__builtin_ia32_vcvtps2ph256:
Craig Topper39c87102016-05-18 03:18:12 +00001771 case X86::BI__builtin_ia32_rndscaleps_128_mask:
1772 case X86::BI__builtin_ia32_rndscalepd_128_mask:
1773 case X86::BI__builtin_ia32_rndscaleps_256_mask:
1774 case X86::BI__builtin_ia32_rndscalepd_256_mask:
1775 case X86::BI__builtin_ia32_rndscaleps_mask:
1776 case X86::BI__builtin_ia32_rndscalepd_mask:
1777 case X86::BI__builtin_ia32_reducepd128_mask:
1778 case X86::BI__builtin_ia32_reducepd256_mask:
1779 case X86::BI__builtin_ia32_reducepd512_mask:
1780 case X86::BI__builtin_ia32_reduceps128_mask:
1781 case X86::BI__builtin_ia32_reduceps256_mask:
1782 case X86::BI__builtin_ia32_reduceps512_mask:
1783 case X86::BI__builtin_ia32_prold512_mask:
1784 case X86::BI__builtin_ia32_prolq512_mask:
1785 case X86::BI__builtin_ia32_prold128_mask:
1786 case X86::BI__builtin_ia32_prold256_mask:
1787 case X86::BI__builtin_ia32_prolq128_mask:
1788 case X86::BI__builtin_ia32_prolq256_mask:
1789 case X86::BI__builtin_ia32_prord128_mask:
1790 case X86::BI__builtin_ia32_prord256_mask:
1791 case X86::BI__builtin_ia32_prorq128_mask:
1792 case X86::BI__builtin_ia32_prorq256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00001793 case X86::BI__builtin_ia32_psllwi512_mask:
1794 case X86::BI__builtin_ia32_psllwi128_mask:
1795 case X86::BI__builtin_ia32_psllwi256_mask:
1796 case X86::BI__builtin_ia32_psrldi128_mask:
1797 case X86::BI__builtin_ia32_psrldi256_mask:
1798 case X86::BI__builtin_ia32_psrldi512_mask:
1799 case X86::BI__builtin_ia32_psrlqi128_mask:
1800 case X86::BI__builtin_ia32_psrlqi256_mask:
1801 case X86::BI__builtin_ia32_psrlqi512_mask:
1802 case X86::BI__builtin_ia32_psrawi512_mask:
1803 case X86::BI__builtin_ia32_psrawi128_mask:
1804 case X86::BI__builtin_ia32_psrawi256_mask:
1805 case X86::BI__builtin_ia32_psrlwi512_mask:
1806 case X86::BI__builtin_ia32_psrlwi128_mask:
1807 case X86::BI__builtin_ia32_psrlwi256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00001808 case X86::BI__builtin_ia32_psradi128_mask:
1809 case X86::BI__builtin_ia32_psradi256_mask:
1810 case X86::BI__builtin_ia32_psradi512_mask:
1811 case X86::BI__builtin_ia32_psraqi128_mask:
1812 case X86::BI__builtin_ia32_psraqi256_mask:
1813 case X86::BI__builtin_ia32_psraqi512_mask:
1814 case X86::BI__builtin_ia32_pslldi128_mask:
1815 case X86::BI__builtin_ia32_pslldi256_mask:
1816 case X86::BI__builtin_ia32_pslldi512_mask:
1817 case X86::BI__builtin_ia32_psllqi128_mask:
1818 case X86::BI__builtin_ia32_psllqi256_mask:
1819 case X86::BI__builtin_ia32_psllqi512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00001820 case X86::BI__builtin_ia32_fpclasspd128_mask:
1821 case X86::BI__builtin_ia32_fpclasspd256_mask:
1822 case X86::BI__builtin_ia32_fpclassps128_mask:
1823 case X86::BI__builtin_ia32_fpclassps256_mask:
1824 case X86::BI__builtin_ia32_fpclassps512_mask:
1825 case X86::BI__builtin_ia32_fpclasspd512_mask:
1826 case X86::BI__builtin_ia32_fpclasssd_mask:
1827 case X86::BI__builtin_ia32_fpclassss_mask:
Craig Topper39c87102016-05-18 03:18:12 +00001828 i = 1; l = 0; u = 255;
1829 break;
1830 case X86::BI__builtin_ia32_palignr:
1831 case X86::BI__builtin_ia32_insertps128:
1832 case X86::BI__builtin_ia32_dpps:
1833 case X86::BI__builtin_ia32_dppd:
1834 case X86::BI__builtin_ia32_dpps256:
1835 case X86::BI__builtin_ia32_mpsadbw128:
1836 case X86::BI__builtin_ia32_mpsadbw256:
1837 case X86::BI__builtin_ia32_pcmpistrm128:
1838 case X86::BI__builtin_ia32_pcmpistri128:
1839 case X86::BI__builtin_ia32_pcmpistria128:
1840 case X86::BI__builtin_ia32_pcmpistric128:
1841 case X86::BI__builtin_ia32_pcmpistrio128:
1842 case X86::BI__builtin_ia32_pcmpistris128:
1843 case X86::BI__builtin_ia32_pcmpistriz128:
1844 case X86::BI__builtin_ia32_pclmulqdq128:
1845 case X86::BI__builtin_ia32_vperm2f128_pd256:
1846 case X86::BI__builtin_ia32_vperm2f128_ps256:
1847 case X86::BI__builtin_ia32_vperm2f128_si256:
1848 case X86::BI__builtin_ia32_permti256:
1849 i = 2; l = -128; u = 255;
1850 break;
1851 case X86::BI__builtin_ia32_palignr128:
1852 case X86::BI__builtin_ia32_palignr256:
1853 case X86::BI__builtin_ia32_palignr128_mask:
1854 case X86::BI__builtin_ia32_palignr256_mask:
1855 case X86::BI__builtin_ia32_palignr512_mask:
1856 case X86::BI__builtin_ia32_alignq512_mask:
1857 case X86::BI__builtin_ia32_alignd512_mask:
1858 case X86::BI__builtin_ia32_alignd128_mask:
1859 case X86::BI__builtin_ia32_alignd256_mask:
1860 case X86::BI__builtin_ia32_alignq128_mask:
1861 case X86::BI__builtin_ia32_alignq256_mask:
1862 case X86::BI__builtin_ia32_vcomisd:
1863 case X86::BI__builtin_ia32_vcomiss:
1864 case X86::BI__builtin_ia32_shuf_f32x4_mask:
1865 case X86::BI__builtin_ia32_shuf_f64x2_mask:
1866 case X86::BI__builtin_ia32_shuf_i32x4_mask:
1867 case X86::BI__builtin_ia32_shuf_i64x2_mask:
Craig Topper39c87102016-05-18 03:18:12 +00001868 case X86::BI__builtin_ia32_dbpsadbw128_mask:
1869 case X86::BI__builtin_ia32_dbpsadbw256_mask:
1870 case X86::BI__builtin_ia32_dbpsadbw512_mask:
1871 i = 2; l = 0; u = 255;
1872 break;
1873 case X86::BI__builtin_ia32_fixupimmpd512_mask:
1874 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
1875 case X86::BI__builtin_ia32_fixupimmps512_mask:
1876 case X86::BI__builtin_ia32_fixupimmps512_maskz:
1877 case X86::BI__builtin_ia32_fixupimmsd_mask:
1878 case X86::BI__builtin_ia32_fixupimmsd_maskz:
1879 case X86::BI__builtin_ia32_fixupimmss_mask:
1880 case X86::BI__builtin_ia32_fixupimmss_maskz:
1881 case X86::BI__builtin_ia32_fixupimmpd128_mask:
1882 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
1883 case X86::BI__builtin_ia32_fixupimmpd256_mask:
1884 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
1885 case X86::BI__builtin_ia32_fixupimmps128_mask:
1886 case X86::BI__builtin_ia32_fixupimmps128_maskz:
1887 case X86::BI__builtin_ia32_fixupimmps256_mask:
1888 case X86::BI__builtin_ia32_fixupimmps256_maskz:
1889 case X86::BI__builtin_ia32_pternlogd512_mask:
1890 case X86::BI__builtin_ia32_pternlogd512_maskz:
1891 case X86::BI__builtin_ia32_pternlogq512_mask:
1892 case X86::BI__builtin_ia32_pternlogq512_maskz:
1893 case X86::BI__builtin_ia32_pternlogd128_mask:
1894 case X86::BI__builtin_ia32_pternlogd128_maskz:
1895 case X86::BI__builtin_ia32_pternlogd256_mask:
1896 case X86::BI__builtin_ia32_pternlogd256_maskz:
1897 case X86::BI__builtin_ia32_pternlogq128_mask:
1898 case X86::BI__builtin_ia32_pternlogq128_maskz:
1899 case X86::BI__builtin_ia32_pternlogq256_mask:
1900 case X86::BI__builtin_ia32_pternlogq256_maskz:
1901 i = 3; l = 0; u = 255;
1902 break;
1903 case X86::BI__builtin_ia32_pcmpestrm128:
1904 case X86::BI__builtin_ia32_pcmpestri128:
1905 case X86::BI__builtin_ia32_pcmpestria128:
1906 case X86::BI__builtin_ia32_pcmpestric128:
1907 case X86::BI__builtin_ia32_pcmpestrio128:
1908 case X86::BI__builtin_ia32_pcmpestris128:
1909 case X86::BI__builtin_ia32_pcmpestriz128:
1910 i = 4; l = -128; u = 255;
1911 break;
1912 case X86::BI__builtin_ia32_rndscalesd_round_mask:
1913 case X86::BI__builtin_ia32_rndscaless_round_mask:
1914 i = 4; l = 0; u = 255;
Richard Trieucc3949d2016-02-18 22:34:54 +00001915 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001916 }
Craig Topperdd84ec52014-12-27 07:00:08 +00001917 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001918}
1919
Richard Smith55ce3522012-06-25 20:30:08 +00001920/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
1921/// parameter with the FormatAttr's correct format_idx and firstDataArg.
1922/// Returns true when the format fits the function and the FormatStringInfo has
1923/// been populated.
1924bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
1925 FormatStringInfo *FSI) {
1926 FSI->HasVAListArg = Format->getFirstArg() == 0;
1927 FSI->FormatIdx = Format->getFormatIdx() - 1;
1928 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001929
Richard Smith55ce3522012-06-25 20:30:08 +00001930 // The way the format attribute works in GCC, the implicit this argument
1931 // of member functions is counted. However, it doesn't appear in our own
1932 // lists, so decrement format_idx in that case.
1933 if (IsCXXMember) {
1934 if(FSI->FormatIdx == 0)
1935 return false;
1936 --FSI->FormatIdx;
1937 if (FSI->FirstDataArg != 0)
1938 --FSI->FirstDataArg;
1939 }
1940 return true;
1941}
Mike Stump11289f42009-09-09 15:08:12 +00001942
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001943/// Checks if a the given expression evaluates to null.
1944///
1945/// \brief Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00001946static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001947 // If the expression has non-null type, it doesn't evaluate to null.
1948 if (auto nullability
1949 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
1950 if (*nullability == NullabilityKind::NonNull)
1951 return false;
1952 }
1953
Ted Kremeneka146db32014-01-17 06:24:47 +00001954 // As a special case, transparent unions initialized with zero are
1955 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001956 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00001957 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
1958 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001959 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00001960 if (const InitListExpr *ILE =
1961 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001962 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00001963 }
1964
1965 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00001966 return (!Expr->isValueDependent() &&
1967 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
1968 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001969}
1970
1971static void CheckNonNullArgument(Sema &S,
1972 const Expr *ArgExpr,
1973 SourceLocation CallSiteLoc) {
1974 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00001975 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
1976 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00001977}
1978
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001979bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
1980 FormatStringInfo FSI;
1981 if ((GetFormatStringType(Format) == FST_NSString) &&
1982 getFormatStringInfo(Format, false, &FSI)) {
1983 Idx = FSI.FormatIdx;
1984 return true;
1985 }
1986 return false;
1987}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001988/// \brief Diagnose use of %s directive in an NSString which is being passed
1989/// as formatting string to formatting method.
1990static void
1991DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
1992 const NamedDecl *FDecl,
1993 Expr **Args,
1994 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001995 unsigned Idx = 0;
1996 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001997 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
1998 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001999 Idx = 2;
2000 Format = true;
2001 }
2002 else
2003 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2004 if (S.GetFormatNSStringIdx(I, Idx)) {
2005 Format = true;
2006 break;
2007 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002008 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002009 if (!Format || NumArgs <= Idx)
2010 return;
2011 const Expr *FormatExpr = Args[Idx];
2012 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2013 FormatExpr = CSCE->getSubExpr();
2014 const StringLiteral *FormatString;
2015 if (const ObjCStringLiteral *OSL =
2016 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2017 FormatString = OSL->getString();
2018 else
2019 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2020 if (!FormatString)
2021 return;
2022 if (S.FormatStringHasSArg(FormatString)) {
2023 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2024 << "%s" << 1 << 1;
2025 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2026 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002027 }
2028}
2029
Douglas Gregorb4866e82015-06-19 18:13:19 +00002030/// Determine whether the given type has a non-null nullability annotation.
2031static bool isNonNullType(ASTContext &ctx, QualType type) {
2032 if (auto nullability = type->getNullability(ctx))
2033 return *nullability == NullabilityKind::NonNull;
2034
2035 return false;
2036}
2037
Ted Kremenek2bc73332014-01-17 06:24:43 +00002038static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00002039 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00002040 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00002041 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00002042 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002043 assert((FDecl || Proto) && "Need a function declaration or prototype");
2044
Ted Kremenek9aedc152014-01-17 06:24:56 +00002045 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00002046 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00002047 if (FDecl) {
2048 // Handle the nonnull attribute on the function/method declaration itself.
2049 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2050 if (!NonNull->args_size()) {
2051 // Easy case: all pointer arguments are nonnull.
2052 for (const auto *Arg : Args)
2053 if (S.isValidPointerAttrType(Arg->getType()))
2054 CheckNonNullArgument(S, Arg, CallSiteLoc);
2055 return;
2056 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002057
Douglas Gregorb4866e82015-06-19 18:13:19 +00002058 for (unsigned Val : NonNull->args()) {
2059 if (Val >= Args.size())
2060 continue;
2061 if (NonNullArgs.empty())
2062 NonNullArgs.resize(Args.size());
2063 NonNullArgs.set(Val);
2064 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002065 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002066 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002067
Douglas Gregorb4866e82015-06-19 18:13:19 +00002068 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2069 // Handle the nonnull attribute on the parameters of the
2070 // function/method.
2071 ArrayRef<ParmVarDecl*> parms;
2072 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2073 parms = FD->parameters();
2074 else
2075 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2076
2077 unsigned ParamIndex = 0;
2078 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2079 I != E; ++I, ++ParamIndex) {
2080 const ParmVarDecl *PVD = *I;
2081 if (PVD->hasAttr<NonNullAttr>() ||
2082 isNonNullType(S.Context, PVD->getType())) {
2083 if (NonNullArgs.empty())
2084 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00002085
Douglas Gregorb4866e82015-06-19 18:13:19 +00002086 NonNullArgs.set(ParamIndex);
2087 }
2088 }
2089 } else {
2090 // If we have a non-function, non-method declaration but no
2091 // function prototype, try to dig out the function prototype.
2092 if (!Proto) {
2093 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2094 QualType type = VD->getType().getNonReferenceType();
2095 if (auto pointerType = type->getAs<PointerType>())
2096 type = pointerType->getPointeeType();
2097 else if (auto blockType = type->getAs<BlockPointerType>())
2098 type = blockType->getPointeeType();
2099 // FIXME: data member pointers?
2100
2101 // Dig out the function prototype, if there is one.
2102 Proto = type->getAs<FunctionProtoType>();
2103 }
2104 }
2105
2106 // Fill in non-null argument information from the nullability
2107 // information on the parameter types (if we have them).
2108 if (Proto) {
2109 unsigned Index = 0;
2110 for (auto paramType : Proto->getParamTypes()) {
2111 if (isNonNullType(S.Context, paramType)) {
2112 if (NonNullArgs.empty())
2113 NonNullArgs.resize(Args.size());
2114
2115 NonNullArgs.set(Index);
2116 }
2117
2118 ++Index;
2119 }
2120 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002121 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002122
Douglas Gregorb4866e82015-06-19 18:13:19 +00002123 // Check for non-null arguments.
2124 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2125 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00002126 if (NonNullArgs[ArgIndex])
2127 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00002128 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002129}
2130
Richard Smith55ce3522012-06-25 20:30:08 +00002131/// Handles the checks for format strings, non-POD arguments to vararg
2132/// functions, and NULL arguments passed to non-NULL parameters.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002133void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2134 ArrayRef<const Expr *> Args, bool IsMemberFunction,
Alp Toker9cacbab2014-01-20 20:26:09 +00002135 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +00002136 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00002137 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00002138 if (CurContext->isDependentContext())
2139 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00002140
Ted Kremenekb8176da2010-09-09 04:33:05 +00002141 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00002142 llvm::SmallBitVector CheckedVarArgs;
2143 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002144 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002145 // Only create vector if there are format attributes.
2146 CheckedVarArgs.resize(Args.size());
2147
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002148 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00002149 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002150 }
Richard Smithd7293d72013-08-05 18:49:43 +00002151 }
Richard Smith55ce3522012-06-25 20:30:08 +00002152
2153 // Refuse POD arguments that weren't caught by the format string
2154 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +00002155 if (CallType != VariadicDoesNotApply) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002156 unsigned NumParams = Proto ? Proto->getNumParams()
2157 : FDecl && isa<FunctionDecl>(FDecl)
2158 ? cast<FunctionDecl>(FDecl)->getNumParams()
2159 : FDecl && isa<ObjCMethodDecl>(FDecl)
2160 ? cast<ObjCMethodDecl>(FDecl)->param_size()
2161 : 0;
2162
Alp Toker9cacbab2014-01-20 20:26:09 +00002163 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002164 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00002165 if (const Expr *Arg = Args[ArgIdx]) {
2166 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2167 checkVariadicArgument(Arg, CallType);
2168 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002169 }
Richard Smithd7293d72013-08-05 18:49:43 +00002170 }
Mike Stump11289f42009-09-09 15:08:12 +00002171
Douglas Gregorb4866e82015-06-19 18:13:19 +00002172 if (FDecl || Proto) {
2173 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002174
Richard Trieu41bc0992013-06-22 00:20:41 +00002175 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002176 if (FDecl) {
2177 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
2178 CheckArgumentWithTypeTag(I, Args.data());
2179 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002180 }
Richard Smith55ce3522012-06-25 20:30:08 +00002181}
2182
2183/// CheckConstructorCall - Check a constructor call for correctness and safety
2184/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002185void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2186 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002187 const FunctionProtoType *Proto,
2188 SourceLocation Loc) {
2189 VariadicCallType CallType =
2190 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Douglas Gregorb4866e82015-06-19 18:13:19 +00002191 checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(),
2192 CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00002193}
2194
2195/// CheckFunctionCall - Check a direct function call for various correctness
2196/// and safety properties not strictly enforced by the C type system.
2197bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2198 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002199 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2200 isa<CXXMethodDecl>(FDecl);
2201 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2202 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00002203 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2204 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00002205 Expr** Args = TheCall->getArgs();
2206 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +00002207 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002208 // If this is a call to a member operator, hide the first argument
2209 // from checkCall.
2210 // FIXME: Our choice of AST representation here is less than ideal.
2211 ++Args;
2212 --NumArgs;
2213 }
Douglas Gregorb4866e82015-06-19 18:13:19 +00002214 checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00002215 IsMemberFunction, TheCall->getRParenLoc(),
2216 TheCall->getCallee()->getSourceRange(), CallType);
2217
2218 IdentifierInfo *FnInfo = FDecl->getIdentifier();
2219 // None of the checks below are needed for functions that don't have
2220 // simple names (e.g., C++ conversion functions).
2221 if (!FnInfo)
2222 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002223
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00002224 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002225 if (getLangOpts().ObjC1)
2226 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00002227
Anna Zaks22122702012-01-17 00:37:07 +00002228 unsigned CMId = FDecl->getMemoryFunctionKind();
2229 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00002230 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00002231
Anna Zaks201d4892012-01-13 21:52:01 +00002232 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00002233 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00002234 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00002235 else if (CMId == Builtin::BIstrncat)
2236 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00002237 else
Anna Zaks22122702012-01-17 00:37:07 +00002238 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00002239
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002240 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00002241}
2242
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002243bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00002244 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00002245 VariadicCallType CallType =
2246 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002247
Douglas Gregorb4866e82015-06-19 18:13:19 +00002248 checkCall(Method, nullptr, Args,
2249 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
2250 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002251
2252 return false;
2253}
2254
Richard Trieu664c4c62013-06-20 21:03:13 +00002255bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2256 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00002257 QualType Ty;
2258 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002259 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002260 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002261 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002262 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002263 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002264
Douglas Gregorb4866e82015-06-19 18:13:19 +00002265 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2266 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002267 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002268
Richard Trieu664c4c62013-06-20 21:03:13 +00002269 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00002270 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00002271 CallType = VariadicDoesNotApply;
2272 } else if (Ty->isBlockPointerType()) {
2273 CallType = VariadicBlock;
2274 } else { // Ty->isFunctionPointerType()
2275 CallType = VariadicFunction;
2276 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002277
Douglas Gregorb4866e82015-06-19 18:13:19 +00002278 checkCall(NDecl, Proto,
2279 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2280 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00002281 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00002282
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002283 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00002284}
2285
Richard Trieu41bc0992013-06-22 00:20:41 +00002286/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2287/// such as function pointers returned from functions.
2288bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002289 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00002290 TheCall->getCallee());
Douglas Gregorb4866e82015-06-19 18:13:19 +00002291 checkCall(/*FDecl=*/nullptr, Proto,
Craig Topper8c2a2a02014-08-30 16:55:39 +00002292 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00002293 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00002294 TheCall->getCallee()->getSourceRange(), CallType);
2295
2296 return false;
2297}
2298
Tim Northovere94a34c2014-03-11 10:49:14 +00002299static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
JF Bastiendda2cb12016-04-18 18:01:49 +00002300 if (!llvm::isValidAtomicOrderingCABI(Ordering))
Tim Northovere94a34c2014-03-11 10:49:14 +00002301 return false;
2302
JF Bastiendda2cb12016-04-18 18:01:49 +00002303 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
Tim Northovere94a34c2014-03-11 10:49:14 +00002304 switch (Op) {
2305 case AtomicExpr::AO__c11_atomic_init:
2306 llvm_unreachable("There is no ordering argument for an init");
2307
2308 case AtomicExpr::AO__c11_atomic_load:
2309 case AtomicExpr::AO__atomic_load_n:
2310 case AtomicExpr::AO__atomic_load:
JF Bastiendda2cb12016-04-18 18:01:49 +00002311 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2312 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002313
2314 case AtomicExpr::AO__c11_atomic_store:
2315 case AtomicExpr::AO__atomic_store:
2316 case AtomicExpr::AO__atomic_store_n:
JF Bastiendda2cb12016-04-18 18:01:49 +00002317 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2318 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2319 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002320
2321 default:
2322 return true;
2323 }
2324}
2325
Richard Smithfeea8832012-04-12 05:08:17 +00002326ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2327 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002328 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2329 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002330
Richard Smithfeea8832012-04-12 05:08:17 +00002331 // All these operations take one of the following forms:
2332 enum {
2333 // C __c11_atomic_init(A *, C)
2334 Init,
2335 // C __c11_atomic_load(A *, int)
2336 Load,
2337 // void __atomic_load(A *, CP, int)
Eric Fiselier8d662442016-03-30 23:39:56 +00002338 LoadCopy,
2339 // void __atomic_store(A *, CP, int)
Richard Smithfeea8832012-04-12 05:08:17 +00002340 Copy,
2341 // C __c11_atomic_add(A *, M, int)
2342 Arithmetic,
2343 // C __atomic_exchange_n(A *, CP, int)
2344 Xchg,
2345 // void __atomic_exchange(A *, C *, CP, int)
2346 GNUXchg,
2347 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2348 C11CmpXchg,
2349 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2350 GNUCmpXchg
2351 } Form = Init;
Eric Fiselier8d662442016-03-30 23:39:56 +00002352 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2353 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
Richard Smithfeea8832012-04-12 05:08:17 +00002354 // where:
2355 // C is an appropriate type,
2356 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2357 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2358 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2359 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002360
Gabor Horvath98bd0982015-03-16 09:59:54 +00002361 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2362 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2363 AtomicExpr::AO__atomic_load,
2364 "need to update code for modified C11 atomics");
Richard Smithfeea8832012-04-12 05:08:17 +00002365 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
2366 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
2367 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2368 Op == AtomicExpr::AO__atomic_store_n ||
2369 Op == AtomicExpr::AO__atomic_exchange_n ||
2370 Op == AtomicExpr::AO__atomic_compare_exchange_n;
2371 bool IsAddSub = false;
2372
2373 switch (Op) {
2374 case AtomicExpr::AO__c11_atomic_init:
2375 Form = Init;
2376 break;
2377
2378 case AtomicExpr::AO__c11_atomic_load:
2379 case AtomicExpr::AO__atomic_load_n:
2380 Form = Load;
2381 break;
2382
Richard Smithfeea8832012-04-12 05:08:17 +00002383 case AtomicExpr::AO__atomic_load:
Eric Fiselier8d662442016-03-30 23:39:56 +00002384 Form = LoadCopy;
2385 break;
2386
2387 case AtomicExpr::AO__c11_atomic_store:
Richard Smithfeea8832012-04-12 05:08:17 +00002388 case AtomicExpr::AO__atomic_store:
2389 case AtomicExpr::AO__atomic_store_n:
2390 Form = Copy;
2391 break;
2392
2393 case AtomicExpr::AO__c11_atomic_fetch_add:
2394 case AtomicExpr::AO__c11_atomic_fetch_sub:
2395 case AtomicExpr::AO__atomic_fetch_add:
2396 case AtomicExpr::AO__atomic_fetch_sub:
2397 case AtomicExpr::AO__atomic_add_fetch:
2398 case AtomicExpr::AO__atomic_sub_fetch:
2399 IsAddSub = true;
2400 // Fall through.
2401 case AtomicExpr::AO__c11_atomic_fetch_and:
2402 case AtomicExpr::AO__c11_atomic_fetch_or:
2403 case AtomicExpr::AO__c11_atomic_fetch_xor:
2404 case AtomicExpr::AO__atomic_fetch_and:
2405 case AtomicExpr::AO__atomic_fetch_or:
2406 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00002407 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00002408 case AtomicExpr::AO__atomic_and_fetch:
2409 case AtomicExpr::AO__atomic_or_fetch:
2410 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00002411 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00002412 Form = Arithmetic;
2413 break;
2414
2415 case AtomicExpr::AO__c11_atomic_exchange:
2416 case AtomicExpr::AO__atomic_exchange_n:
2417 Form = Xchg;
2418 break;
2419
2420 case AtomicExpr::AO__atomic_exchange:
2421 Form = GNUXchg;
2422 break;
2423
2424 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
2425 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
2426 Form = C11CmpXchg;
2427 break;
2428
2429 case AtomicExpr::AO__atomic_compare_exchange:
2430 case AtomicExpr::AO__atomic_compare_exchange_n:
2431 Form = GNUCmpXchg;
2432 break;
2433 }
2434
2435 // Check we have the right number of arguments.
2436 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002437 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00002438 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002439 << TheCall->getCallee()->getSourceRange();
2440 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00002441 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
2442 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002443 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00002444 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002445 << TheCall->getCallee()->getSourceRange();
2446 return ExprError();
2447 }
2448
Richard Smithfeea8832012-04-12 05:08:17 +00002449 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002450 Expr *Ptr = TheCall->getArg(0);
George Burgess IV92b43a42016-07-21 03:28:13 +00002451 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
2452 if (ConvertedPtr.isInvalid())
2453 return ExprError();
2454
2455 Ptr = ConvertedPtr.get();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002456 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
2457 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00002458 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002459 << Ptr->getType() << Ptr->getSourceRange();
2460 return ExprError();
2461 }
2462
Richard Smithfeea8832012-04-12 05:08:17 +00002463 // For a __c11 builtin, this should be a pointer to an _Atomic type.
2464 QualType AtomTy = pointerType->getPointeeType(); // 'A'
2465 QualType ValType = AtomTy; // 'C'
2466 if (IsC11) {
2467 if (!AtomTy->isAtomicType()) {
2468 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
2469 << Ptr->getType() << Ptr->getSourceRange();
2470 return ExprError();
2471 }
Richard Smithe00921a2012-09-15 06:09:58 +00002472 if (AtomTy.isConstQualified()) {
2473 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
2474 << Ptr->getType() << Ptr->getSourceRange();
2475 return ExprError();
2476 }
Richard Smithfeea8832012-04-12 05:08:17 +00002477 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiselier8d662442016-03-30 23:39:56 +00002478 } else if (Form != Load && Form != LoadCopy) {
Eric Fiseliera3a7c562015-10-04 00:11:02 +00002479 if (ValType.isConstQualified()) {
2480 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
2481 << Ptr->getType() << Ptr->getSourceRange();
2482 return ExprError();
2483 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002484 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002485
Richard Smithfeea8832012-04-12 05:08:17 +00002486 // For an arithmetic operation, the implied arithmetic must be well-formed.
2487 if (Form == Arithmetic) {
2488 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
2489 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
2490 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2491 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2492 return ExprError();
2493 }
2494 if (!IsAddSub && !ValType->isIntegerType()) {
2495 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
2496 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2497 return ExprError();
2498 }
David Majnemere85cff82015-01-28 05:48:06 +00002499 if (IsC11 && ValType->isPointerType() &&
2500 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
2501 diag::err_incomplete_type)) {
2502 return ExprError();
2503 }
Richard Smithfeea8832012-04-12 05:08:17 +00002504 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
2505 // For __atomic_*_n operations, the value type must be a scalar integral or
2506 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002507 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00002508 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2509 return ExprError();
2510 }
2511
Eli Friedmanaa769812013-09-11 03:49:34 +00002512 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
2513 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00002514 // For GNU atomics, require a trivially-copyable type. This is not part of
2515 // the GNU atomics specification, but we enforce it for sanity.
2516 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002517 << Ptr->getType() << Ptr->getSourceRange();
2518 return ExprError();
2519 }
2520
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002521 switch (ValType.getObjCLifetime()) {
2522 case Qualifiers::OCL_None:
2523 case Qualifiers::OCL_ExplicitNone:
2524 // okay
2525 break;
2526
2527 case Qualifiers::OCL_Weak:
2528 case Qualifiers::OCL_Strong:
2529 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00002530 // FIXME: Can this happen? By this point, ValType should be known
2531 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002532 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
2533 << ValType << Ptr->getSourceRange();
2534 return ExprError();
2535 }
2536
David Majnemerc6eb6502015-06-03 00:26:35 +00002537 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
2538 // volatile-ness of the pointee-type inject itself into the result or the
Eric Fiselier8d662442016-03-30 23:39:56 +00002539 // other operands. Similarly atomic_load can take a pointer to a const 'A'.
David Majnemerc6eb6502015-06-03 00:26:35 +00002540 ValType.removeLocalVolatile();
Eric Fiselier8d662442016-03-30 23:39:56 +00002541 ValType.removeLocalConst();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002542 QualType ResultType = ValType;
Eric Fiselier8d662442016-03-30 23:39:56 +00002543 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002544 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00002545 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002546 ResultType = Context.BoolTy;
2547
Richard Smithfeea8832012-04-12 05:08:17 +00002548 // The type of a parameter passed 'by value'. In the GNU atomics, such
2549 // arguments are actually passed as pointers.
2550 QualType ByValType = ValType; // 'CP'
2551 if (!IsC11 && !IsN)
2552 ByValType = Ptr->getType();
2553
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002554 // The first argument --- the pointer --- has a fixed type; we
2555 // deduce the types of the rest of the arguments accordingly. Walk
2556 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00002557 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002558 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00002559 if (i < NumVals[Form] + 1) {
2560 switch (i) {
2561 case 1:
2562 // The second argument is the non-atomic operand. For arithmetic, this
2563 // is always passed by value, and for a compare_exchange it is always
2564 // passed by address. For the rest, GNU uses by-address and C11 uses
2565 // by-value.
2566 assert(Form != Load);
2567 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
2568 Ty = ValType;
2569 else if (Form == Copy || Form == Xchg)
2570 Ty = ByValType;
2571 else if (Form == Arithmetic)
2572 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00002573 else {
2574 Expr *ValArg = TheCall->getArg(i);
2575 unsigned AS = 0;
2576 // Keep address space of non-atomic pointer type.
2577 if (const PointerType *PtrTy =
2578 ValArg->getType()->getAs<PointerType>()) {
2579 AS = PtrTy->getPointeeType().getAddressSpace();
2580 }
2581 Ty = Context.getPointerType(
2582 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
2583 }
Richard Smithfeea8832012-04-12 05:08:17 +00002584 break;
2585 case 2:
2586 // The third argument to compare_exchange / GNU exchange is a
2587 // (pointer to a) desired value.
2588 Ty = ByValType;
2589 break;
2590 case 3:
2591 // The fourth argument to GNU compare_exchange is a 'weak' flag.
2592 Ty = Context.BoolTy;
2593 break;
2594 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002595 } else {
2596 // The order(s) are always converted to int.
2597 Ty = Context.IntTy;
2598 }
Richard Smithfeea8832012-04-12 05:08:17 +00002599
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002600 InitializedEntity Entity =
2601 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00002602 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002603 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2604 if (Arg.isInvalid())
2605 return true;
2606 TheCall->setArg(i, Arg.get());
2607 }
2608
Richard Smithfeea8832012-04-12 05:08:17 +00002609 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002610 SmallVector<Expr*, 5> SubExprs;
2611 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00002612 switch (Form) {
2613 case Init:
2614 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00002615 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00002616 break;
2617 case Load:
2618 SubExprs.push_back(TheCall->getArg(1)); // Order
2619 break;
Eric Fiselier8d662442016-03-30 23:39:56 +00002620 case LoadCopy:
Richard Smithfeea8832012-04-12 05:08:17 +00002621 case Copy:
2622 case Arithmetic:
2623 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002624 SubExprs.push_back(TheCall->getArg(2)); // Order
2625 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00002626 break;
2627 case GNUXchg:
2628 // Note, AtomicExpr::getVal2() has a special case for this atomic.
2629 SubExprs.push_back(TheCall->getArg(3)); // Order
2630 SubExprs.push_back(TheCall->getArg(1)); // Val1
2631 SubExprs.push_back(TheCall->getArg(2)); // Val2
2632 break;
2633 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002634 SubExprs.push_back(TheCall->getArg(3)); // Order
2635 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002636 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00002637 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00002638 break;
2639 case GNUCmpXchg:
2640 SubExprs.push_back(TheCall->getArg(4)); // Order
2641 SubExprs.push_back(TheCall->getArg(1)); // Val1
2642 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
2643 SubExprs.push_back(TheCall->getArg(2)); // Val2
2644 SubExprs.push_back(TheCall->getArg(3)); // Weak
2645 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002646 }
Tim Northovere94a34c2014-03-11 10:49:14 +00002647
2648 if (SubExprs.size() >= 2 && Form != Init) {
2649 llvm::APSInt Result(32);
2650 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
2651 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00002652 Diag(SubExprs[1]->getLocStart(),
2653 diag::warn_atomic_op_has_invalid_memory_order)
2654 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00002655 }
2656
Fariborz Jahanian615de762013-05-28 17:37:39 +00002657 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
2658 SubExprs, ResultType, Op,
2659 TheCall->getRParenLoc());
2660
2661 if ((Op == AtomicExpr::AO__c11_atomic_load ||
2662 (Op == AtomicExpr::AO__c11_atomic_store)) &&
2663 Context.AtomicUsesUnsupportedLibcall(AE))
2664 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
2665 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002666
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002667 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002668}
2669
John McCall29ad95b2011-08-27 01:09:30 +00002670/// checkBuiltinArgument - Given a call to a builtin function, perform
2671/// normal type-checking on the given argument, updating the call in
2672/// place. This is useful when a builtin function requires custom
2673/// type-checking for some of its arguments but not necessarily all of
2674/// them.
2675///
2676/// Returns true on error.
2677static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
2678 FunctionDecl *Fn = E->getDirectCallee();
2679 assert(Fn && "builtin call without direct callee!");
2680
2681 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
2682 InitializedEntity Entity =
2683 InitializedEntity::InitializeParameter(S.Context, Param);
2684
2685 ExprResult Arg = E->getArg(0);
2686 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
2687 if (Arg.isInvalid())
2688 return true;
2689
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002690 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00002691 return false;
2692}
2693
Chris Lattnerdc046542009-05-08 06:58:22 +00002694/// SemaBuiltinAtomicOverloaded - We have a call to a function like
2695/// __sync_fetch_and_add, which is an overloaded function based on the pointer
2696/// type of its first argument. The main ActOnCallExpr routines have already
2697/// promoted the types of arguments because all of these calls are prototyped as
2698/// void(...).
2699///
2700/// This function goes through and does final semantic checking for these
2701/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00002702ExprResult
2703Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002704 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00002705 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2706 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2707
2708 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002709 if (TheCall->getNumArgs() < 1) {
2710 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2711 << 0 << 1 << TheCall->getNumArgs()
2712 << TheCall->getCallee()->getSourceRange();
2713 return ExprError();
2714 }
Mike Stump11289f42009-09-09 15:08:12 +00002715
Chris Lattnerdc046542009-05-08 06:58:22 +00002716 // Inspect the first argument of the atomic builtin. This should always be
2717 // a pointer type, whose element is an integral scalar or pointer type.
2718 // Because it is a pointer type, we don't have to worry about any implicit
2719 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002720 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00002721 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00002722 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
2723 if (FirstArgResult.isInvalid())
2724 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002725 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00002726 TheCall->setArg(0, FirstArg);
2727
John McCall31168b02011-06-15 23:02:42 +00002728 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
2729 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002730 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
2731 << FirstArg->getType() << FirstArg->getSourceRange();
2732 return ExprError();
2733 }
Mike Stump11289f42009-09-09 15:08:12 +00002734
John McCall31168b02011-06-15 23:02:42 +00002735 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00002736 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002737 !ValType->isBlockPointerType()) {
2738 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
2739 << FirstArg->getType() << FirstArg->getSourceRange();
2740 return ExprError();
2741 }
Chris Lattnerdc046542009-05-08 06:58:22 +00002742
John McCall31168b02011-06-15 23:02:42 +00002743 switch (ValType.getObjCLifetime()) {
2744 case Qualifiers::OCL_None:
2745 case Qualifiers::OCL_ExplicitNone:
2746 // okay
2747 break;
2748
2749 case Qualifiers::OCL_Weak:
2750 case Qualifiers::OCL_Strong:
2751 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00002752 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00002753 << ValType << FirstArg->getSourceRange();
2754 return ExprError();
2755 }
2756
John McCallb50451a2011-10-05 07:41:44 +00002757 // Strip any qualifiers off ValType.
2758 ValType = ValType.getUnqualifiedType();
2759
Chandler Carruth3973af72010-07-18 20:54:12 +00002760 // The majority of builtins return a value, but a few have special return
2761 // types, so allow them to override appropriately below.
2762 QualType ResultType = ValType;
2763
Chris Lattnerdc046542009-05-08 06:58:22 +00002764 // We need to figure out which concrete builtin this maps onto. For example,
2765 // __sync_fetch_and_add with a 2 byte object turns into
2766 // __sync_fetch_and_add_2.
2767#define BUILTIN_ROW(x) \
2768 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
2769 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00002770
Chris Lattnerdc046542009-05-08 06:58:22 +00002771 static const unsigned BuiltinIndices[][5] = {
2772 BUILTIN_ROW(__sync_fetch_and_add),
2773 BUILTIN_ROW(__sync_fetch_and_sub),
2774 BUILTIN_ROW(__sync_fetch_and_or),
2775 BUILTIN_ROW(__sync_fetch_and_and),
2776 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00002777 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00002778
Chris Lattnerdc046542009-05-08 06:58:22 +00002779 BUILTIN_ROW(__sync_add_and_fetch),
2780 BUILTIN_ROW(__sync_sub_and_fetch),
2781 BUILTIN_ROW(__sync_and_and_fetch),
2782 BUILTIN_ROW(__sync_or_and_fetch),
2783 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00002784 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00002785
Chris Lattnerdc046542009-05-08 06:58:22 +00002786 BUILTIN_ROW(__sync_val_compare_and_swap),
2787 BUILTIN_ROW(__sync_bool_compare_and_swap),
2788 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00002789 BUILTIN_ROW(__sync_lock_release),
2790 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00002791 };
Mike Stump11289f42009-09-09 15:08:12 +00002792#undef BUILTIN_ROW
2793
Chris Lattnerdc046542009-05-08 06:58:22 +00002794 // Determine the index of the size.
2795 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00002796 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00002797 case 1: SizeIndex = 0; break;
2798 case 2: SizeIndex = 1; break;
2799 case 4: SizeIndex = 2; break;
2800 case 8: SizeIndex = 3; break;
2801 case 16: SizeIndex = 4; break;
2802 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002803 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
2804 << FirstArg->getType() << FirstArg->getSourceRange();
2805 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00002806 }
Mike Stump11289f42009-09-09 15:08:12 +00002807
Chris Lattnerdc046542009-05-08 06:58:22 +00002808 // Each of these builtins has one pointer argument, followed by some number of
2809 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
2810 // that we ignore. Find out which row of BuiltinIndices to read from as well
2811 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00002812 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00002813 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00002814 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00002815 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00002816 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00002817 case Builtin::BI__sync_fetch_and_add:
2818 case Builtin::BI__sync_fetch_and_add_1:
2819 case Builtin::BI__sync_fetch_and_add_2:
2820 case Builtin::BI__sync_fetch_and_add_4:
2821 case Builtin::BI__sync_fetch_and_add_8:
2822 case Builtin::BI__sync_fetch_and_add_16:
2823 BuiltinIndex = 0;
2824 break;
2825
2826 case Builtin::BI__sync_fetch_and_sub:
2827 case Builtin::BI__sync_fetch_and_sub_1:
2828 case Builtin::BI__sync_fetch_and_sub_2:
2829 case Builtin::BI__sync_fetch_and_sub_4:
2830 case Builtin::BI__sync_fetch_and_sub_8:
2831 case Builtin::BI__sync_fetch_and_sub_16:
2832 BuiltinIndex = 1;
2833 break;
2834
2835 case Builtin::BI__sync_fetch_and_or:
2836 case Builtin::BI__sync_fetch_and_or_1:
2837 case Builtin::BI__sync_fetch_and_or_2:
2838 case Builtin::BI__sync_fetch_and_or_4:
2839 case Builtin::BI__sync_fetch_and_or_8:
2840 case Builtin::BI__sync_fetch_and_or_16:
2841 BuiltinIndex = 2;
2842 break;
2843
2844 case Builtin::BI__sync_fetch_and_and:
2845 case Builtin::BI__sync_fetch_and_and_1:
2846 case Builtin::BI__sync_fetch_and_and_2:
2847 case Builtin::BI__sync_fetch_and_and_4:
2848 case Builtin::BI__sync_fetch_and_and_8:
2849 case Builtin::BI__sync_fetch_and_and_16:
2850 BuiltinIndex = 3;
2851 break;
Mike Stump11289f42009-09-09 15:08:12 +00002852
Douglas Gregor73722482011-11-28 16:30:08 +00002853 case Builtin::BI__sync_fetch_and_xor:
2854 case Builtin::BI__sync_fetch_and_xor_1:
2855 case Builtin::BI__sync_fetch_and_xor_2:
2856 case Builtin::BI__sync_fetch_and_xor_4:
2857 case Builtin::BI__sync_fetch_and_xor_8:
2858 case Builtin::BI__sync_fetch_and_xor_16:
2859 BuiltinIndex = 4;
2860 break;
2861
Hal Finkeld2208b52014-10-02 20:53:50 +00002862 case Builtin::BI__sync_fetch_and_nand:
2863 case Builtin::BI__sync_fetch_and_nand_1:
2864 case Builtin::BI__sync_fetch_and_nand_2:
2865 case Builtin::BI__sync_fetch_and_nand_4:
2866 case Builtin::BI__sync_fetch_and_nand_8:
2867 case Builtin::BI__sync_fetch_and_nand_16:
2868 BuiltinIndex = 5;
2869 WarnAboutSemanticsChange = true;
2870 break;
2871
Douglas Gregor73722482011-11-28 16:30:08 +00002872 case Builtin::BI__sync_add_and_fetch:
2873 case Builtin::BI__sync_add_and_fetch_1:
2874 case Builtin::BI__sync_add_and_fetch_2:
2875 case Builtin::BI__sync_add_and_fetch_4:
2876 case Builtin::BI__sync_add_and_fetch_8:
2877 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002878 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00002879 break;
2880
2881 case Builtin::BI__sync_sub_and_fetch:
2882 case Builtin::BI__sync_sub_and_fetch_1:
2883 case Builtin::BI__sync_sub_and_fetch_2:
2884 case Builtin::BI__sync_sub_and_fetch_4:
2885 case Builtin::BI__sync_sub_and_fetch_8:
2886 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002887 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00002888 break;
2889
2890 case Builtin::BI__sync_and_and_fetch:
2891 case Builtin::BI__sync_and_and_fetch_1:
2892 case Builtin::BI__sync_and_and_fetch_2:
2893 case Builtin::BI__sync_and_and_fetch_4:
2894 case Builtin::BI__sync_and_and_fetch_8:
2895 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002896 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00002897 break;
2898
2899 case Builtin::BI__sync_or_and_fetch:
2900 case Builtin::BI__sync_or_and_fetch_1:
2901 case Builtin::BI__sync_or_and_fetch_2:
2902 case Builtin::BI__sync_or_and_fetch_4:
2903 case Builtin::BI__sync_or_and_fetch_8:
2904 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002905 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00002906 break;
2907
2908 case Builtin::BI__sync_xor_and_fetch:
2909 case Builtin::BI__sync_xor_and_fetch_1:
2910 case Builtin::BI__sync_xor_and_fetch_2:
2911 case Builtin::BI__sync_xor_and_fetch_4:
2912 case Builtin::BI__sync_xor_and_fetch_8:
2913 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002914 BuiltinIndex = 10;
2915 break;
2916
2917 case Builtin::BI__sync_nand_and_fetch:
2918 case Builtin::BI__sync_nand_and_fetch_1:
2919 case Builtin::BI__sync_nand_and_fetch_2:
2920 case Builtin::BI__sync_nand_and_fetch_4:
2921 case Builtin::BI__sync_nand_and_fetch_8:
2922 case Builtin::BI__sync_nand_and_fetch_16:
2923 BuiltinIndex = 11;
2924 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00002925 break;
Mike Stump11289f42009-09-09 15:08:12 +00002926
Chris Lattnerdc046542009-05-08 06:58:22 +00002927 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00002928 case Builtin::BI__sync_val_compare_and_swap_1:
2929 case Builtin::BI__sync_val_compare_and_swap_2:
2930 case Builtin::BI__sync_val_compare_and_swap_4:
2931 case Builtin::BI__sync_val_compare_and_swap_8:
2932 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002933 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00002934 NumFixed = 2;
2935 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002936
Chris Lattnerdc046542009-05-08 06:58:22 +00002937 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00002938 case Builtin::BI__sync_bool_compare_and_swap_1:
2939 case Builtin::BI__sync_bool_compare_and_swap_2:
2940 case Builtin::BI__sync_bool_compare_and_swap_4:
2941 case Builtin::BI__sync_bool_compare_and_swap_8:
2942 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002943 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00002944 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00002945 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00002946 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002947
2948 case Builtin::BI__sync_lock_test_and_set:
2949 case Builtin::BI__sync_lock_test_and_set_1:
2950 case Builtin::BI__sync_lock_test_and_set_2:
2951 case Builtin::BI__sync_lock_test_and_set_4:
2952 case Builtin::BI__sync_lock_test_and_set_8:
2953 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002954 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00002955 break;
2956
Chris Lattnerdc046542009-05-08 06:58:22 +00002957 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00002958 case Builtin::BI__sync_lock_release_1:
2959 case Builtin::BI__sync_lock_release_2:
2960 case Builtin::BI__sync_lock_release_4:
2961 case Builtin::BI__sync_lock_release_8:
2962 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002963 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00002964 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00002965 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00002966 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002967
2968 case Builtin::BI__sync_swap:
2969 case Builtin::BI__sync_swap_1:
2970 case Builtin::BI__sync_swap_2:
2971 case Builtin::BI__sync_swap_4:
2972 case Builtin::BI__sync_swap_8:
2973 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002974 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00002975 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00002976 }
Mike Stump11289f42009-09-09 15:08:12 +00002977
Chris Lattnerdc046542009-05-08 06:58:22 +00002978 // Now that we know how many fixed arguments we expect, first check that we
2979 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002980 if (TheCall->getNumArgs() < 1+NumFixed) {
2981 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2982 << 0 << 1+NumFixed << TheCall->getNumArgs()
2983 << TheCall->getCallee()->getSourceRange();
2984 return ExprError();
2985 }
Mike Stump11289f42009-09-09 15:08:12 +00002986
Hal Finkeld2208b52014-10-02 20:53:50 +00002987 if (WarnAboutSemanticsChange) {
2988 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
2989 << TheCall->getCallee()->getSourceRange();
2990 }
2991
Chris Lattner5b9241b2009-05-08 15:36:58 +00002992 // Get the decl for the concrete builtin from this, we can tell what the
2993 // concrete integer type we should convert to is.
2994 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Eric Christopher02d5d862015-08-06 01:01:12 +00002995 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00002996 FunctionDecl *NewBuiltinDecl;
2997 if (NewBuiltinID == BuiltinID)
2998 NewBuiltinDecl = FDecl;
2999 else {
3000 // Perform builtin lookup to avoid redeclaring it.
3001 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3002 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3003 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3004 assert(Res.getFoundDecl());
3005 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00003006 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003007 return ExprError();
3008 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003009
John McCallcf142162010-08-07 06:22:56 +00003010 // The first argument --- the pointer --- has a fixed type; we
3011 // deduce the types of the rest of the arguments accordingly. Walk
3012 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00003013 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00003014 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00003015
Chris Lattnerdc046542009-05-08 06:58:22 +00003016 // GCC does an implicit conversion to the pointer or integer ValType. This
3017 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00003018 // Initialize the argument.
3019 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3020 ValType, /*consume*/ false);
3021 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00003022 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003023 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003024
Chris Lattnerdc046542009-05-08 06:58:22 +00003025 // Okay, we have something that *can* be converted to the right type. Check
3026 // to see if there is a potentially weird extension going on here. This can
3027 // happen when you do an atomic operation on something like an char* and
3028 // pass in 42. The 42 gets converted to char. This is even more strange
3029 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00003030 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003031 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00003032 }
Mike Stump11289f42009-09-09 15:08:12 +00003033
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003034 ASTContext& Context = this->getASTContext();
3035
3036 // Create a new DeclRefExpr to refer to the new decl.
3037 DeclRefExpr* NewDRE = DeclRefExpr::Create(
3038 Context,
3039 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00003040 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003041 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00003042 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003043 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00003044 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003045 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00003046
Chris Lattnerdc046542009-05-08 06:58:22 +00003047 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00003048 // FIXME: This loses syntactic information.
3049 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
3050 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3051 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003052 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00003053
Chandler Carruthbc8cab12010-07-18 07:23:17 +00003054 // Change the result type of the call to match the original value type. This
3055 // is arbitrary, but the codegen for these builtins ins design to handle it
3056 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00003057 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003058
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003059 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00003060}
3061
Michael Zolotukhin84df1232015-09-08 23:52:33 +00003062/// SemaBuiltinNontemporalOverloaded - We have a call to
3063/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3064/// overloaded function based on the pointer type of its last argument.
3065///
3066/// This function goes through and does final semantic checking for these
3067/// builtins.
3068ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3069 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3070 DeclRefExpr *DRE =
3071 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3072 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3073 unsigned BuiltinID = FDecl->getBuiltinID();
3074 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3075 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3076 "Unexpected nontemporal load/store builtin!");
3077 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3078 unsigned numArgs = isStore ? 2 : 1;
3079
3080 // Ensure that we have the proper number of arguments.
3081 if (checkArgCount(*this, TheCall, numArgs))
3082 return ExprError();
3083
3084 // Inspect the last argument of the nontemporal builtin. This should always
3085 // be a pointer type, from which we imply the type of the memory access.
3086 // Because it is a pointer type, we don't have to worry about any implicit
3087 // casts here.
3088 Expr *PointerArg = TheCall->getArg(numArgs - 1);
3089 ExprResult PointerArgResult =
3090 DefaultFunctionArrayLvalueConversion(PointerArg);
3091
3092 if (PointerArgResult.isInvalid())
3093 return ExprError();
3094 PointerArg = PointerArgResult.get();
3095 TheCall->setArg(numArgs - 1, PointerArg);
3096
3097 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3098 if (!pointerType) {
3099 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3100 << PointerArg->getType() << PointerArg->getSourceRange();
3101 return ExprError();
3102 }
3103
3104 QualType ValType = pointerType->getPointeeType();
3105
3106 // Strip any qualifiers off ValType.
3107 ValType = ValType.getUnqualifiedType();
3108 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3109 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3110 !ValType->isVectorType()) {
3111 Diag(DRE->getLocStart(),
3112 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3113 << PointerArg->getType() << PointerArg->getSourceRange();
3114 return ExprError();
3115 }
3116
3117 if (!isStore) {
3118 TheCall->setType(ValType);
3119 return TheCallResult;
3120 }
3121
3122 ExprResult ValArg = TheCall->getArg(0);
3123 InitializedEntity Entity = InitializedEntity::InitializeParameter(
3124 Context, ValType, /*consume*/ false);
3125 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3126 if (ValArg.isInvalid())
3127 return ExprError();
3128
3129 TheCall->setArg(0, ValArg.get());
3130 TheCall->setType(Context.VoidTy);
3131 return TheCallResult;
3132}
3133
Chris Lattner6436fb62009-02-18 06:01:06 +00003134/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00003135/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00003136/// Note: It might also make sense to do the UTF-16 conversion here (would
3137/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00003138bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00003139 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00003140 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3141
Douglas Gregorfb65e592011-07-27 05:40:30 +00003142 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003143 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3144 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00003145 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00003146 }
Mike Stump11289f42009-09-09 15:08:12 +00003147
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003148 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003149 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003150 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003151 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00003152 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003153 UTF16 *ToPtr = &ToBuf[0];
3154
3155 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
3156 &ToPtr, ToPtr + NumBytes,
3157 strictConversion);
3158 // Check for conversion failure.
3159 if (Result != conversionOK)
3160 Diag(Arg->getLocStart(),
3161 diag::warn_cfstring_truncated) << Arg->getSourceRange();
3162 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00003163 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003164}
3165
Charles Davisc7d5c942015-09-17 20:55:33 +00003166/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3167/// for validity. Emit an error and return true on failure; return false
3168/// on success.
3169bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00003170 Expr *Fn = TheCall->getCallee();
3171 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00003172 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003173 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003174 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3175 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00003176 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003177 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00003178 return true;
3179 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003180
3181 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00003182 return Diag(TheCall->getLocEnd(),
3183 diag::err_typecheck_call_too_few_args_at_least)
3184 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003185 }
3186
John McCall29ad95b2011-08-27 01:09:30 +00003187 // Type-check the first argument normally.
3188 if (checkBuiltinArgument(*this, TheCall, 0))
3189 return true;
3190
Chris Lattnere202e6a2007-12-20 00:05:45 +00003191 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00003192 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00003193 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00003194 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00003195 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00003196 else if (FunctionDecl *FD = getCurFunctionDecl())
3197 isVariadic = FD->isVariadic();
3198 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00003199 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00003200
Chris Lattnere202e6a2007-12-20 00:05:45 +00003201 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00003202 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3203 return true;
3204 }
Mike Stump11289f42009-09-09 15:08:12 +00003205
Chris Lattner43be2e62007-12-19 23:59:04 +00003206 // Verify that the second argument to the builtin is the last argument of the
3207 // current function or method.
3208 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00003209 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00003210
Nico Weber9eea7642013-05-24 23:31:57 +00003211 // These are valid if SecondArgIsLastNamedArgument is false after the next
3212 // block.
3213 QualType Type;
3214 SourceLocation ParamLoc;
Aaron Ballman1de59c52016-04-24 13:30:21 +00003215 bool IsCRegister = false;
Nico Weber9eea7642013-05-24 23:31:57 +00003216
Anders Carlsson6a8350b2008-02-11 04:20:54 +00003217 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3218 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00003219 // FIXME: This isn't correct for methods (results in bogus warning).
3220 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00003221 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00003222 if (CurBlock)
David Majnemera3debed2016-06-24 05:33:44 +00003223 LastArg = CurBlock->TheDecl->parameters().back();
Steve Naroff439a3e42009-04-15 19:33:47 +00003224 else if (FunctionDecl *FD = getCurFunctionDecl())
David Majnemera3debed2016-06-24 05:33:44 +00003225 LastArg = FD->parameters().back();
Chris Lattner43be2e62007-12-19 23:59:04 +00003226 else
David Majnemera3debed2016-06-24 05:33:44 +00003227 LastArg = getCurMethodDecl()->parameters().back();
Chris Lattner43be2e62007-12-19 23:59:04 +00003228 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00003229
3230 Type = PV->getType();
3231 ParamLoc = PV->getLocation();
Aaron Ballman1de59c52016-04-24 13:30:21 +00003232 IsCRegister =
3233 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
Chris Lattner43be2e62007-12-19 23:59:04 +00003234 }
3235 }
Mike Stump11289f42009-09-09 15:08:12 +00003236
Chris Lattner43be2e62007-12-19 23:59:04 +00003237 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00003238 Diag(TheCall->getArg(1)->getLocStart(),
Aaron Ballman05164812016-04-18 18:10:53 +00003239 diag::warn_second_arg_of_va_start_not_last_named_param);
Aaron Ballman1de59c52016-04-24 13:30:21 +00003240 else if (IsCRegister || Type->isReferenceType() ||
3241 Type->isPromotableIntegerType() ||
3242 Type->isSpecificBuiltinType(BuiltinType::Float)) {
3243 unsigned Reason = 0;
3244 if (Type->isReferenceType()) Reason = 1;
3245 else if (IsCRegister) Reason = 2;
3246 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
Nico Weber9eea7642013-05-24 23:31:57 +00003247 Diag(ParamLoc, diag::note_parameter_type) << Type;
3248 }
3249
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00003250 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00003251 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00003252}
Chris Lattner43be2e62007-12-19 23:59:04 +00003253
Charles Davisc7d5c942015-09-17 20:55:33 +00003254/// Check the arguments to '__builtin_va_start' for validity, and that
3255/// it was called from a function of the native ABI.
3256/// Emit an error and return true on failure; return false on success.
3257bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
3258 // On x86-64 Unix, don't allow this in Win64 ABI functions.
3259 // On x64 Windows, don't allow this in System V ABI functions.
3260 // (Yes, that means there's no corresponding way to support variadic
3261 // System V ABI functions on Windows.)
3262 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) {
3263 unsigned OS = Context.getTargetInfo().getTriple().getOS();
3264 clang::CallingConv CC = CC_C;
3265 if (const FunctionDecl *FD = getCurFunctionDecl())
3266 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3267 if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) ||
3268 (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64))
3269 return Diag(TheCall->getCallee()->getLocStart(),
3270 diag::err_va_start_used_in_wrong_abi_function)
3271 << (OS != llvm::Triple::Win32);
3272 }
3273 return SemaBuiltinVAStartImpl(TheCall);
3274}
3275
3276/// Check the arguments to '__builtin_ms_va_start' for validity, and that
3277/// it was called from a Win64 ABI function.
3278/// Emit an error and return true on failure; return false on success.
3279bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) {
3280 // This only makes sense for x86-64.
3281 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3282 Expr *Callee = TheCall->getCallee();
3283 if (TT.getArch() != llvm::Triple::x86_64)
3284 return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt);
3285 // Don't allow this in System V ABI functions.
3286 clang::CallingConv CC = CC_C;
3287 if (const FunctionDecl *FD = getCurFunctionDecl())
3288 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3289 if (CC == CC_X86_64SysV ||
3290 (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64))
3291 return Diag(Callee->getLocStart(),
3292 diag::err_ms_va_start_used_in_sysv_function);
3293 return SemaBuiltinVAStartImpl(TheCall);
3294}
3295
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003296bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
3297 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
3298 // const char *named_addr);
3299
3300 Expr *Func = Call->getCallee();
3301
3302 if (Call->getNumArgs() < 3)
3303 return Diag(Call->getLocEnd(),
3304 diag::err_typecheck_call_too_few_args_at_least)
3305 << 0 /*function call*/ << 3 << Call->getNumArgs();
3306
3307 // Determine whether the current function is variadic or not.
3308 bool IsVariadic;
3309 if (BlockScopeInfo *CurBlock = getCurBlock())
3310 IsVariadic = CurBlock->TheDecl->isVariadic();
3311 else if (FunctionDecl *FD = getCurFunctionDecl())
3312 IsVariadic = FD->isVariadic();
3313 else if (ObjCMethodDecl *MD = getCurMethodDecl())
3314 IsVariadic = MD->isVariadic();
3315 else
3316 llvm_unreachable("unexpected statement type");
3317
3318 if (!IsVariadic) {
3319 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3320 return true;
3321 }
3322
3323 // Type-check the first argument normally.
3324 if (checkBuiltinArgument(*this, Call, 0))
3325 return true;
3326
Benjamin Kramere0ca6e12015-03-01 18:09:50 +00003327 const struct {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003328 unsigned ArgNo;
3329 QualType Type;
3330 } ArgumentTypes[] = {
3331 { 1, Context.getPointerType(Context.CharTy.withConst()) },
3332 { 2, Context.getSizeType() },
3333 };
3334
3335 for (const auto &AT : ArgumentTypes) {
3336 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
3337 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
3338 continue;
3339 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
3340 << Arg->getType() << AT.Type << 1 /* different class */
3341 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
3342 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
3343 }
3344
3345 return false;
3346}
3347
Chris Lattner2da14fb2007-12-20 00:26:33 +00003348/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
3349/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00003350bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
3351 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00003352 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00003353 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00003354 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00003355 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003356 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003357 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00003358 << SourceRange(TheCall->getArg(2)->getLocStart(),
3359 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003360
John Wiegley01296292011-04-08 18:41:53 +00003361 ExprResult OrigArg0 = TheCall->getArg(0);
3362 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00003363
Chris Lattner2da14fb2007-12-20 00:26:33 +00003364 // Do standard promotions between the two arguments, returning their common
3365 // type.
Chris Lattner08464942007-12-28 05:29:59 +00003366 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00003367 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
3368 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00003369
3370 // Make sure any conversions are pushed back into the call; this is
3371 // type safe since unordered compare builtins are declared as "_Bool
3372 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00003373 TheCall->setArg(0, OrigArg0.get());
3374 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00003375
John Wiegley01296292011-04-08 18:41:53 +00003376 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00003377 return false;
3378
Chris Lattner2da14fb2007-12-20 00:26:33 +00003379 // If the common type isn't a real floating type, then the arguments were
3380 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00003381 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00003382 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003383 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00003384 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
3385 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003386
Chris Lattner2da14fb2007-12-20 00:26:33 +00003387 return false;
3388}
3389
Benjamin Kramer634fc102010-02-15 22:42:31 +00003390/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
3391/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00003392/// to check everything. We expect the last argument to be a floating point
3393/// value.
3394bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
3395 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00003396 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00003397 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00003398 if (TheCall->getNumArgs() > NumArgs)
3399 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003400 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003401 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00003402 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003403 (*(TheCall->arg_end()-1))->getLocEnd());
3404
Benjamin Kramer64aae502010-02-16 10:07:31 +00003405 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00003406
Eli Friedman7e4faac2009-08-31 20:06:00 +00003407 if (OrigArg->isTypeDependent())
3408 return false;
3409
Chris Lattner68784ef2010-05-06 05:50:07 +00003410 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00003411 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00003412 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003413 diag::err_typecheck_call_invalid_unary_fp)
3414 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003415
Chris Lattner68784ef2010-05-06 05:50:07 +00003416 // If this is an implicit conversion from float -> double, remove it.
3417 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
3418 Expr *CastArg = Cast->getSubExpr();
3419 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
3420 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
3421 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00003422 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00003423 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00003424 }
3425 }
3426
Eli Friedman7e4faac2009-08-31 20:06:00 +00003427 return false;
3428}
3429
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003430/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
3431// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00003432ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00003433 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003434 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00003435 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00003436 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3437 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003438
Nate Begemana0110022010-06-08 00:16:34 +00003439 // Determine which of the following types of shufflevector we're checking:
3440 // 1) unary, vector mask: (lhs, mask)
Craig Topperb3174a82016-05-18 04:11:25 +00003441 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
Nate Begemana0110022010-06-08 00:16:34 +00003442 QualType resType = TheCall->getArg(0)->getType();
3443 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00003444
Douglas Gregorc25f7662009-05-19 22:10:17 +00003445 if (!TheCall->getArg(0)->isTypeDependent() &&
3446 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00003447 QualType LHSType = TheCall->getArg(0)->getType();
3448 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00003449
Craig Topperbaca3892013-07-29 06:47:04 +00003450 if (!LHSType->isVectorType() || !RHSType->isVectorType())
3451 return ExprError(Diag(TheCall->getLocStart(),
3452 diag::err_shufflevector_non_vector)
3453 << SourceRange(TheCall->getArg(0)->getLocStart(),
3454 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00003455
Nate Begemana0110022010-06-08 00:16:34 +00003456 numElements = LHSType->getAs<VectorType>()->getNumElements();
3457 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00003458
Nate Begemana0110022010-06-08 00:16:34 +00003459 // Check to see if we have a call with 2 vector arguments, the unary shuffle
3460 // with mask. If so, verify that RHS is an integer vector type with the
3461 // same number of elts as lhs.
3462 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00003463 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00003464 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00003465 return ExprError(Diag(TheCall->getLocStart(),
3466 diag::err_shufflevector_incompatible_vector)
3467 << SourceRange(TheCall->getArg(1)->getLocStart(),
3468 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00003469 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00003470 return ExprError(Diag(TheCall->getLocStart(),
3471 diag::err_shufflevector_incompatible_vector)
3472 << SourceRange(TheCall->getArg(0)->getLocStart(),
3473 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00003474 } else if (numElements != numResElements) {
3475 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00003476 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00003477 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00003478 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003479 }
3480
3481 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00003482 if (TheCall->getArg(i)->isTypeDependent() ||
3483 TheCall->getArg(i)->isValueDependent())
3484 continue;
3485
Nate Begemana0110022010-06-08 00:16:34 +00003486 llvm::APSInt Result(32);
3487 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
3488 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00003489 diag::err_shufflevector_nonconstant_argument)
3490 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003491
Craig Topper50ad5b72013-08-03 17:40:38 +00003492 // Allow -1 which will be translated to undef in the IR.
3493 if (Result.isSigned() && Result.isAllOnesValue())
3494 continue;
3495
Chris Lattner7ab824e2008-08-10 02:05:13 +00003496 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003497 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00003498 diag::err_shufflevector_argument_too_large)
3499 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003500 }
3501
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003502 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003503
Chris Lattner7ab824e2008-08-10 02:05:13 +00003504 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003505 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00003506 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003507 }
3508
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003509 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
3510 TheCall->getCallee()->getLocStart(),
3511 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003512}
Chris Lattner43be2e62007-12-19 23:59:04 +00003513
Hal Finkelc4d7c822013-09-18 03:29:45 +00003514/// SemaConvertVectorExpr - Handle __builtin_convertvector
3515ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
3516 SourceLocation BuiltinLoc,
3517 SourceLocation RParenLoc) {
3518 ExprValueKind VK = VK_RValue;
3519 ExprObjectKind OK = OK_Ordinary;
3520 QualType DstTy = TInfo->getType();
3521 QualType SrcTy = E->getType();
3522
3523 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
3524 return ExprError(Diag(BuiltinLoc,
3525 diag::err_convertvector_non_vector)
3526 << E->getSourceRange());
3527 if (!DstTy->isVectorType() && !DstTy->isDependentType())
3528 return ExprError(Diag(BuiltinLoc,
3529 diag::err_convertvector_non_vector_type));
3530
3531 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
3532 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
3533 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
3534 if (SrcElts != DstElts)
3535 return ExprError(Diag(BuiltinLoc,
3536 diag::err_convertvector_incompatible_vector)
3537 << E->getSourceRange());
3538 }
3539
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003540 return new (Context)
3541 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00003542}
3543
Daniel Dunbarb7257262008-07-21 22:59:13 +00003544/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
3545// This is declared to take (const void*, ...) and can take two
3546// optional constant int args.
3547bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00003548 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003549
Chris Lattner3b054132008-11-19 05:08:23 +00003550 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003551 return Diag(TheCall->getLocEnd(),
3552 diag::err_typecheck_call_too_many_args_at_most)
3553 << 0 /*function call*/ << 3 << NumArgs
3554 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003555
3556 // Argument 0 is checked for us and the remaining arguments must be
3557 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00003558 for (unsigned i = 1; i != NumArgs; ++i)
3559 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00003560 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003561
Warren Hunt20e4a5d2014-02-21 23:08:53 +00003562 return false;
3563}
3564
Hal Finkelf0417332014-07-17 14:25:55 +00003565/// SemaBuiltinAssume - Handle __assume (MS Extension).
3566// __assume does not evaluate its arguments, and should warn if its argument
3567// has side effects.
3568bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
3569 Expr *Arg = TheCall->getArg(0);
3570 if (Arg->isInstantiationDependent()) return false;
3571
3572 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00003573 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00003574 << Arg->getSourceRange()
3575 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
3576
3577 return false;
3578}
3579
3580/// Handle __builtin_assume_aligned. This is declared
3581/// as (const void*, size_t, ...) and can take one optional constant int arg.
3582bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
3583 unsigned NumArgs = TheCall->getNumArgs();
3584
3585 if (NumArgs > 3)
3586 return Diag(TheCall->getLocEnd(),
3587 diag::err_typecheck_call_too_many_args_at_most)
3588 << 0 /*function call*/ << 3 << NumArgs
3589 << TheCall->getSourceRange();
3590
3591 // The alignment must be a constant integer.
3592 Expr *Arg = TheCall->getArg(1);
3593
3594 // We can't check the value of a dependent argument.
3595 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
3596 llvm::APSInt Result;
3597 if (SemaBuiltinConstantArg(TheCall, 1, Result))
3598 return true;
3599
3600 if (!Result.isPowerOf2())
3601 return Diag(TheCall->getLocStart(),
3602 diag::err_alignment_not_power_of_two)
3603 << Arg->getSourceRange();
3604 }
3605
3606 if (NumArgs > 2) {
3607 ExprResult Arg(TheCall->getArg(2));
3608 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3609 Context.getSizeType(), false);
3610 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3611 if (Arg.isInvalid()) return true;
3612 TheCall->setArg(2, Arg.get());
3613 }
Hal Finkelf0417332014-07-17 14:25:55 +00003614
3615 return false;
3616}
3617
Eric Christopher8d0c6212010-04-17 02:26:23 +00003618/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
3619/// TheCall is a constant expression.
3620bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
3621 llvm::APSInt &Result) {
3622 Expr *Arg = TheCall->getArg(ArgNum);
3623 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3624 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3625
3626 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
3627
3628 if (!Arg->isIntegerConstantExpr(Result, Context))
3629 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00003630 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00003631
Chris Lattnerd545ad12009-09-23 06:06:36 +00003632 return false;
3633}
3634
Richard Sandiford28940af2014-04-16 08:47:51 +00003635/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
3636/// TheCall is a constant expression in the range [Low, High].
3637bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
3638 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00003639 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00003640
3641 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00003642 Expr *Arg = TheCall->getArg(ArgNum);
3643 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00003644 return false;
3645
Eric Christopher8d0c6212010-04-17 02:26:23 +00003646 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00003647 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00003648 return true;
3649
Richard Sandiford28940af2014-04-16 08:47:51 +00003650 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00003651 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00003652 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00003653
3654 return false;
3655}
3656
Luke Cheeseman59b2d832015-06-15 17:51:01 +00003657/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
3658/// TheCall is an ARM/AArch64 special register string literal.
3659bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
3660 int ArgNum, unsigned ExpectedFieldNum,
3661 bool AllowName) {
3662 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
3663 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
3664 BuiltinID == ARM::BI__builtin_arm_rsr ||
3665 BuiltinID == ARM::BI__builtin_arm_rsrp ||
3666 BuiltinID == ARM::BI__builtin_arm_wsr ||
3667 BuiltinID == ARM::BI__builtin_arm_wsrp;
3668 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
3669 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
3670 BuiltinID == AArch64::BI__builtin_arm_rsr ||
3671 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
3672 BuiltinID == AArch64::BI__builtin_arm_wsr ||
3673 BuiltinID == AArch64::BI__builtin_arm_wsrp;
3674 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
3675
3676 // We can't check the value of a dependent argument.
3677 Expr *Arg = TheCall->getArg(ArgNum);
3678 if (Arg->isTypeDependent() || Arg->isValueDependent())
3679 return false;
3680
3681 // Check if the argument is a string literal.
3682 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3683 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
3684 << Arg->getSourceRange();
3685
3686 // Check the type of special register given.
3687 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3688 SmallVector<StringRef, 6> Fields;
3689 Reg.split(Fields, ":");
3690
3691 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
3692 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
3693 << Arg->getSourceRange();
3694
3695 // If the string is the name of a register then we cannot check that it is
3696 // valid here but if the string is of one the forms described in ACLE then we
3697 // can check that the supplied fields are integers and within the valid
3698 // ranges.
3699 if (Fields.size() > 1) {
3700 bool FiveFields = Fields.size() == 5;
3701
3702 bool ValidString = true;
3703 if (IsARMBuiltin) {
3704 ValidString &= Fields[0].startswith_lower("cp") ||
3705 Fields[0].startswith_lower("p");
3706 if (ValidString)
3707 Fields[0] =
3708 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
3709
3710 ValidString &= Fields[2].startswith_lower("c");
3711 if (ValidString)
3712 Fields[2] = Fields[2].drop_front(1);
3713
3714 if (FiveFields) {
3715 ValidString &= Fields[3].startswith_lower("c");
3716 if (ValidString)
3717 Fields[3] = Fields[3].drop_front(1);
3718 }
3719 }
3720
3721 SmallVector<int, 5> Ranges;
3722 if (FiveFields)
3723 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15});
3724 else
3725 Ranges.append({15, 7, 15});
3726
3727 for (unsigned i=0; i<Fields.size(); ++i) {
3728 int IntField;
3729 ValidString &= !Fields[i].getAsInteger(10, IntField);
3730 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
3731 }
3732
3733 if (!ValidString)
3734 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
3735 << Arg->getSourceRange();
3736
3737 } else if (IsAArch64Builtin && Fields.size() == 1) {
3738 // If the register name is one of those that appear in the condition below
3739 // and the special register builtin being used is one of the write builtins,
3740 // then we require that the argument provided for writing to the register
3741 // is an integer constant expression. This is because it will be lowered to
3742 // an MSR (immediate) instruction, so we need to know the immediate at
3743 // compile time.
3744 if (TheCall->getNumArgs() != 2)
3745 return false;
3746
3747 std::string RegLower = Reg.lower();
3748 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
3749 RegLower != "pan" && RegLower != "uao")
3750 return false;
3751
3752 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
3753 }
3754
3755 return false;
3756}
3757
Eli Friedmanc97d0142009-05-03 06:04:26 +00003758/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003759/// This checks that the target supports __builtin_longjmp and
3760/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003761bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003762 if (!Context.getTargetInfo().hasSjLjLowering())
3763 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
3764 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
3765
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003766 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00003767 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00003768
Eric Christopher8d0c6212010-04-17 02:26:23 +00003769 // TODO: This is less than ideal. Overload this to take a value.
3770 if (SemaBuiltinConstantArg(TheCall, 1, Result))
3771 return true;
3772
3773 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003774 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
3775 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
3776
3777 return false;
3778}
3779
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003780/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
3781/// This checks that the target supports __builtin_setjmp.
3782bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
3783 if (!Context.getTargetInfo().hasSjLjLowering())
3784 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
3785 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
3786 return false;
3787}
3788
Richard Smithd7293d72013-08-05 18:49:43 +00003789namespace {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003790class UncoveredArgHandler {
3791 enum { Unknown = -1, AllCovered = -2 };
3792 signed FirstUncoveredArg;
3793 SmallVector<const Expr *, 4> DiagnosticExprs;
3794
3795public:
3796 UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
3797
3798 bool hasUncoveredArg() const {
3799 return (FirstUncoveredArg >= 0);
3800 }
3801
3802 unsigned getUncoveredArg() const {
3803 assert(hasUncoveredArg() && "no uncovered argument");
3804 return FirstUncoveredArg;
3805 }
3806
3807 void setAllCovered() {
3808 // A string has been found with all arguments covered, so clear out
3809 // the diagnostics.
3810 DiagnosticExprs.clear();
3811 FirstUncoveredArg = AllCovered;
3812 }
3813
3814 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
3815 assert(NewFirstUncoveredArg >= 0 && "Outside range");
3816
3817 // Don't update if a previous string covers all arguments.
3818 if (FirstUncoveredArg == AllCovered)
3819 return;
3820
3821 // UncoveredArgHandler tracks the highest uncovered argument index
3822 // and with it all the strings that match this index.
3823 if (NewFirstUncoveredArg == FirstUncoveredArg)
3824 DiagnosticExprs.push_back(StrExpr);
3825 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
3826 DiagnosticExprs.clear();
3827 DiagnosticExprs.push_back(StrExpr);
3828 FirstUncoveredArg = NewFirstUncoveredArg;
3829 }
3830 }
3831
3832 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
3833};
3834
Richard Smithd7293d72013-08-05 18:49:43 +00003835enum StringLiteralCheckType {
3836 SLCT_NotALiteral,
3837 SLCT_UncheckedLiteral,
3838 SLCT_CheckedLiteral
3839};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003840} // end anonymous namespace
Richard Smithd7293d72013-08-05 18:49:43 +00003841
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00003842static void CheckFormatString(Sema &S, const StringLiteral *FExpr,
3843 const Expr *OrigFormatExpr,
3844 ArrayRef<const Expr *> Args,
3845 bool HasVAListArg, unsigned format_idx,
3846 unsigned firstDataArg,
3847 Sema::FormatStringType Type,
3848 bool inFunctionCall,
3849 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003850 llvm::SmallBitVector &CheckedVarArgs,
3851 UncoveredArgHandler &UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00003852
Richard Smith55ce3522012-06-25 20:30:08 +00003853// Determine if an expression is a string literal or constant string.
3854// If this function returns false on the arguments to a function expecting a
3855// format string, we will usually need to emit a warning.
3856// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00003857static StringLiteralCheckType
3858checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
3859 bool HasVAListArg, unsigned format_idx,
3860 unsigned firstDataArg, Sema::FormatStringType Type,
3861 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003862 llvm::SmallBitVector &CheckedVarArgs,
3863 UncoveredArgHandler &UncoveredArg) {
Ted Kremenek808829352010-09-09 03:51:39 +00003864 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00003865 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00003866 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003867
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003868 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00003869
Richard Smithd7293d72013-08-05 18:49:43 +00003870 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00003871 // Technically -Wformat-nonliteral does not warn about this case.
3872 // The behavior of printf and friends in this case is implementation
3873 // dependent. Ideally if the format string cannot be null then
3874 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00003875 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00003876
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003877 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00003878 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003879 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00003880 // The expression is a literal if both sub-expressions were, and it was
3881 // completely checked only if both sub-expressions were checked.
3882 const AbstractConditionalOperator *C =
3883 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003884
3885 // Determine whether it is necessary to check both sub-expressions, for
3886 // example, because the condition expression is a constant that can be
3887 // evaluated at compile time.
3888 bool CheckLeft = true, CheckRight = true;
3889
3890 bool Cond;
3891 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
3892 if (Cond)
3893 CheckRight = false;
3894 else
3895 CheckLeft = false;
3896 }
3897
3898 StringLiteralCheckType Left;
3899 if (!CheckLeft)
3900 Left = SLCT_UncheckedLiteral;
3901 else {
3902 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
3903 HasVAListArg, format_idx, firstDataArg,
3904 Type, CallType, InFunctionCall,
3905 CheckedVarArgs, UncoveredArg);
3906 if (Left == SLCT_NotALiteral || !CheckRight)
3907 return Left;
3908 }
3909
Richard Smith55ce3522012-06-25 20:30:08 +00003910 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00003911 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003912 HasVAListArg, format_idx, firstDataArg,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003913 Type, CallType, InFunctionCall, CheckedVarArgs,
3914 UncoveredArg);
3915
3916 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003917 }
3918
3919 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00003920 E = cast<ImplicitCastExpr>(E)->getSubExpr();
3921 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003922 }
3923
John McCallc07a0c72011-02-17 10:25:35 +00003924 case Stmt::OpaqueValueExprClass:
3925 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
3926 E = src;
3927 goto tryAgain;
3928 }
Richard Smith55ce3522012-06-25 20:30:08 +00003929 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00003930
Ted Kremeneka8890832011-02-24 23:03:04 +00003931 case Stmt::PredefinedExprClass:
3932 // While __func__, etc., are technically not string literals, they
3933 // cannot contain format specifiers and thus are not a security
3934 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00003935 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00003936
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003937 case Stmt::DeclRefExprClass: {
3938 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00003939
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003940 // As an exception, do not flag errors for variables binding to
3941 // const string literals.
3942 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
3943 bool isConstant = false;
3944 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003945
Richard Smithd7293d72013-08-05 18:49:43 +00003946 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
3947 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00003948 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00003949 isConstant = T.isConstant(S.Context) &&
3950 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00003951 } else if (T->isObjCObjectPointerType()) {
3952 // In ObjC, there is usually no "const ObjectPointer" type,
3953 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00003954 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003955 }
Mike Stump11289f42009-09-09 15:08:12 +00003956
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003957 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00003958 if (const Expr *Init = VD->getAnyInitializer()) {
3959 // Look through initializers like const char c[] = { "foo" }
3960 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3961 if (InitList->isStringLiteralInit())
3962 Init = InitList->getInit(0)->IgnoreParenImpCasts();
3963 }
Richard Smithd7293d72013-08-05 18:49:43 +00003964 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003965 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003966 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003967 /*InFunctionCall*/false, CheckedVarArgs,
3968 UncoveredArg);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00003969 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003970 }
Mike Stump11289f42009-09-09 15:08:12 +00003971
Anders Carlssonb012ca92009-06-28 19:55:58 +00003972 // For vprintf* functions (i.e., HasVAListArg==true), we add a
3973 // special check to see if the format string is a function parameter
3974 // of the function calling the printf function. If the function
3975 // has an attribute indicating it is a printf-like function, then we
3976 // should suppress warnings concerning non-literals being used in a call
3977 // to a vprintf function. For example:
3978 //
3979 // void
3980 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
3981 // va_list ap;
3982 // va_start(ap, fmt);
3983 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
3984 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00003985 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003986 if (HasVAListArg) {
3987 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
3988 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
3989 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003990 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003991 // adjust for implicit parameter
3992 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
3993 if (MD->isInstance())
3994 ++PVIndex;
3995 // We also check if the formats are compatible.
3996 // We can't pass a 'scanf' string to a 'printf' function.
3997 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00003998 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00003999 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004000 }
4001 }
4002 }
4003 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004004 }
Mike Stump11289f42009-09-09 15:08:12 +00004005
Richard Smith55ce3522012-06-25 20:30:08 +00004006 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004007 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004008
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00004009 case Stmt::CallExprClass:
4010 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004011 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00004012 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
4013 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
4014 unsigned ArgIndex = FA->getFormatIdx();
4015 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4016 if (MD->isInstance())
4017 --ArgIndex;
4018 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00004019
Richard Smithd7293d72013-08-05 18:49:43 +00004020 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004021 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00004022 Type, CallType, InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004023 CheckedVarArgs, UncoveredArg);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004024 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4025 unsigned BuiltinID = FD->getBuiltinID();
4026 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
4027 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
4028 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00004029 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004030 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004031 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004032 InFunctionCall, CheckedVarArgs,
4033 UncoveredArg);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004034 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004035 }
4036 }
Mike Stump11289f42009-09-09 15:08:12 +00004037
Richard Smith55ce3522012-06-25 20:30:08 +00004038 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004039 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004040 case Stmt::ObjCStringLiteralClass:
4041 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00004042 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004043
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004044 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004045 StrE = ObjCFExpr->getString();
4046 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004047 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004048
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004049 if (StrE) {
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004050 CheckFormatString(S, StrE, E, Args, HasVAListArg, format_idx,
4051 firstDataArg, Type, InFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004052 CheckedVarArgs, UncoveredArg);
Richard Smith55ce3522012-06-25 20:30:08 +00004053 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004054 }
Mike Stump11289f42009-09-09 15:08:12 +00004055
Richard Smith55ce3522012-06-25 20:30:08 +00004056 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004057 }
Mike Stump11289f42009-09-09 15:08:12 +00004058
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004059 default:
Richard Smith55ce3522012-06-25 20:30:08 +00004060 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004061 }
4062}
4063
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004064Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00004065 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004066 .Case("scanf", FST_Scanf)
4067 .Cases("printf", "printf0", FST_Printf)
4068 .Cases("NSString", "CFString", FST_NSString)
4069 .Case("strftime", FST_Strftime)
4070 .Case("strfmon", FST_Strfmon)
4071 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004072 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00004073 .Case("os_trace", FST_OSTrace)
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004074 .Default(FST_Unknown);
4075}
4076
Jordan Rose3e0ec582012-07-19 18:10:23 +00004077/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00004078/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00004079/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004080bool Sema::CheckFormatArguments(const FormatAttr *Format,
4081 ArrayRef<const Expr *> Args,
4082 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004083 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00004084 SourceLocation Loc, SourceRange Range,
4085 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00004086 FormatStringInfo FSI;
4087 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004088 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00004089 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00004090 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00004091 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004092}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00004093
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004094bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004095 bool HasVAListArg, unsigned format_idx,
4096 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004097 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00004098 SourceLocation Loc, SourceRange Range,
4099 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00004100 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004101 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004102 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00004103 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004104 }
Mike Stump11289f42009-09-09 15:08:12 +00004105
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004106 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00004107
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004108 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00004109 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004110 // Dynamically generated format strings are difficult to
4111 // automatically vet at compile time. Requiring that format strings
4112 // are string literals: (1) permits the checking of format strings by
4113 // the compiler and thereby (2) can practically remove the source of
4114 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00004115
Mike Stump11289f42009-09-09 15:08:12 +00004116 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00004117 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00004118 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00004119 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004120 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00004121 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00004122 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
4123 format_idx, firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004124 /*IsFunctionCall*/true, CheckedVarArgs,
4125 UncoveredArg);
4126
4127 // Generate a diagnostic where an uncovered argument is detected.
4128 if (UncoveredArg.hasUncoveredArg()) {
4129 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
4130 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
4131 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
4132 }
4133
Richard Smith55ce3522012-06-25 20:30:08 +00004134 if (CT != SLCT_NotALiteral)
4135 // Literal format string found, check done!
4136 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00004137
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00004138 // Strftime is particular as it always uses a single 'time' argument,
4139 // so it is safe to pass a non-literal string.
4140 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00004141 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00004142
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00004143 // Do not emit diag when the string param is a macro expansion and the
4144 // format is either NSString or CFString. This is a hack to prevent
4145 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
4146 // which are usually used in place of NS and CF string literals.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004147 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
4148 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
Richard Smith55ce3522012-06-25 20:30:08 +00004149 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00004150
Chris Lattnercc5d1c22009-04-29 04:59:47 +00004151 // If there are no arguments specified, warn with -Wformat-security, otherwise
4152 // warn only with -Wformat-nonliteral.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004153 if (Args.size() == firstDataArg) {
Bob Wilson57819fc2016-03-15 20:56:38 +00004154 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
4155 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004156 switch (Type) {
4157 default:
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004158 break;
4159 case FST_Kprintf:
4160 case FST_FreeBSDKPrintf:
4161 case FST_Printf:
Bob Wilson57819fc2016-03-15 20:56:38 +00004162 Diag(FormatLoc, diag::note_format_security_fixit)
4163 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004164 break;
4165 case FST_NSString:
Bob Wilson57819fc2016-03-15 20:56:38 +00004166 Diag(FormatLoc, diag::note_format_security_fixit)
4167 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004168 break;
4169 }
4170 } else {
4171 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00004172 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004173 }
Richard Smith55ce3522012-06-25 20:30:08 +00004174 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004175}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004176
Ted Kremenekab278de2010-01-28 23:39:18 +00004177namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00004178class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
4179protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00004180 Sema &S;
4181 const StringLiteral *FExpr;
4182 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00004183 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00004184 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00004185 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00004186 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004187 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00004188 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00004189 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00004190 bool usesPositionalArgs;
4191 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00004192 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00004193 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00004194 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004195 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004196
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004197public:
Ted Kremenek02087932010-07-16 02:11:22 +00004198 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00004199 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004200 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004201 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004202 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00004203 Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004204 llvm::SmallBitVector &CheckedVarArgs,
4205 UncoveredArgHandler &UncoveredArg)
Ted Kremenekab278de2010-01-28 23:39:18 +00004206 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004207 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
4208 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004209 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00004210 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00004211 inFunctionCall(inFunctionCall), CallType(callType),
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004212 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00004213 CoveredArgs.resize(numDataArgs);
4214 CoveredArgs.reset();
4215 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004216
Ted Kremenek019d2242010-01-29 01:50:07 +00004217 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004218
Ted Kremenek02087932010-07-16 02:11:22 +00004219 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004220 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004221
Jordan Rose92303592012-09-08 04:00:03 +00004222 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00004223 const analyze_format_string::FormatSpecifier &FS,
4224 const analyze_format_string::ConversionSpecifier &CS,
4225 const char *startSpecifier, unsigned specifierLen,
4226 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00004227
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004228 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00004229 const analyze_format_string::FormatSpecifier &FS,
4230 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004231
4232 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00004233 const analyze_format_string::ConversionSpecifier &CS,
4234 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004235
Craig Toppere14c0f82014-03-12 04:55:44 +00004236 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00004237
Craig Toppere14c0f82014-03-12 04:55:44 +00004238 void HandleInvalidPosition(const char *startSpecifier,
4239 unsigned specifierLen,
4240 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00004241
Craig Toppere14c0f82014-03-12 04:55:44 +00004242 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00004243
Craig Toppere14c0f82014-03-12 04:55:44 +00004244 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004245
Richard Trieu03cf7b72011-10-28 00:41:25 +00004246 template <typename Range>
Benjamin Kramer7320b992016-06-15 14:20:56 +00004247 static void
4248 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
4249 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
4250 bool IsStringLocation, Range StringRange,
4251 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00004252
Ted Kremenek02087932010-07-16 02:11:22 +00004253protected:
Ted Kremenekce815422010-07-19 21:25:57 +00004254 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
4255 const char *startSpec,
4256 unsigned specifierLen,
4257 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00004258
4259 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
4260 const char *startSpec,
4261 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00004262
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004263 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00004264 CharSourceRange getSpecifierRange(const char *startSpecifier,
4265 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00004266 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004267
Ted Kremenek5739de72010-01-29 01:06:55 +00004268 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004269
4270 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
4271 const analyze_format_string::ConversionSpecifier &CS,
4272 const char *startSpecifier, unsigned specifierLen,
4273 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00004274
4275 template <typename Range>
4276 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
4277 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00004278 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00004279};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004280} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00004281
Ted Kremenek02087932010-07-16 02:11:22 +00004282SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00004283 return OrigFormatExpr->getSourceRange();
4284}
4285
Ted Kremenek02087932010-07-16 02:11:22 +00004286CharSourceRange CheckFormatHandler::
4287getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00004288 SourceLocation Start = getLocationOfByte(startSpecifier);
4289 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
4290
4291 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00004292 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00004293
4294 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004295}
4296
Ted Kremenek02087932010-07-16 02:11:22 +00004297SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004298 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00004299}
4300
Ted Kremenek02087932010-07-16 02:11:22 +00004301void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
4302 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00004303 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
4304 getLocationOfByte(startSpecifier),
4305 /*IsStringLocation*/true,
4306 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00004307}
4308
Jordan Rose92303592012-09-08 04:00:03 +00004309void CheckFormatHandler::HandleInvalidLengthModifier(
4310 const analyze_format_string::FormatSpecifier &FS,
4311 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00004312 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00004313 using namespace analyze_format_string;
4314
4315 const LengthModifier &LM = FS.getLengthModifier();
4316 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4317
4318 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00004319 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00004320 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004321 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00004322 getLocationOfByte(LM.getStart()),
4323 /*IsStringLocation*/true,
4324 getSpecifierRange(startSpecifier, specifierLen));
4325
4326 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4327 << FixedLM->toString()
4328 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
4329
4330 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004331 FixItHint Hint;
4332 if (DiagID == diag::warn_format_nonsensical_length)
4333 Hint = FixItHint::CreateRemoval(LMRange);
4334
4335 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00004336 getLocationOfByte(LM.getStart()),
4337 /*IsStringLocation*/true,
4338 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00004339 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00004340 }
4341}
4342
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004343void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00004344 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004345 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004346 using namespace analyze_format_string;
4347
4348 const LengthModifier &LM = FS.getLengthModifier();
4349 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4350
4351 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00004352 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00004353 if (FixedLM) {
4354 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4355 << LM.toString() << 0,
4356 getLocationOfByte(LM.getStart()),
4357 /*IsStringLocation*/true,
4358 getSpecifierRange(startSpecifier, specifierLen));
4359
4360 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4361 << FixedLM->toString()
4362 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
4363
4364 } else {
4365 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4366 << LM.toString() << 0,
4367 getLocationOfByte(LM.getStart()),
4368 /*IsStringLocation*/true,
4369 getSpecifierRange(startSpecifier, specifierLen));
4370 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004371}
4372
4373void CheckFormatHandler::HandleNonStandardConversionSpecifier(
4374 const analyze_format_string::ConversionSpecifier &CS,
4375 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00004376 using namespace analyze_format_string;
4377
4378 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00004379 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00004380 if (FixedCS) {
4381 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4382 << CS.toString() << /*conversion specifier*/1,
4383 getLocationOfByte(CS.getStart()),
4384 /*IsStringLocation*/true,
4385 getSpecifierRange(startSpecifier, specifierLen));
4386
4387 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
4388 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
4389 << FixedCS->toString()
4390 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
4391 } else {
4392 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4393 << CS.toString() << /*conversion specifier*/1,
4394 getLocationOfByte(CS.getStart()),
4395 /*IsStringLocation*/true,
4396 getSpecifierRange(startSpecifier, specifierLen));
4397 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004398}
4399
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00004400void CheckFormatHandler::HandlePosition(const char *startPos,
4401 unsigned posLen) {
4402 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
4403 getLocationOfByte(startPos),
4404 /*IsStringLocation*/true,
4405 getSpecifierRange(startPos, posLen));
4406}
4407
Ted Kremenekd1668192010-02-27 01:41:03 +00004408void
Ted Kremenek02087932010-07-16 02:11:22 +00004409CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
4410 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004411 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
4412 << (unsigned) p,
4413 getLocationOfByte(startPos), /*IsStringLocation*/true,
4414 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00004415}
4416
Ted Kremenek02087932010-07-16 02:11:22 +00004417void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00004418 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004419 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
4420 getLocationOfByte(startPos),
4421 /*IsStringLocation*/true,
4422 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00004423}
4424
Ted Kremenek02087932010-07-16 02:11:22 +00004425void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004426 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00004427 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00004428 EmitFormatDiagnostic(
4429 S.PDiag(diag::warn_printf_format_string_contains_null_char),
4430 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
4431 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00004432 }
Ted Kremenek02087932010-07-16 02:11:22 +00004433}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004434
Jordan Rose58bbe422012-07-19 18:10:08 +00004435// Note that this may return NULL if there was an error parsing or building
4436// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00004437const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004438 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00004439}
4440
4441void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004442 // Does the number of data arguments exceed the number of
4443 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00004444 if (!HasVAListArg) {
4445 // Find any arguments that weren't covered.
4446 CoveredArgs.flip();
4447 signed notCoveredArg = CoveredArgs.find_first();
4448 if (notCoveredArg >= 0) {
4449 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004450 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
4451 } else {
4452 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00004453 }
4454 }
4455}
4456
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004457void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
4458 const Expr *ArgExpr) {
4459 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
4460 "Invalid state");
4461
4462 if (!ArgExpr)
4463 return;
4464
4465 SourceLocation Loc = ArgExpr->getLocStart();
4466
4467 if (S.getSourceManager().isInSystemMacro(Loc))
4468 return;
4469
4470 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
4471 for (auto E : DiagnosticExprs)
4472 PDiag << E->getSourceRange();
4473
4474 CheckFormatHandler::EmitFormatDiagnostic(
4475 S, IsFunctionCall, DiagnosticExprs[0],
4476 PDiag, Loc, /*IsStringLocation*/false,
4477 DiagnosticExprs[0]->getSourceRange());
4478}
4479
Ted Kremenekce815422010-07-19 21:25:57 +00004480bool
4481CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
4482 SourceLocation Loc,
4483 const char *startSpec,
4484 unsigned specifierLen,
4485 const char *csStart,
4486 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00004487 bool keepGoing = true;
4488 if (argIndex < NumDataArgs) {
4489 // Consider the argument coverered, even though the specifier doesn't
4490 // make sense.
4491 CoveredArgs.set(argIndex);
4492 }
4493 else {
4494 // If argIndex exceeds the number of data arguments we
4495 // don't issue a warning because that is just a cascade of warnings (and
4496 // they may have intended '%%' anyway). We don't want to continue processing
4497 // the format string after this point, however, as we will like just get
4498 // gibberish when trying to match arguments.
4499 keepGoing = false;
4500 }
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00004501
4502 StringRef Specifier(csStart, csLen);
4503
4504 // If the specifier in non-printable, it could be the first byte of a UTF-8
4505 // sequence. In that case, print the UTF-8 code point. If not, print the byte
4506 // hex value.
4507 std::string CodePointStr;
4508 if (!llvm::sys::locale::isPrint(*csStart)) {
4509 UTF32 CodePoint;
4510 const UTF8 **B = reinterpret_cast<const UTF8 **>(&csStart);
4511 const UTF8 *E =
4512 reinterpret_cast<const UTF8 *>(csStart + csLen);
4513 ConversionResult Result =
4514 llvm::convertUTF8Sequence(B, E, &CodePoint, strictConversion);
4515
4516 if (Result != conversionOK) {
4517 unsigned char FirstChar = *csStart;
4518 CodePoint = (UTF32)FirstChar;
4519 }
4520
4521 llvm::raw_string_ostream OS(CodePointStr);
4522 if (CodePoint < 256)
4523 OS << "\\x" << llvm::format("%02x", CodePoint);
4524 else if (CodePoint <= 0xFFFF)
4525 OS << "\\u" << llvm::format("%04x", CodePoint);
4526 else
4527 OS << "\\U" << llvm::format("%08x", CodePoint);
4528 OS.flush();
4529 Specifier = CodePointStr;
4530 }
4531
4532 EmitFormatDiagnostic(
4533 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
4534 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
4535
Ted Kremenekce815422010-07-19 21:25:57 +00004536 return keepGoing;
4537}
4538
Richard Trieu03cf7b72011-10-28 00:41:25 +00004539void
4540CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
4541 const char *startSpec,
4542 unsigned specifierLen) {
4543 EmitFormatDiagnostic(
4544 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
4545 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
4546}
4547
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004548bool
4549CheckFormatHandler::CheckNumArgs(
4550 const analyze_format_string::FormatSpecifier &FS,
4551 const analyze_format_string::ConversionSpecifier &CS,
4552 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
4553
4554 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004555 PartialDiagnostic PDiag = FS.usesPositionalArg()
4556 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
4557 << (argIndex+1) << NumDataArgs)
4558 : S.PDiag(diag::warn_printf_insufficient_data_args);
4559 EmitFormatDiagnostic(
4560 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
4561 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004562
4563 // Since more arguments than conversion tokens are given, by extension
4564 // all arguments are covered, so mark this as so.
4565 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004566 return false;
4567 }
4568 return true;
4569}
4570
Richard Trieu03cf7b72011-10-28 00:41:25 +00004571template<typename Range>
4572void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
4573 SourceLocation Loc,
4574 bool IsStringLocation,
4575 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00004576 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004577 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00004578 Loc, IsStringLocation, StringRange, FixIt);
4579}
4580
4581/// \brief If the format string is not within the funcion call, emit a note
4582/// so that the function call and string are in diagnostic messages.
4583///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00004584/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00004585/// call and only one diagnostic message will be produced. Otherwise, an
4586/// extra note will be emitted pointing to location of the format string.
4587///
4588/// \param ArgumentExpr the expression that is passed as the format string
4589/// argument in the function call. Used for getting locations when two
4590/// diagnostics are emitted.
4591///
4592/// \param PDiag the callee should already have provided any strings for the
4593/// diagnostic message. This function only adds locations and fixits
4594/// to diagnostics.
4595///
4596/// \param Loc primary location for diagnostic. If two diagnostics are
4597/// required, one will be at Loc and a new SourceLocation will be created for
4598/// the other one.
4599///
4600/// \param IsStringLocation if true, Loc points to the format string should be
4601/// used for the note. Otherwise, Loc points to the argument list and will
4602/// be used with PDiag.
4603///
4604/// \param StringRange some or all of the string to highlight. This is
4605/// templated so it can accept either a CharSourceRange or a SourceRange.
4606///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00004607/// \param FixIt optional fix it hint for the format string.
Benjamin Kramer7320b992016-06-15 14:20:56 +00004608template <typename Range>
4609void CheckFormatHandler::EmitFormatDiagnostic(
4610 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
4611 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
4612 Range StringRange, ArrayRef<FixItHint> FixIt) {
Jordan Roseaee34382012-09-05 22:56:26 +00004613 if (InFunctionCall) {
4614 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
4615 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00004616 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00004617 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004618 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
4619 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00004620
4621 const Sema::SemaDiagnosticBuilder &Note =
4622 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
4623 diag::note_format_string_defined);
4624
4625 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00004626 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00004627 }
4628}
4629
Ted Kremenek02087932010-07-16 02:11:22 +00004630//===--- CHECK: Printf format string checking ------------------------------===//
4631
4632namespace {
4633class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004634 bool ObjCContext;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004635
Ted Kremenek02087932010-07-16 02:11:22 +00004636public:
4637 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
4638 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004639 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00004640 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004641 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004642 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00004643 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004644 llvm::SmallBitVector &CheckedVarArgs,
4645 UncoveredArgHandler &UncoveredArg)
Richard Smithd7293d72013-08-05 18:49:43 +00004646 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
4647 numDataArgs, beg, hasVAListArg, Args,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004648 formatIdx, inFunctionCall, CallType, CheckedVarArgs,
4649 UncoveredArg),
Richard Smithd7293d72013-08-05 18:49:43 +00004650 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00004651 {}
4652
Ted Kremenek02087932010-07-16 02:11:22 +00004653 bool HandleInvalidPrintfConversionSpecifier(
4654 const analyze_printf::PrintfSpecifier &FS,
4655 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004656 unsigned specifierLen) override;
4657
Ted Kremenek02087932010-07-16 02:11:22 +00004658 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
4659 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004660 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00004661 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
4662 const char *StartSpecifier,
4663 unsigned SpecifierLen,
4664 const Expr *E);
4665
Ted Kremenek02087932010-07-16 02:11:22 +00004666 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
4667 const char *startSpecifier, unsigned specifierLen);
4668 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
4669 const analyze_printf::OptionalAmount &Amt,
4670 unsigned type,
4671 const char *startSpecifier, unsigned specifierLen);
4672 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
4673 const analyze_printf::OptionalFlag &flag,
4674 const char *startSpecifier, unsigned specifierLen);
4675 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
4676 const analyze_printf::OptionalFlag &ignoredFlag,
4677 const analyze_printf::OptionalFlag &flag,
4678 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004679 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00004680 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00004681
4682 void HandleEmptyObjCModifierFlag(const char *startFlag,
4683 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00004684
Ted Kremenek2b417712015-07-02 05:39:16 +00004685 void HandleInvalidObjCModifierFlag(const char *startFlag,
4686 unsigned flagLen) override;
4687
4688 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
4689 const char *flagsEnd,
4690 const char *conversionPosition)
4691 override;
4692};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004693} // end anonymous namespace
Ted Kremenek02087932010-07-16 02:11:22 +00004694
4695bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
4696 const analyze_printf::PrintfSpecifier &FS,
4697 const char *startSpecifier,
4698 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004699 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00004700 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00004701
Ted Kremenekce815422010-07-19 21:25:57 +00004702 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
4703 getLocationOfByte(CS.getStart()),
4704 startSpecifier, specifierLen,
4705 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00004706}
4707
Ted Kremenek02087932010-07-16 02:11:22 +00004708bool CheckPrintfHandler::HandleAmount(
4709 const analyze_format_string::OptionalAmount &Amt,
4710 unsigned k, const char *startSpecifier,
4711 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004712 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004713 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00004714 unsigned argIndex = Amt.getArgIndex();
4715 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004716 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
4717 << k,
4718 getLocationOfByte(Amt.getStart()),
4719 /*IsStringLocation*/true,
4720 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00004721 // Don't do any more checking. We will just emit
4722 // spurious errors.
4723 return false;
4724 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004725
Ted Kremenek5739de72010-01-29 01:06:55 +00004726 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00004727 // Although not in conformance with C99, we also allow the argument to be
4728 // an 'unsigned int' as that is a reasonably safe case. GCC also
4729 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00004730 CoveredArgs.set(argIndex);
4731 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00004732 if (!Arg)
4733 return false;
4734
Ted Kremenek5739de72010-01-29 01:06:55 +00004735 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004736
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004737 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
4738 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004739
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004740 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004741 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004742 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00004743 << T << Arg->getSourceRange(),
4744 getLocationOfByte(Amt.getStart()),
4745 /*IsStringLocation*/true,
4746 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00004747 // Don't do any more checking. We will just emit
4748 // spurious errors.
4749 return false;
4750 }
4751 }
4752 }
4753 return true;
4754}
Ted Kremenek5739de72010-01-29 01:06:55 +00004755
Tom Careb49ec692010-06-17 19:00:27 +00004756void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00004757 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004758 const analyze_printf::OptionalAmount &Amt,
4759 unsigned type,
4760 const char *startSpecifier,
4761 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004762 const analyze_printf::PrintfConversionSpecifier &CS =
4763 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00004764
Richard Trieu03cf7b72011-10-28 00:41:25 +00004765 FixItHint fixit =
4766 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
4767 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
4768 Amt.getConstantLength()))
4769 : FixItHint();
4770
4771 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
4772 << type << CS.toString(),
4773 getLocationOfByte(Amt.getStart()),
4774 /*IsStringLocation*/true,
4775 getSpecifierRange(startSpecifier, specifierLen),
4776 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00004777}
4778
Ted Kremenek02087932010-07-16 02:11:22 +00004779void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004780 const analyze_printf::OptionalFlag &flag,
4781 const char *startSpecifier,
4782 unsigned specifierLen) {
4783 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004784 const analyze_printf::PrintfConversionSpecifier &CS =
4785 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00004786 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
4787 << flag.toString() << CS.toString(),
4788 getLocationOfByte(flag.getPosition()),
4789 /*IsStringLocation*/true,
4790 getSpecifierRange(startSpecifier, specifierLen),
4791 FixItHint::CreateRemoval(
4792 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00004793}
4794
4795void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00004796 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004797 const analyze_printf::OptionalFlag &ignoredFlag,
4798 const analyze_printf::OptionalFlag &flag,
4799 const char *startSpecifier,
4800 unsigned specifierLen) {
4801 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00004802 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
4803 << ignoredFlag.toString() << flag.toString(),
4804 getLocationOfByte(ignoredFlag.getPosition()),
4805 /*IsStringLocation*/true,
4806 getSpecifierRange(startSpecifier, specifierLen),
4807 FixItHint::CreateRemoval(
4808 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00004809}
4810
Ted Kremenek2b417712015-07-02 05:39:16 +00004811// void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
4812// bool IsStringLocation, Range StringRange,
4813// ArrayRef<FixItHint> Fixit = None);
4814
4815void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
4816 unsigned flagLen) {
4817 // Warn about an empty flag.
4818 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
4819 getLocationOfByte(startFlag),
4820 /*IsStringLocation*/true,
4821 getSpecifierRange(startFlag, flagLen));
4822}
4823
4824void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
4825 unsigned flagLen) {
4826 // Warn about an invalid flag.
4827 auto Range = getSpecifierRange(startFlag, flagLen);
4828 StringRef flag(startFlag, flagLen);
4829 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
4830 getLocationOfByte(startFlag),
4831 /*IsStringLocation*/true,
4832 Range, FixItHint::CreateRemoval(Range));
4833}
4834
4835void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
4836 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
4837 // Warn about using '[...]' without a '@' conversion.
4838 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
4839 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
4840 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
4841 getLocationOfByte(conversionPosition),
4842 /*IsStringLocation*/true,
4843 Range, FixItHint::CreateRemoval(Range));
4844}
4845
Richard Smith55ce3522012-06-25 20:30:08 +00004846// Determines if the specified is a C++ class or struct containing
4847// a member with the specified name and kind (e.g. a CXXMethodDecl named
4848// "c_str()").
4849template<typename MemberKind>
4850static llvm::SmallPtrSet<MemberKind*, 1>
4851CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
4852 const RecordType *RT = Ty->getAs<RecordType>();
4853 llvm::SmallPtrSet<MemberKind*, 1> Results;
4854
4855 if (!RT)
4856 return Results;
4857 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00004858 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00004859 return Results;
4860
Alp Tokerb6cc5922014-05-03 03:45:55 +00004861 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00004862 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00004863 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00004864
4865 // We just need to include all members of the right kind turned up by the
4866 // filter, at this point.
4867 if (S.LookupQualifiedName(R, RT->getDecl()))
4868 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
4869 NamedDecl *decl = (*I)->getUnderlyingDecl();
4870 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
4871 Results.insert(FK);
4872 }
4873 return Results;
4874}
4875
Richard Smith2868a732014-02-28 01:36:39 +00004876/// Check if we could call '.c_str()' on an object.
4877///
4878/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
4879/// allow the call, or if it would be ambiguous).
4880bool Sema::hasCStrMethod(const Expr *E) {
4881 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
4882 MethodSet Results =
4883 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
4884 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
4885 MI != ME; ++MI)
4886 if ((*MI)->getMinRequiredArguments() == 0)
4887 return true;
4888 return false;
4889}
4890
Richard Smith55ce3522012-06-25 20:30:08 +00004891// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004892// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00004893// Returns true when a c_str() conversion method is found.
4894bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00004895 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00004896 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
4897
4898 MethodSet Results =
4899 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
4900
4901 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
4902 MI != ME; ++MI) {
4903 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00004904 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00004905 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00004906 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00004907 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00004908 S.Diag(E->getLocStart(), diag::note_printf_c_str)
4909 << "c_str()"
4910 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
4911 return true;
4912 }
4913 }
4914
4915 return false;
4916}
4917
Ted Kremenekab278de2010-01-28 23:39:18 +00004918bool
Ted Kremenek02087932010-07-16 02:11:22 +00004919CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00004920 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00004921 const char *startSpecifier,
4922 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004923 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00004924 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004925 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00004926
Ted Kremenek6cd69422010-07-19 22:01:06 +00004927 if (FS.consumesDataArgument()) {
4928 if (atFirstArg) {
4929 atFirstArg = false;
4930 usesPositionalArgs = FS.usesPositionalArg();
4931 }
4932 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004933 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
4934 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00004935 return false;
4936 }
Ted Kremenek5739de72010-01-29 01:06:55 +00004937 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004938
Ted Kremenekd1668192010-02-27 01:41:03 +00004939 // First check if the field width, precision, and conversion specifier
4940 // have matching data arguments.
4941 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
4942 startSpecifier, specifierLen)) {
4943 return false;
4944 }
4945
4946 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
4947 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004948 return false;
4949 }
4950
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004951 if (!CS.consumesDataArgument()) {
4952 // FIXME: Technically specifying a precision or field width here
4953 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00004954 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004955 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004956
Ted Kremenek4a49d982010-02-26 19:18:41 +00004957 // Consume the argument.
4958 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00004959 if (argIndex < NumDataArgs) {
4960 // The check to see if the argIndex is valid will come later.
4961 // We set the bit here because we may exit early from this
4962 // function if we encounter some other error.
4963 CoveredArgs.set(argIndex);
4964 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00004965
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004966 // FreeBSD kernel extensions.
4967 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
4968 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
4969 // We need at least two arguments.
4970 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
4971 return false;
4972
4973 // Claim the second argument.
4974 CoveredArgs.set(argIndex + 1);
4975
4976 // Type check the first argument (int for %b, pointer for %D)
4977 const Expr *Ex = getDataArg(argIndex);
4978 const analyze_printf::ArgType &AT =
4979 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
4980 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
4981 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
4982 EmitFormatDiagnostic(
4983 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4984 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
4985 << false << Ex->getSourceRange(),
4986 Ex->getLocStart(), /*IsStringLocation*/false,
4987 getSpecifierRange(startSpecifier, specifierLen));
4988
4989 // Type check the second argument (char * for both %b and %D)
4990 Ex = getDataArg(argIndex + 1);
4991 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
4992 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
4993 EmitFormatDiagnostic(
4994 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4995 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
4996 << false << Ex->getSourceRange(),
4997 Ex->getLocStart(), /*IsStringLocation*/false,
4998 getSpecifierRange(startSpecifier, specifierLen));
4999
5000 return true;
5001 }
5002
Ted Kremenek4a49d982010-02-26 19:18:41 +00005003 // Check for using an Objective-C specific conversion specifier
5004 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005005 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00005006 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5007 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00005008 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005009
Tom Careb49ec692010-06-17 19:00:27 +00005010 // Check for invalid use of field width
5011 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00005012 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00005013 startSpecifier, specifierLen);
5014 }
5015
5016 // Check for invalid use of precision
5017 if (!FS.hasValidPrecision()) {
5018 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
5019 startSpecifier, specifierLen);
5020 }
5021
5022 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00005023 if (!FS.hasValidThousandsGroupingPrefix())
5024 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005025 if (!FS.hasValidLeadingZeros())
5026 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
5027 if (!FS.hasValidPlusPrefix())
5028 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00005029 if (!FS.hasValidSpacePrefix())
5030 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005031 if (!FS.hasValidAlternativeForm())
5032 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
5033 if (!FS.hasValidLeftJustified())
5034 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
5035
5036 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00005037 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
5038 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
5039 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005040 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
5041 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
5042 startSpecifier, specifierLen);
5043
5044 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00005045 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00005046 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5047 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00005048 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005049 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00005050 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005051 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5052 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00005053
Jordan Rose92303592012-09-08 04:00:03 +00005054 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
5055 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5056
Ted Kremenek9fcd8302010-01-29 01:43:31 +00005057 // The remaining checks depend on the data arguments.
5058 if (HasVAListArg)
5059 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005060
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005061 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00005062 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005063
Jordan Rose58bbe422012-07-19 18:10:08 +00005064 const Expr *Arg = getDataArg(argIndex);
5065 if (!Arg)
5066 return true;
5067
5068 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00005069}
5070
Jordan Roseaee34382012-09-05 22:56:26 +00005071static bool requiresParensToAddCast(const Expr *E) {
5072 // FIXME: We should have a general way to reason about operator
5073 // precedence and whether parens are actually needed here.
5074 // Take care of a few common cases where they aren't.
5075 const Expr *Inside = E->IgnoreImpCasts();
5076 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
5077 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
5078
5079 switch (Inside->getStmtClass()) {
5080 case Stmt::ArraySubscriptExprClass:
5081 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005082 case Stmt::CharacterLiteralClass:
5083 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005084 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005085 case Stmt::FloatingLiteralClass:
5086 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005087 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005088 case Stmt::ObjCArrayLiteralClass:
5089 case Stmt::ObjCBoolLiteralExprClass:
5090 case Stmt::ObjCBoxedExprClass:
5091 case Stmt::ObjCDictionaryLiteralClass:
5092 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005093 case Stmt::ObjCIvarRefExprClass:
5094 case Stmt::ObjCMessageExprClass:
5095 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005096 case Stmt::ObjCStringLiteralClass:
5097 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005098 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005099 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005100 case Stmt::UnaryOperatorClass:
5101 return false;
5102 default:
5103 return true;
5104 }
5105}
5106
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005107static std::pair<QualType, StringRef>
5108shouldNotPrintDirectly(const ASTContext &Context,
5109 QualType IntendedTy,
5110 const Expr *E) {
5111 // Use a 'while' to peel off layers of typedefs.
5112 QualType TyTy = IntendedTy;
5113 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
5114 StringRef Name = UserTy->getDecl()->getName();
5115 QualType CastTy = llvm::StringSwitch<QualType>(Name)
5116 .Case("NSInteger", Context.LongTy)
5117 .Case("NSUInteger", Context.UnsignedLongTy)
5118 .Case("SInt32", Context.IntTy)
5119 .Case("UInt32", Context.UnsignedIntTy)
5120 .Default(QualType());
5121
5122 if (!CastTy.isNull())
5123 return std::make_pair(CastTy, Name);
5124
5125 TyTy = UserTy->desugar();
5126 }
5127
5128 // Strip parens if necessary.
5129 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
5130 return shouldNotPrintDirectly(Context,
5131 PE->getSubExpr()->getType(),
5132 PE->getSubExpr());
5133
5134 // If this is a conditional expression, then its result type is constructed
5135 // via usual arithmetic conversions and thus there might be no necessary
5136 // typedef sugar there. Recurse to operands to check for NSInteger &
5137 // Co. usage condition.
5138 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5139 QualType TrueTy, FalseTy;
5140 StringRef TrueName, FalseName;
5141
5142 std::tie(TrueTy, TrueName) =
5143 shouldNotPrintDirectly(Context,
5144 CO->getTrueExpr()->getType(),
5145 CO->getTrueExpr());
5146 std::tie(FalseTy, FalseName) =
5147 shouldNotPrintDirectly(Context,
5148 CO->getFalseExpr()->getType(),
5149 CO->getFalseExpr());
5150
5151 if (TrueTy == FalseTy)
5152 return std::make_pair(TrueTy, TrueName);
5153 else if (TrueTy.isNull())
5154 return std::make_pair(FalseTy, FalseName);
5155 else if (FalseTy.isNull())
5156 return std::make_pair(TrueTy, TrueName);
5157 }
5158
5159 return std::make_pair(QualType(), StringRef());
5160}
5161
Richard Smith55ce3522012-06-25 20:30:08 +00005162bool
5163CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5164 const char *StartSpecifier,
5165 unsigned SpecifierLen,
5166 const Expr *E) {
5167 using namespace analyze_format_string;
5168 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005169 // Now type check the data expression that matches the
5170 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005171 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
5172 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00005173 if (!AT.isValid())
5174 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00005175
Jordan Rose598ec092012-12-05 18:44:40 +00005176 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00005177 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
5178 ExprTy = TET->getUnderlyingExpr()->getType();
5179 }
5180
Seth Cantrellb4802962015-03-04 03:12:10 +00005181 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
5182
5183 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00005184 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00005185 }
Jordan Rose98709982012-06-04 22:48:57 +00005186
Jordan Rose22b74712012-09-05 22:56:19 +00005187 // Look through argument promotions for our error message's reported type.
5188 // This includes the integral and floating promotions, but excludes array
5189 // and function pointer decay; seeing that an argument intended to be a
5190 // string has type 'char [6]' is probably more confusing than 'char *'.
5191 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5192 if (ICE->getCastKind() == CK_IntegralCast ||
5193 ICE->getCastKind() == CK_FloatingCast) {
5194 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00005195 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00005196
5197 // Check if we didn't match because of an implicit cast from a 'char'
5198 // or 'short' to an 'int'. This is done because printf is a varargs
5199 // function.
5200 if (ICE->getType() == S.Context.IntTy ||
5201 ICE->getType() == S.Context.UnsignedIntTy) {
5202 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00005203 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00005204 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00005205 }
Jordan Rose98709982012-06-04 22:48:57 +00005206 }
Jordan Rose598ec092012-12-05 18:44:40 +00005207 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
5208 // Special case for 'a', which has type 'int' in C.
5209 // Note, however, that we do /not/ want to treat multibyte constants like
5210 // 'MooV' as characters! This form is deprecated but still exists.
5211 if (ExprTy == S.Context.IntTy)
5212 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
5213 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00005214 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005215
Jordan Rosebc53ed12014-05-31 04:12:14 +00005216 // Look through enums to their underlying type.
5217 bool IsEnum = false;
5218 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
5219 ExprTy = EnumTy->getDecl()->getIntegerType();
5220 IsEnum = true;
5221 }
5222
Jordan Rose0e5badd2012-12-05 18:44:49 +00005223 // %C in an Objective-C context prints a unichar, not a wchar_t.
5224 // If the argument is an integer of some kind, believe the %C and suggest
5225 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00005226 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00005227 if (ObjCContext &&
5228 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
5229 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
5230 !ExprTy->isCharType()) {
5231 // 'unichar' is defined as a typedef of unsigned short, but we should
5232 // prefer using the typedef if it is visible.
5233 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00005234
5235 // While we are here, check if the value is an IntegerLiteral that happens
5236 // to be within the valid range.
5237 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
5238 const llvm::APInt &V = IL->getValue();
5239 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
5240 return true;
5241 }
5242
Jordan Rose0e5badd2012-12-05 18:44:49 +00005243 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
5244 Sema::LookupOrdinaryName);
5245 if (S.LookupName(Result, S.getCurScope())) {
5246 NamedDecl *ND = Result.getFoundDecl();
5247 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
5248 if (TD->getUnderlyingType() == IntendedTy)
5249 IntendedTy = S.Context.getTypedefType(TD);
5250 }
5251 }
5252 }
5253
5254 // Special-case some of Darwin's platform-independence types by suggesting
5255 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005256 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00005257 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005258 QualType CastTy;
5259 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
5260 if (!CastTy.isNull()) {
5261 IntendedTy = CastTy;
5262 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00005263 }
5264 }
5265
Jordan Rose22b74712012-09-05 22:56:19 +00005266 // We may be able to offer a FixItHint if it is a supported type.
5267 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00005268 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00005269 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005270
Jordan Rose22b74712012-09-05 22:56:19 +00005271 if (success) {
5272 // Get the fix string from the fixed format specifier
5273 SmallString<16> buf;
5274 llvm::raw_svector_ostream os(buf);
5275 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005276
Jordan Roseaee34382012-09-05 22:56:26 +00005277 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
5278
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005279 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00005280 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5281 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
5282 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5283 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00005284 // In this case, the specifier is wrong and should be changed to match
5285 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00005286 EmitFormatDiagnostic(S.PDiag(diag)
5287 << AT.getRepresentativeTypeName(S.Context)
5288 << IntendedTy << IsEnum << E->getSourceRange(),
5289 E->getLocStart(),
5290 /*IsStringLocation*/ false, SpecRange,
5291 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00005292 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00005293 // The canonical type for formatting this value is different from the
5294 // actual type of the expression. (This occurs, for example, with Darwin's
5295 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
5296 // should be printed as 'long' for 64-bit compatibility.)
5297 // Rather than emitting a normal format/argument mismatch, we want to
5298 // add a cast to the recommended type (and correct the format string
5299 // if necessary).
5300 SmallString<16> CastBuf;
5301 llvm::raw_svector_ostream CastFix(CastBuf);
5302 CastFix << "(";
5303 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
5304 CastFix << ")";
5305
5306 SmallVector<FixItHint,4> Hints;
5307 if (!AT.matchesType(S.Context, IntendedTy))
5308 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
5309
5310 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
5311 // If there's already a cast present, just replace it.
5312 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
5313 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
5314
5315 } else if (!requiresParensToAddCast(E)) {
5316 // If the expression has high enough precedence,
5317 // just write the C-style cast.
5318 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
5319 CastFix.str()));
5320 } else {
5321 // Otherwise, add parens around the expression as well as the cast.
5322 CastFix << "(";
5323 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
5324 CastFix.str()));
5325
Alp Tokerb6cc5922014-05-03 03:45:55 +00005326 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00005327 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
5328 }
5329
Jordan Rose0e5badd2012-12-05 18:44:49 +00005330 if (ShouldNotPrintDirectly) {
5331 // The expression has a type that should not be printed directly.
5332 // We extract the name from the typedef because we don't want to show
5333 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005334 StringRef Name;
5335 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
5336 Name = TypedefTy->getDecl()->getName();
5337 else
5338 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00005339 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00005340 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00005341 << E->getSourceRange(),
5342 E->getLocStart(), /*IsStringLocation=*/false,
5343 SpecRange, Hints);
5344 } else {
5345 // In this case, the expression could be printed using a different
5346 // specifier, but we've decided that the specifier is probably correct
5347 // and we should cast instead. Just use the normal warning message.
5348 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00005349 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5350 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00005351 << E->getSourceRange(),
5352 E->getLocStart(), /*IsStringLocation*/false,
5353 SpecRange, Hints);
5354 }
Jordan Roseaee34382012-09-05 22:56:26 +00005355 }
Jordan Rose22b74712012-09-05 22:56:19 +00005356 } else {
5357 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
5358 SpecifierLen);
5359 // Since the warning for passing non-POD types to variadic functions
5360 // was deferred until now, we emit a warning for non-POD
5361 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00005362 switch (S.isValidVarArgType(ExprTy)) {
5363 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00005364 case Sema::VAK_ValidInCXX11: {
5365 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5366 if (match == analyze_printf::ArgType::NoMatchPedantic) {
5367 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5368 }
Richard Smithd7293d72013-08-05 18:49:43 +00005369
Seth Cantrellb4802962015-03-04 03:12:10 +00005370 EmitFormatDiagnostic(
5371 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
5372 << IsEnum << CSR << E->getSourceRange(),
5373 E->getLocStart(), /*IsStringLocation*/ false, CSR);
5374 break;
5375 }
Richard Smithd7293d72013-08-05 18:49:43 +00005376 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00005377 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00005378 EmitFormatDiagnostic(
5379 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005380 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00005381 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00005382 << CallType
5383 << AT.getRepresentativeTypeName(S.Context)
5384 << CSR
5385 << E->getSourceRange(),
5386 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00005387 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00005388 break;
5389
5390 case Sema::VAK_Invalid:
5391 if (ExprTy->isObjCObjectType())
5392 EmitFormatDiagnostic(
5393 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
5394 << S.getLangOpts().CPlusPlus11
5395 << ExprTy
5396 << CallType
5397 << AT.getRepresentativeTypeName(S.Context)
5398 << CSR
5399 << E->getSourceRange(),
5400 E->getLocStart(), /*IsStringLocation*/false, CSR);
5401 else
5402 // FIXME: If this is an initializer list, suggest removing the braces
5403 // or inserting a cast to the target type.
5404 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
5405 << isa<InitListExpr>(E) << ExprTy << CallType
5406 << AT.getRepresentativeTypeName(S.Context)
5407 << E->getSourceRange();
5408 break;
5409 }
5410
5411 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
5412 "format string specifier index out of range");
5413 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005414 }
5415
Ted Kremenekab278de2010-01-28 23:39:18 +00005416 return true;
5417}
5418
Ted Kremenek02087932010-07-16 02:11:22 +00005419//===--- CHECK: Scanf format string checking ------------------------------===//
5420
5421namespace {
5422class CheckScanfHandler : public CheckFormatHandler {
5423public:
5424 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
5425 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005426 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005427 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005428 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00005429 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005430 llvm::SmallBitVector &CheckedVarArgs,
5431 UncoveredArgHandler &UncoveredArg)
Richard Smithd7293d72013-08-05 18:49:43 +00005432 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
5433 numDataArgs, beg, hasVAListArg,
5434 Args, formatIdx, inFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005435 CheckedVarArgs, UncoveredArg)
Jordan Rose3e0ec582012-07-19 18:10:23 +00005436 {}
Ted Kremenek02087932010-07-16 02:11:22 +00005437
5438 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
5439 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005440 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00005441
5442 bool HandleInvalidScanfConversionSpecifier(
5443 const analyze_scanf::ScanfSpecifier &FS,
5444 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005445 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00005446
Craig Toppere14c0f82014-03-12 04:55:44 +00005447 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00005448};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005449} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00005450
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00005451void CheckScanfHandler::HandleIncompleteScanList(const char *start,
5452 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005453 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
5454 getLocationOfByte(end), /*IsStringLocation*/true,
5455 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00005456}
5457
Ted Kremenekce815422010-07-19 21:25:57 +00005458bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
5459 const analyze_scanf::ScanfSpecifier &FS,
5460 const char *startSpecifier,
5461 unsigned specifierLen) {
5462
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005463 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00005464 FS.getConversionSpecifier();
5465
5466 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5467 getLocationOfByte(CS.getStart()),
5468 startSpecifier, specifierLen,
5469 CS.getStart(), CS.getLength());
5470}
5471
Ted Kremenek02087932010-07-16 02:11:22 +00005472bool CheckScanfHandler::HandleScanfSpecifier(
5473 const analyze_scanf::ScanfSpecifier &FS,
5474 const char *startSpecifier,
5475 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00005476 using namespace analyze_scanf;
5477 using namespace analyze_format_string;
5478
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005479 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00005480
Ted Kremenek6cd69422010-07-19 22:01:06 +00005481 // Handle case where '%' and '*' don't consume an argument. These shouldn't
5482 // be used to decide if we are using positional arguments consistently.
5483 if (FS.consumesDataArgument()) {
5484 if (atFirstArg) {
5485 atFirstArg = false;
5486 usesPositionalArgs = FS.usesPositionalArg();
5487 }
5488 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005489 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5490 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00005491 return false;
5492 }
Ted Kremenek02087932010-07-16 02:11:22 +00005493 }
5494
5495 // Check if the field with is non-zero.
5496 const OptionalAmount &Amt = FS.getFieldWidth();
5497 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
5498 if (Amt.getConstantAmount() == 0) {
5499 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
5500 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00005501 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
5502 getLocationOfByte(Amt.getStart()),
5503 /*IsStringLocation*/true, R,
5504 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00005505 }
5506 }
Seth Cantrellb4802962015-03-04 03:12:10 +00005507
Ted Kremenek02087932010-07-16 02:11:22 +00005508 if (!FS.consumesDataArgument()) {
5509 // FIXME: Technically specifying a precision or field width here
5510 // makes no sense. Worth issuing a warning at some point.
5511 return true;
5512 }
Seth Cantrellb4802962015-03-04 03:12:10 +00005513
Ted Kremenek02087932010-07-16 02:11:22 +00005514 // Consume the argument.
5515 unsigned argIndex = FS.getArgIndex();
5516 if (argIndex < NumDataArgs) {
5517 // The check to see if the argIndex is valid will come later.
5518 // We set the bit here because we may exit early from this
5519 // function if we encounter some other error.
5520 CoveredArgs.set(argIndex);
5521 }
Seth Cantrellb4802962015-03-04 03:12:10 +00005522
Ted Kremenek4407ea42010-07-20 20:04:47 +00005523 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00005524 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00005525 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5526 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00005527 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005528 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00005529 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005530 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5531 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005532
Jordan Rose92303592012-09-08 04:00:03 +00005533 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
5534 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5535
Ted Kremenek02087932010-07-16 02:11:22 +00005536 // The remaining checks depend on the data arguments.
5537 if (HasVAListArg)
5538 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00005539
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005540 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00005541 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00005542
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005543 // Check that the argument type matches the format specifier.
5544 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00005545 if (!Ex)
5546 return true;
5547
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00005548 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00005549
5550 if (!AT.isValid()) {
5551 return true;
5552 }
5553
Seth Cantrellb4802962015-03-04 03:12:10 +00005554 analyze_format_string::ArgType::MatchKind match =
5555 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00005556 if (match == analyze_format_string::ArgType::Match) {
5557 return true;
5558 }
Seth Cantrellb4802962015-03-04 03:12:10 +00005559
Seth Cantrell79340072015-03-04 05:58:08 +00005560 ScanfSpecifier fixedFS = FS;
5561 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
5562 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005563
Seth Cantrell79340072015-03-04 05:58:08 +00005564 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5565 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
5566 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5567 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005568
Seth Cantrell79340072015-03-04 05:58:08 +00005569 if (success) {
5570 // Get the fix string from the fixed format specifier.
5571 SmallString<128> buf;
5572 llvm::raw_svector_ostream os(buf);
5573 fixedFS.toString(os);
5574
5575 EmitFormatDiagnostic(
5576 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
5577 << Ex->getType() << false << Ex->getSourceRange(),
5578 Ex->getLocStart(),
5579 /*IsStringLocation*/ false,
5580 getSpecifierRange(startSpecifier, specifierLen),
5581 FixItHint::CreateReplacement(
5582 getSpecifierRange(startSpecifier, specifierLen), os.str()));
5583 } else {
5584 EmitFormatDiagnostic(S.PDiag(diag)
5585 << AT.getRepresentativeTypeName(S.Context)
5586 << Ex->getType() << false << Ex->getSourceRange(),
5587 Ex->getLocStart(),
5588 /*IsStringLocation*/ false,
5589 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005590 }
5591
Ted Kremenek02087932010-07-16 02:11:22 +00005592 return true;
5593}
5594
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005595static void CheckFormatString(Sema &S, const StringLiteral *FExpr,
5596 const Expr *OrigFormatExpr,
5597 ArrayRef<const Expr *> Args,
5598 bool HasVAListArg, unsigned format_idx,
5599 unsigned firstDataArg,
5600 Sema::FormatStringType Type,
5601 bool inFunctionCall,
5602 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005603 llvm::SmallBitVector &CheckedVarArgs,
5604 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00005605 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00005606 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005607 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005608 S, inFunctionCall, Args[format_idx],
5609 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00005610 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00005611 return;
5612 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005613
Ted Kremenekab278de2010-01-28 23:39:18 +00005614 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005615 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00005616 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005617 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005618 const ConstantArrayType *T =
5619 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005620 assert(T && "String literal not of constant array type!");
5621 size_t TypeSize = T->getSize().getZExtValue();
5622 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005623 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005624
5625 // Emit a warning if the string literal is truncated and does not contain an
5626 // embedded null character.
5627 if (TypeSize <= StrRef.size() &&
5628 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
5629 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005630 S, inFunctionCall, Args[format_idx],
5631 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005632 FExpr->getLocStart(),
5633 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
5634 return;
5635 }
5636
Ted Kremenekab278de2010-01-28 23:39:18 +00005637 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00005638 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005639 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005640 S, inFunctionCall, Args[format_idx],
5641 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00005642 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00005643 return;
5644 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005645
5646 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
5647 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSTrace) {
5648 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, firstDataArg,
5649 numDataArgs, (Type == Sema::FST_NSString ||
5650 Type == Sema::FST_OSTrace),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005651 Str, HasVAListArg, Args, format_idx,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005652 inFunctionCall, CallType, CheckedVarArgs,
5653 UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005654
Hans Wennborg23926bd2011-12-15 10:25:47 +00005655 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005656 S.getLangOpts(),
5657 S.Context.getTargetInfo(),
5658 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00005659 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005660 } else if (Type == Sema::FST_Scanf) {
5661 CheckScanfHandler H(S, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005662 Str, HasVAListArg, Args, format_idx,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005663 inFunctionCall, CallType, CheckedVarArgs,
5664 UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005665
Hans Wennborg23926bd2011-12-15 10:25:47 +00005666 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005667 S.getLangOpts(),
5668 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00005669 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005670 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00005671}
5672
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00005673bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
5674 // Str - The format string. NOTE: this is NOT null-terminated!
5675 StringRef StrRef = FExpr->getString();
5676 const char *Str = StrRef.data();
5677 // Account for cases where the string literal is truncated in a declaration.
5678 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
5679 assert(T && "String literal not of constant array type!");
5680 size_t TypeSize = T->getSize().getZExtValue();
5681 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
5682 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
5683 getLangOpts(),
5684 Context.getTargetInfo());
5685}
5686
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005687//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
5688
5689// Returns the related absolute value function that is larger, of 0 if one
5690// does not exist.
5691static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
5692 switch (AbsFunction) {
5693 default:
5694 return 0;
5695
5696 case Builtin::BI__builtin_abs:
5697 return Builtin::BI__builtin_labs;
5698 case Builtin::BI__builtin_labs:
5699 return Builtin::BI__builtin_llabs;
5700 case Builtin::BI__builtin_llabs:
5701 return 0;
5702
5703 case Builtin::BI__builtin_fabsf:
5704 return Builtin::BI__builtin_fabs;
5705 case Builtin::BI__builtin_fabs:
5706 return Builtin::BI__builtin_fabsl;
5707 case Builtin::BI__builtin_fabsl:
5708 return 0;
5709
5710 case Builtin::BI__builtin_cabsf:
5711 return Builtin::BI__builtin_cabs;
5712 case Builtin::BI__builtin_cabs:
5713 return Builtin::BI__builtin_cabsl;
5714 case Builtin::BI__builtin_cabsl:
5715 return 0;
5716
5717 case Builtin::BIabs:
5718 return Builtin::BIlabs;
5719 case Builtin::BIlabs:
5720 return Builtin::BIllabs;
5721 case Builtin::BIllabs:
5722 return 0;
5723
5724 case Builtin::BIfabsf:
5725 return Builtin::BIfabs;
5726 case Builtin::BIfabs:
5727 return Builtin::BIfabsl;
5728 case Builtin::BIfabsl:
5729 return 0;
5730
5731 case Builtin::BIcabsf:
5732 return Builtin::BIcabs;
5733 case Builtin::BIcabs:
5734 return Builtin::BIcabsl;
5735 case Builtin::BIcabsl:
5736 return 0;
5737 }
5738}
5739
5740// Returns the argument type of the absolute value function.
5741static QualType getAbsoluteValueArgumentType(ASTContext &Context,
5742 unsigned AbsType) {
5743 if (AbsType == 0)
5744 return QualType();
5745
5746 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
5747 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
5748 if (Error != ASTContext::GE_None)
5749 return QualType();
5750
5751 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
5752 if (!FT)
5753 return QualType();
5754
5755 if (FT->getNumParams() != 1)
5756 return QualType();
5757
5758 return FT->getParamType(0);
5759}
5760
5761// Returns the best absolute value function, or zero, based on type and
5762// current absolute value function.
5763static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
5764 unsigned AbsFunctionKind) {
5765 unsigned BestKind = 0;
5766 uint64_t ArgSize = Context.getTypeSize(ArgType);
5767 for (unsigned Kind = AbsFunctionKind; Kind != 0;
5768 Kind = getLargerAbsoluteValueFunction(Kind)) {
5769 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
5770 if (Context.getTypeSize(ParamType) >= ArgSize) {
5771 if (BestKind == 0)
5772 BestKind = Kind;
5773 else if (Context.hasSameType(ParamType, ArgType)) {
5774 BestKind = Kind;
5775 break;
5776 }
5777 }
5778 }
5779 return BestKind;
5780}
5781
5782enum AbsoluteValueKind {
5783 AVK_Integer,
5784 AVK_Floating,
5785 AVK_Complex
5786};
5787
5788static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
5789 if (T->isIntegralOrEnumerationType())
5790 return AVK_Integer;
5791 if (T->isRealFloatingType())
5792 return AVK_Floating;
5793 if (T->isAnyComplexType())
5794 return AVK_Complex;
5795
5796 llvm_unreachable("Type not integer, floating, or complex");
5797}
5798
5799// Changes the absolute value function to a different type. Preserves whether
5800// the function is a builtin.
5801static unsigned changeAbsFunction(unsigned AbsKind,
5802 AbsoluteValueKind ValueKind) {
5803 switch (ValueKind) {
5804 case AVK_Integer:
5805 switch (AbsKind) {
5806 default:
5807 return 0;
5808 case Builtin::BI__builtin_fabsf:
5809 case Builtin::BI__builtin_fabs:
5810 case Builtin::BI__builtin_fabsl:
5811 case Builtin::BI__builtin_cabsf:
5812 case Builtin::BI__builtin_cabs:
5813 case Builtin::BI__builtin_cabsl:
5814 return Builtin::BI__builtin_abs;
5815 case Builtin::BIfabsf:
5816 case Builtin::BIfabs:
5817 case Builtin::BIfabsl:
5818 case Builtin::BIcabsf:
5819 case Builtin::BIcabs:
5820 case Builtin::BIcabsl:
5821 return Builtin::BIabs;
5822 }
5823 case AVK_Floating:
5824 switch (AbsKind) {
5825 default:
5826 return 0;
5827 case Builtin::BI__builtin_abs:
5828 case Builtin::BI__builtin_labs:
5829 case Builtin::BI__builtin_llabs:
5830 case Builtin::BI__builtin_cabsf:
5831 case Builtin::BI__builtin_cabs:
5832 case Builtin::BI__builtin_cabsl:
5833 return Builtin::BI__builtin_fabsf;
5834 case Builtin::BIabs:
5835 case Builtin::BIlabs:
5836 case Builtin::BIllabs:
5837 case Builtin::BIcabsf:
5838 case Builtin::BIcabs:
5839 case Builtin::BIcabsl:
5840 return Builtin::BIfabsf;
5841 }
5842 case AVK_Complex:
5843 switch (AbsKind) {
5844 default:
5845 return 0;
5846 case Builtin::BI__builtin_abs:
5847 case Builtin::BI__builtin_labs:
5848 case Builtin::BI__builtin_llabs:
5849 case Builtin::BI__builtin_fabsf:
5850 case Builtin::BI__builtin_fabs:
5851 case Builtin::BI__builtin_fabsl:
5852 return Builtin::BI__builtin_cabsf;
5853 case Builtin::BIabs:
5854 case Builtin::BIlabs:
5855 case Builtin::BIllabs:
5856 case Builtin::BIfabsf:
5857 case Builtin::BIfabs:
5858 case Builtin::BIfabsl:
5859 return Builtin::BIcabsf;
5860 }
5861 }
5862 llvm_unreachable("Unable to convert function");
5863}
5864
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00005865static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005866 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
5867 if (!FnInfo)
5868 return 0;
5869
5870 switch (FDecl->getBuiltinID()) {
5871 default:
5872 return 0;
5873 case Builtin::BI__builtin_abs:
5874 case Builtin::BI__builtin_fabs:
5875 case Builtin::BI__builtin_fabsf:
5876 case Builtin::BI__builtin_fabsl:
5877 case Builtin::BI__builtin_labs:
5878 case Builtin::BI__builtin_llabs:
5879 case Builtin::BI__builtin_cabs:
5880 case Builtin::BI__builtin_cabsf:
5881 case Builtin::BI__builtin_cabsl:
5882 case Builtin::BIabs:
5883 case Builtin::BIlabs:
5884 case Builtin::BIllabs:
5885 case Builtin::BIfabs:
5886 case Builtin::BIfabsf:
5887 case Builtin::BIfabsl:
5888 case Builtin::BIcabs:
5889 case Builtin::BIcabsf:
5890 case Builtin::BIcabsl:
5891 return FDecl->getBuiltinID();
5892 }
5893 llvm_unreachable("Unknown Builtin type");
5894}
5895
5896// If the replacement is valid, emit a note with replacement function.
5897// Additionally, suggest including the proper header if not already included.
5898static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00005899 unsigned AbsKind, QualType ArgType) {
5900 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00005901 const char *HeaderName = nullptr;
5902 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00005903 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
5904 FunctionName = "std::abs";
5905 if (ArgType->isIntegralOrEnumerationType()) {
5906 HeaderName = "cstdlib";
5907 } else if (ArgType->isRealFloatingType()) {
5908 HeaderName = "cmath";
5909 } else {
5910 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005911 }
Richard Trieubeffb832014-04-15 23:47:53 +00005912
5913 // Lookup all std::abs
5914 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00005915 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00005916 R.suppressDiagnostics();
5917 S.LookupQualifiedName(R, Std);
5918
5919 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005920 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00005921 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
5922 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
5923 } else {
5924 FDecl = dyn_cast<FunctionDecl>(I);
5925 }
5926 if (!FDecl)
5927 continue;
5928
5929 // Found std::abs(), check that they are the right ones.
5930 if (FDecl->getNumParams() != 1)
5931 continue;
5932
5933 // Check that the parameter type can handle the argument.
5934 QualType ParamType = FDecl->getParamDecl(0)->getType();
5935 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
5936 S.Context.getTypeSize(ArgType) <=
5937 S.Context.getTypeSize(ParamType)) {
5938 // Found a function, don't need the header hint.
5939 EmitHeaderHint = false;
5940 break;
5941 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005942 }
Richard Trieubeffb832014-04-15 23:47:53 +00005943 }
5944 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00005945 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00005946 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
5947
5948 if (HeaderName) {
5949 DeclarationName DN(&S.Context.Idents.get(FunctionName));
5950 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
5951 R.suppressDiagnostics();
5952 S.LookupName(R, S.getCurScope());
5953
5954 if (R.isSingleResult()) {
5955 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
5956 if (FD && FD->getBuiltinID() == AbsKind) {
5957 EmitHeaderHint = false;
5958 } else {
5959 return;
5960 }
5961 } else if (!R.empty()) {
5962 return;
5963 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005964 }
5965 }
5966
5967 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00005968 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005969
Richard Trieubeffb832014-04-15 23:47:53 +00005970 if (!HeaderName)
5971 return;
5972
5973 if (!EmitHeaderHint)
5974 return;
5975
Alp Toker5d96e0a2014-07-11 20:53:51 +00005976 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
5977 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00005978}
5979
5980static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
5981 if (!FDecl)
5982 return false;
5983
5984 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
5985 return false;
5986
5987 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
5988
5989 while (ND && ND->isInlineNamespace()) {
5990 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005991 }
Richard Trieubeffb832014-04-15 23:47:53 +00005992
5993 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
5994 return false;
5995
5996 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
5997 return false;
5998
5999 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006000}
6001
6002// Warn when using the wrong abs() function.
6003void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
6004 const FunctionDecl *FDecl,
6005 IdentifierInfo *FnInfo) {
6006 if (Call->getNumArgs() != 1)
6007 return;
6008
6009 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00006010 bool IsStdAbs = IsFunctionStdAbs(FDecl);
6011 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006012 return;
6013
6014 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6015 QualType ParamType = Call->getArg(0)->getType();
6016
Alp Toker5d96e0a2014-07-11 20:53:51 +00006017 // Unsigned types cannot be negative. Suggest removing the absolute value
6018 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006019 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00006020 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00006021 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006022 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
6023 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00006024 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006025 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
6026 return;
6027 }
6028
David Majnemer7f77eb92015-11-15 03:04:34 +00006029 // Taking the absolute value of a pointer is very suspicious, they probably
6030 // wanted to index into an array, dereference a pointer, call a function, etc.
6031 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
6032 unsigned DiagType = 0;
6033 if (ArgType->isFunctionType())
6034 DiagType = 1;
6035 else if (ArgType->isArrayType())
6036 DiagType = 2;
6037
6038 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
6039 return;
6040 }
6041
Richard Trieubeffb832014-04-15 23:47:53 +00006042 // std::abs has overloads which prevent most of the absolute value problems
6043 // from occurring.
6044 if (IsStdAbs)
6045 return;
6046
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006047 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
6048 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
6049
6050 // The argument and parameter are the same kind. Check if they are the right
6051 // size.
6052 if (ArgValueKind == ParamValueKind) {
6053 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
6054 return;
6055
6056 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
6057 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
6058 << FDecl << ArgType << ParamType;
6059
6060 if (NewAbsKind == 0)
6061 return;
6062
6063 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00006064 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006065 return;
6066 }
6067
6068 // ArgValueKind != ParamValueKind
6069 // The wrong type of absolute value function was used. Attempt to find the
6070 // proper one.
6071 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
6072 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
6073 if (NewAbsKind == 0)
6074 return;
6075
6076 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
6077 << FDecl << ParamValueKind << ArgValueKind;
6078
6079 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00006080 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006081}
6082
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006083//===--- CHECK: Standard memory functions ---------------------------------===//
6084
Nico Weber0e6daef2013-12-26 23:38:39 +00006085/// \brief Takes the expression passed to the size_t parameter of functions
6086/// such as memcmp, strncat, etc and warns if it's a comparison.
6087///
6088/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
6089static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
6090 IdentifierInfo *FnName,
6091 SourceLocation FnLoc,
6092 SourceLocation RParenLoc) {
6093 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
6094 if (!Size)
6095 return false;
6096
6097 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
6098 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
6099 return false;
6100
Nico Weber0e6daef2013-12-26 23:38:39 +00006101 SourceRange SizeRange = Size->getSourceRange();
6102 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
6103 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00006104 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00006105 << FnName << FixItHint::CreateInsertion(
6106 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00006107 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00006108 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00006109 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00006110 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
6111 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00006112
6113 return true;
6114}
6115
Reid Kleckner5fb5b122014-06-27 23:58:21 +00006116/// \brief Determine whether the given type is or contains a dynamic class type
6117/// (e.g., whether it has a vtable).
6118static const CXXRecordDecl *getContainedDynamicClass(QualType T,
6119 bool &IsContained) {
6120 // Look through array types while ignoring qualifiers.
6121 const Type *Ty = T->getBaseElementTypeUnsafe();
6122 IsContained = false;
6123
6124 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
6125 RD = RD ? RD->getDefinition() : nullptr;
Richard Trieu1c7237a2016-03-31 04:18:07 +00006126 if (!RD || RD->isInvalidDecl())
Reid Kleckner5fb5b122014-06-27 23:58:21 +00006127 return nullptr;
6128
6129 if (RD->isDynamicClass())
6130 return RD;
6131
6132 // Check all the fields. If any bases were dynamic, the class is dynamic.
6133 // It's impossible for a class to transitively contain itself by value, so
6134 // infinite recursion is impossible.
6135 for (auto *FD : RD->fields()) {
6136 bool SubContained;
6137 if (const CXXRecordDecl *ContainedRD =
6138 getContainedDynamicClass(FD->getType(), SubContained)) {
6139 IsContained = true;
6140 return ContainedRD;
6141 }
6142 }
6143
6144 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00006145}
6146
Chandler Carruth889ed862011-06-21 23:04:20 +00006147/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006148/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00006149static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00006150 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006151 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6152 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
6153 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00006154
Craig Topperc3ec1492014-05-26 06:22:03 +00006155 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006156}
6157
Chandler Carruth889ed862011-06-21 23:04:20 +00006158/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00006159static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006160 if (const UnaryExprOrTypeTraitExpr *SizeOf =
6161 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6162 if (SizeOf->getKind() == clang::UETT_SizeOf)
6163 return SizeOf->getTypeOfArgument();
6164
6165 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00006166}
6167
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006168/// \brief Check for dangerous or invalid arguments to memset().
6169///
Chandler Carruthac687262011-06-03 06:23:57 +00006170/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00006171/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
6172/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006173///
6174/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00006175void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00006176 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00006177 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00006178 assert(BId != 0);
6179
Ted Kremenekb5fabb22011-04-28 01:38:02 +00006180 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00006181 // we have enough arguments, and if not, abort further checking.
Bruno Cardoso Lopes9e4374d2016-08-05 16:41:00 +00006182 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00006183 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00006184 return;
6185
Bruno Cardoso Lopes9e4374d2016-08-05 16:41:00 +00006186 unsigned LastArg = (BId == Builtin::BImemset ||
Anna Zaks22122702012-01-17 00:37:07 +00006187 BId == Builtin::BIstrndup ? 1 : 2);
Bruno Cardoso Lopes9e4374d2016-08-05 16:41:00 +00006188 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00006189 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006190
Nico Weber0e6daef2013-12-26 23:38:39 +00006191 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
6192 Call->getLocStart(), Call->getRParenLoc()))
6193 return;
6194
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006195 // We have special checking when the length is a sizeof expression.
6196 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
6197 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
6198 llvm::FoldingSetNodeID SizeOfArgID;
6199
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006200 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
6201 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00006202 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006203
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006204 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00006205 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006206 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00006207 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00006208
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006209 // Never warn about void type pointers. This can be used to suppress
6210 // false positives.
6211 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006212 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006213
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006214 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
6215 // actually comparing the expressions for equality. Because computing the
6216 // expression IDs can be expensive, we only do this if the diagnostic is
6217 // enabled.
6218 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006219 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
6220 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006221 // We only compute IDs for expressions if the warning is enabled, and
6222 // cache the sizeof arg's ID.
6223 if (SizeOfArgID == llvm::FoldingSetNodeID())
6224 SizeOfArg->Profile(SizeOfArgID, Context, true);
6225 llvm::FoldingSetNodeID DestID;
6226 Dest->Profile(DestID, Context, true);
6227 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00006228 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
6229 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006230 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00006231 StringRef ReadableName = FnName->getName();
6232
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006233 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00006234 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006235 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00006236 if (!PointeeTy->isIncompleteType() &&
6237 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006238 ActionIdx = 2; // If the pointee's size is sizeof(char),
6239 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00006240
6241 // If the function is defined as a builtin macro, do not show macro
6242 // expansion.
6243 SourceLocation SL = SizeOfArg->getExprLoc();
6244 SourceRange DSR = Dest->getSourceRange();
6245 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00006246 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00006247
6248 if (SM.isMacroArgExpansion(SL)) {
6249 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
6250 SL = SM.getSpellingLoc(SL);
6251 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
6252 SM.getSpellingLoc(DSR.getEnd()));
6253 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
6254 SM.getSpellingLoc(SSR.getEnd()));
6255 }
6256
Anna Zaksd08d9152012-05-30 23:14:52 +00006257 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006258 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00006259 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00006260 << PointeeTy
6261 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00006262 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00006263 << SSR);
6264 DiagRuntimeBehavior(SL, SizeOfArg,
6265 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
6266 << ActionIdx
6267 << SSR);
6268
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006269 break;
6270 }
6271 }
6272
6273 // Also check for cases where the sizeof argument is the exact same
6274 // type as the memory argument, and where it points to a user-defined
6275 // record type.
6276 if (SizeOfArgTy != QualType()) {
6277 if (PointeeTy->isRecordType() &&
6278 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
6279 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
6280 PDiag(diag::warn_sizeof_pointer_type_memaccess)
6281 << FnName << SizeOfArgTy << ArgIdx
6282 << PointeeTy << Dest->getSourceRange()
6283 << LenExpr->getSourceRange());
6284 break;
6285 }
Nico Weberc5e73862011-06-14 16:14:58 +00006286 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00006287 } else if (DestTy->isArrayType()) {
6288 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00006289 }
Nico Weberc5e73862011-06-14 16:14:58 +00006290
Nico Weberc44b35e2015-03-21 17:37:46 +00006291 if (PointeeTy == QualType())
6292 continue;
Anna Zaks22122702012-01-17 00:37:07 +00006293
Nico Weberc44b35e2015-03-21 17:37:46 +00006294 // Always complain about dynamic classes.
6295 bool IsContained;
6296 if (const CXXRecordDecl *ContainedRD =
6297 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00006298
Nico Weberc44b35e2015-03-21 17:37:46 +00006299 unsigned OperationType = 0;
6300 // "overwritten" if we're warning about the destination for any call
6301 // but memcmp; otherwise a verb appropriate to the call.
6302 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
6303 if (BId == Builtin::BImemcpy)
6304 OperationType = 1;
6305 else if(BId == Builtin::BImemmove)
6306 OperationType = 2;
6307 else if (BId == Builtin::BImemcmp)
6308 OperationType = 3;
6309 }
6310
John McCall31168b02011-06-15 23:02:42 +00006311 DiagRuntimeBehavior(
6312 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00006313 PDiag(diag::warn_dyn_class_memaccess)
6314 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
6315 << FnName << IsContained << ContainedRD << OperationType
6316 << Call->getCallee()->getSourceRange());
6317 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
6318 BId != Builtin::BImemset)
6319 DiagRuntimeBehavior(
6320 Dest->getExprLoc(), Dest,
6321 PDiag(diag::warn_arc_object_memaccess)
6322 << ArgIdx << FnName << PointeeTy
6323 << Call->getCallee()->getSourceRange());
6324 else
6325 continue;
6326
6327 DiagRuntimeBehavior(
6328 Dest->getExprLoc(), Dest,
6329 PDiag(diag::note_bad_memaccess_silence)
6330 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
6331 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006332 }
6333}
6334
Ted Kremenek6865f772011-08-18 20:55:45 +00006335// A little helper routine: ignore addition and subtraction of integer literals.
6336// This intentionally does not ignore all integer constant expressions because
6337// we don't want to remove sizeof().
6338static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
6339 Ex = Ex->IgnoreParenCasts();
6340
6341 for (;;) {
6342 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
6343 if (!BO || !BO->isAdditiveOp())
6344 break;
6345
6346 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
6347 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
6348
6349 if (isa<IntegerLiteral>(RHS))
6350 Ex = LHS;
6351 else if (isa<IntegerLiteral>(LHS))
6352 Ex = RHS;
6353 else
6354 break;
6355 }
6356
6357 return Ex;
6358}
6359
Anna Zaks13b08572012-08-08 21:42:23 +00006360static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
6361 ASTContext &Context) {
6362 // Only handle constant-sized or VLAs, but not flexible members.
6363 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
6364 // Only issue the FIXIT for arrays of size > 1.
6365 if (CAT->getSize().getSExtValue() <= 1)
6366 return false;
6367 } else if (!Ty->isVariableArrayType()) {
6368 return false;
6369 }
6370 return true;
6371}
6372
Ted Kremenek6865f772011-08-18 20:55:45 +00006373// Warn if the user has made the 'size' argument to strlcpy or strlcat
6374// be the size of the source, instead of the destination.
6375void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
6376 IdentifierInfo *FnName) {
6377
6378 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00006379 unsigned NumArgs = Call->getNumArgs();
6380 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00006381 return;
6382
6383 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
6384 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00006385 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00006386
6387 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
6388 Call->getLocStart(), Call->getRParenLoc()))
6389 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00006390
6391 // Look for 'strlcpy(dst, x, sizeof(x))'
6392 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
6393 CompareWithSrc = Ex;
6394 else {
6395 // Look for 'strlcpy(dst, x, strlen(x))'
6396 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00006397 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
6398 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00006399 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
6400 }
6401 }
6402
6403 if (!CompareWithSrc)
6404 return;
6405
6406 // Determine if the argument to sizeof/strlen is equal to the source
6407 // argument. In principle there's all kinds of things you could do
6408 // here, for instance creating an == expression and evaluating it with
6409 // EvaluateAsBooleanCondition, but this uses a more direct technique:
6410 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
6411 if (!SrcArgDRE)
6412 return;
6413
6414 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
6415 if (!CompareWithSrcDRE ||
6416 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
6417 return;
6418
6419 const Expr *OriginalSizeArg = Call->getArg(2);
6420 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
6421 << OriginalSizeArg->getSourceRange() << FnName;
6422
6423 // Output a FIXIT hint if the destination is an array (rather than a
6424 // pointer to an array). This could be enhanced to handle some
6425 // pointers if we know the actual size, like if DstArg is 'array+2'
6426 // we could say 'sizeof(array)-2'.
6427 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00006428 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00006429 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00006430
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00006431 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00006432 llvm::raw_svector_ostream OS(sizeString);
6433 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00006434 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00006435 OS << ")";
6436
6437 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
6438 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
6439 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00006440}
6441
Anna Zaks314cd092012-02-01 19:08:57 +00006442/// Check if two expressions refer to the same declaration.
6443static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
6444 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
6445 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
6446 return D1->getDecl() == D2->getDecl();
6447 return false;
6448}
6449
6450static const Expr *getStrlenExprArg(const Expr *E) {
6451 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6452 const FunctionDecl *FD = CE->getDirectCallee();
6453 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00006454 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00006455 return CE->getArg(0)->IgnoreParenCasts();
6456 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006457 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00006458}
6459
6460// Warn on anti-patterns as the 'size' argument to strncat.
6461// The correct size argument should look like following:
6462// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
6463void Sema::CheckStrncatArguments(const CallExpr *CE,
6464 IdentifierInfo *FnName) {
6465 // Don't crash if the user has the wrong number of arguments.
6466 if (CE->getNumArgs() < 3)
6467 return;
6468 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
6469 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
6470 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
6471
Nico Weber0e6daef2013-12-26 23:38:39 +00006472 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
6473 CE->getRParenLoc()))
6474 return;
6475
Anna Zaks314cd092012-02-01 19:08:57 +00006476 // Identify common expressions, which are wrongly used as the size argument
6477 // to strncat and may lead to buffer overflows.
6478 unsigned PatternType = 0;
6479 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
6480 // - sizeof(dst)
6481 if (referToTheSameDecl(SizeOfArg, DstArg))
6482 PatternType = 1;
6483 // - sizeof(src)
6484 else if (referToTheSameDecl(SizeOfArg, SrcArg))
6485 PatternType = 2;
6486 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
6487 if (BE->getOpcode() == BO_Sub) {
6488 const Expr *L = BE->getLHS()->IgnoreParenCasts();
6489 const Expr *R = BE->getRHS()->IgnoreParenCasts();
6490 // - sizeof(dst) - strlen(dst)
6491 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
6492 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
6493 PatternType = 1;
6494 // - sizeof(src) - (anything)
6495 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
6496 PatternType = 2;
6497 }
6498 }
6499
6500 if (PatternType == 0)
6501 return;
6502
Anna Zaks5069aa32012-02-03 01:27:37 +00006503 // Generate the diagnostic.
6504 SourceLocation SL = LenArg->getLocStart();
6505 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00006506 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00006507
6508 // If the function is defined as a builtin macro, do not show macro expansion.
6509 if (SM.isMacroArgExpansion(SL)) {
6510 SL = SM.getSpellingLoc(SL);
6511 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
6512 SM.getSpellingLoc(SR.getEnd()));
6513 }
6514
Anna Zaks13b08572012-08-08 21:42:23 +00006515 // Check if the destination is an array (rather than a pointer to an array).
6516 QualType DstTy = DstArg->getType();
6517 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
6518 Context);
6519 if (!isKnownSizeArray) {
6520 if (PatternType == 1)
6521 Diag(SL, diag::warn_strncat_wrong_size) << SR;
6522 else
6523 Diag(SL, diag::warn_strncat_src_size) << SR;
6524 return;
6525 }
6526
Anna Zaks314cd092012-02-01 19:08:57 +00006527 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00006528 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00006529 else
Anna Zaks5069aa32012-02-03 01:27:37 +00006530 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00006531
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00006532 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00006533 llvm::raw_svector_ostream OS(sizeString);
6534 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00006535 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00006536 OS << ") - ";
6537 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00006538 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00006539 OS << ") - 1";
6540
Anna Zaks5069aa32012-02-03 01:27:37 +00006541 Diag(SL, diag::note_strncat_wrong_size)
6542 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00006543}
6544
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006545//===--- CHECK: Return Address of Stack Variable --------------------------===//
6546
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006547static const Expr *EvalVal(const Expr *E,
6548 SmallVectorImpl<const DeclRefExpr *> &refVars,
6549 const Decl *ParentDecl);
6550static const Expr *EvalAddr(const Expr *E,
6551 SmallVectorImpl<const DeclRefExpr *> &refVars,
6552 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006553
6554/// CheckReturnStackAddr - Check if a return statement returns the address
6555/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006556static void
6557CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
6558 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00006559
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006560 const Expr *stackE = nullptr;
6561 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006562
6563 // Perform checking for returned stack addresses, local blocks,
6564 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00006565 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006566 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006567 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00006568 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006569 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006570 }
6571
Craig Topperc3ec1492014-05-26 06:22:03 +00006572 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006573 return; // Nothing suspicious was found.
6574
Richard Trieu81b6c562016-08-05 23:24:47 +00006575 // Parameters are initalized in the calling scope, so taking the address
6576 // of a parameter reference doesn't need a warning.
6577 for (auto *DRE : refVars)
6578 if (isa<ParmVarDecl>(DRE->getDecl()))
6579 return;
6580
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006581 SourceLocation diagLoc;
6582 SourceRange diagRange;
6583 if (refVars.empty()) {
6584 diagLoc = stackE->getLocStart();
6585 diagRange = stackE->getSourceRange();
6586 } else {
6587 // We followed through a reference variable. 'stackE' contains the
6588 // problematic expression but we will warn at the return statement pointing
6589 // at the reference variable. We will later display the "trail" of
6590 // reference variables using notes.
6591 diagLoc = refVars[0]->getLocStart();
6592 diagRange = refVars[0]->getSourceRange();
6593 }
6594
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006595 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
6596 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00006597 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006598 << DR->getDecl()->getDeclName() << diagRange;
6599 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006600 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006601 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006602 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006603 } else { // local temporary.
Richard Trieu81b6c562016-08-05 23:24:47 +00006604 // If there is an LValue->RValue conversion, then the value of the
6605 // reference type is used, not the reference.
6606 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
6607 if (ICE->getCastKind() == CK_LValueToRValue) {
6608 return;
6609 }
6610 }
Craig Topperda7b27f2015-11-17 05:40:09 +00006611 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
6612 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006613 }
6614
6615 // Display the "trail" of reference variables that we followed until we
6616 // found the problematic expression using notes.
6617 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006618 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006619 // If this var binds to another reference var, show the range of the next
6620 // var, otherwise the var binds to the problematic expression, in which case
6621 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006622 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
6623 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006624 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
6625 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006626 }
6627}
6628
6629/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
6630/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006631/// to a location on the stack, a local block, an address of a label, or a
6632/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006633/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006634/// encounter a subexpression that (1) clearly does not lead to one of the
6635/// above problematic expressions (2) is something we cannot determine leads to
6636/// a problematic expression based on such local checking.
6637///
6638/// Both EvalAddr and EvalVal follow through reference variables to evaluate
6639/// the expression that they point to. Such variables are added to the
6640/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006641///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00006642/// EvalAddr processes expressions that are pointers that are used as
6643/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006644/// At the base case of the recursion is a check for the above problematic
6645/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006646///
6647/// This implementation handles:
6648///
6649/// * pointer-to-pointer casts
6650/// * implicit conversions from array references to pointers
6651/// * taking the address of fields
6652/// * arbitrary interplay between "&" and "*" operators
6653/// * pointer arithmetic from an address of a stack variable
6654/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006655static const Expr *EvalAddr(const Expr *E,
6656 SmallVectorImpl<const DeclRefExpr *> &refVars,
6657 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006658 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00006659 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006660
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006661 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00006662 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00006663 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006664 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00006665 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00006666
Peter Collingbourne91147592011-04-15 00:35:48 +00006667 E = E->IgnoreParens();
6668
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006669 // Our "symbolic interpreter" is just a dispatch off the currently
6670 // viewed AST node. We then recursively traverse the AST by calling
6671 // EvalAddr and EvalVal appropriately.
6672 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006673 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006674 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006675
Richard Smith40f08eb2014-01-30 22:05:38 +00006676 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00006677 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00006678 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00006679
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006680 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006681 // If this is a reference variable, follow through to the expression that
6682 // it points to.
6683 if (V->hasLocalStorage() &&
6684 V->getType()->isReferenceType() && V->hasInit()) {
6685 // Add the reference variable to the "trail".
6686 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006687 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006688 }
6689
Craig Topperc3ec1492014-05-26 06:22:03 +00006690 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006691 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006692
Chris Lattner934edb22007-12-28 05:31:15 +00006693 case Stmt::UnaryOperatorClass: {
6694 // The only unary operator that make sense to handle here
6695 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006696 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006697
John McCalle3027922010-08-25 11:45:40 +00006698 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006699 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006700 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006701 }
Mike Stump11289f42009-09-09 15:08:12 +00006702
Chris Lattner934edb22007-12-28 05:31:15 +00006703 case Stmt::BinaryOperatorClass: {
6704 // Handle pointer arithmetic. All other binary operators are not valid
6705 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006706 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00006707 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00006708
John McCalle3027922010-08-25 11:45:40 +00006709 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00006710 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006711
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006712 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00006713
6714 // Determine which argument is the real pointer base. It could be
6715 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006716 if (!Base->getType()->isPointerType())
6717 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00006718
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006719 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006720 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00006721 }
Steve Naroff2752a172008-09-10 19:17:48 +00006722
Chris Lattner934edb22007-12-28 05:31:15 +00006723 // For conditional operators we need to see if either the LHS or RHS are
6724 // valid DeclRefExpr*s. If one of them is valid, we return it.
6725 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006726 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006727
Chris Lattner934edb22007-12-28 05:31:15 +00006728 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006729 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006730 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006731 // In C++, we can have a throw-expression, which has 'void' type.
6732 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006733 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006734 return LHS;
6735 }
Chris Lattner934edb22007-12-28 05:31:15 +00006736
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006737 // In C++, we can have a throw-expression, which has 'void' type.
6738 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00006739 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006740
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006741 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00006742 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006743
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006744 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00006745 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006746 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00006747 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006748
6749 case Stmt::AddrLabelExprClass:
6750 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00006751
John McCall28fc7092011-11-10 05:35:25 +00006752 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006753 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
6754 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00006755
Ted Kremenekc3b4c522008-08-07 00:49:01 +00006756 // For casts, we need to handle conversions from arrays to
6757 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00006758 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00006759 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00006760 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00006761 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00006762 case Stmt::CXXStaticCastExprClass:
6763 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00006764 case Stmt::CXXConstCastExprClass:
6765 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006766 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00006767 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00006768 case CK_LValueToRValue:
6769 case CK_NoOp:
6770 case CK_BaseToDerived:
6771 case CK_DerivedToBase:
6772 case CK_UncheckedDerivedToBase:
6773 case CK_Dynamic:
6774 case CK_CPointerToObjCPointerCast:
6775 case CK_BlockPointerToObjCPointerCast:
6776 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006777 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00006778
6779 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006780 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00006781
Richard Trieudadefde2014-07-02 04:39:38 +00006782 case CK_BitCast:
6783 if (SubExpr->getType()->isAnyPointerType() ||
6784 SubExpr->getType()->isBlockPointerType() ||
6785 SubExpr->getType()->isObjCQualifiedIdType())
6786 return EvalAddr(SubExpr, refVars, ParentDecl);
6787 else
6788 return nullptr;
6789
Eli Friedman8195ad72012-02-23 23:04:32 +00006790 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00006791 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00006792 }
Chris Lattner934edb22007-12-28 05:31:15 +00006793 }
Mike Stump11289f42009-09-09 15:08:12 +00006794
Douglas Gregorfe314812011-06-21 17:03:29 +00006795 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006796 if (const Expr *Result =
6797 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
6798 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00006799 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00006800 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006801
Chris Lattner934edb22007-12-28 05:31:15 +00006802 // Everything else: we simply don't reason about them.
6803 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00006804 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00006805 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006806}
Mike Stump11289f42009-09-09 15:08:12 +00006807
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006808/// EvalVal - This function is complements EvalAddr in the mutual recursion.
6809/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006810static const Expr *EvalVal(const Expr *E,
6811 SmallVectorImpl<const DeclRefExpr *> &refVars,
6812 const Decl *ParentDecl) {
6813 do {
6814 // We should only be called for evaluating non-pointer expressions, or
6815 // expressions with a pointer type that are not used as references but
6816 // instead
6817 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00006818
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006819 // Our "symbolic interpreter" is just a dispatch off the currently
6820 // viewed AST node. We then recursively traverse the AST by calling
6821 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00006822
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006823 E = E->IgnoreParens();
6824 switch (E->getStmtClass()) {
6825 case Stmt::ImplicitCastExprClass: {
6826 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
6827 if (IE->getValueKind() == VK_LValue) {
6828 E = IE->getSubExpr();
6829 continue;
6830 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006831 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006832 }
Richard Smith40f08eb2014-01-30 22:05:38 +00006833
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006834 case Stmt::ExprWithCleanupsClass:
6835 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
6836 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006837
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006838 case Stmt::DeclRefExprClass: {
6839 // When we hit a DeclRefExpr we are looking at code that refers to a
6840 // variable's name. If it's not a reference variable we check if it has
6841 // local storage within the function, and if so, return the expression.
6842 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6843
6844 // If we leave the immediate function, the lifetime isn't about to end.
6845 if (DR->refersToEnclosingVariableOrCapture())
6846 return nullptr;
6847
6848 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
6849 // Check if it refers to itself, e.g. "int& i = i;".
6850 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006851 return DR;
6852
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006853 if (V->hasLocalStorage()) {
6854 if (!V->getType()->isReferenceType())
6855 return DR;
6856
6857 // Reference variable, follow through to the expression that
6858 // it points to.
6859 if (V->hasInit()) {
6860 // Add the reference variable to the "trail".
6861 refVars.push_back(DR);
6862 return EvalVal(V->getInit(), refVars, V);
6863 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006864 }
6865 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006866
6867 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006868 }
Mike Stump11289f42009-09-09 15:08:12 +00006869
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006870 case Stmt::UnaryOperatorClass: {
6871 // The only unary operator that make sense to handle here
6872 // is Deref. All others don't resolve to a "name." This includes
6873 // handling all sorts of rvalues passed to a unary operator.
6874 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006875
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006876 if (U->getOpcode() == UO_Deref)
6877 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00006878
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006879 return nullptr;
6880 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006881
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006882 case Stmt::ArraySubscriptExprClass: {
6883 // Array subscripts are potential references to data on the stack. We
6884 // retrieve the DeclRefExpr* for the array variable if it indeed
6885 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00006886 const auto *ASE = cast<ArraySubscriptExpr>(E);
6887 if (ASE->isTypeDependent())
6888 return nullptr;
6889 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006890 }
Mike Stump11289f42009-09-09 15:08:12 +00006891
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006892 case Stmt::OMPArraySectionExprClass: {
6893 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
6894 ParentDecl);
6895 }
Mike Stump11289f42009-09-09 15:08:12 +00006896
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006897 case Stmt::ConditionalOperatorClass: {
6898 // For conditional operators we need to see if either the LHS or RHS are
6899 // non-NULL Expr's. If one is non-NULL, we return it.
6900 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00006901
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006902 // Handle the GNU extension for missing LHS.
6903 if (const Expr *LHSExpr = C->getLHS()) {
6904 // In C++, we can have a throw-expression, which has 'void' type.
6905 if (!LHSExpr->getType()->isVoidType())
6906 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
6907 return LHS;
6908 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006909
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006910 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006911 if (C->getRHS()->getType()->isVoidType())
6912 return nullptr;
6913
6914 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006915 }
6916
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006917 // Accesses to members are potential references to data on the stack.
6918 case Stmt::MemberExprClass: {
6919 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00006920
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006921 // Check for indirect access. We only want direct field accesses.
6922 if (M->isArrow())
6923 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006924
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006925 // Check whether the member type is itself a reference, in which case
6926 // we're not going to refer to the member, but to what the member refers
6927 // to.
6928 if (M->getMemberDecl()->getType()->isReferenceType())
6929 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006930
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006931 return EvalVal(M->getBase(), refVars, ParentDecl);
6932 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00006933
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006934 case Stmt::MaterializeTemporaryExprClass:
6935 if (const Expr *Result =
6936 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
6937 refVars, ParentDecl))
6938 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006939 return E;
6940
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006941 default:
6942 // Check that we don't return or take the address of a reference to a
6943 // temporary. This is only useful in C++.
6944 if (!E->isTypeDependent() && E->isRValue())
6945 return E;
6946
6947 // Everything else: we simply don't reason about them.
6948 return nullptr;
6949 }
6950 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006951}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006952
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006953void
6954Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
6955 SourceLocation ReturnLoc,
6956 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00006957 const AttrVec *Attrs,
6958 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006959 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
6960
6961 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00006962 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
6963 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00006964 CheckNonNullExpr(*this, RetValExp))
6965 Diag(ReturnLoc, diag::warn_null_ret)
6966 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00006967
6968 // C++11 [basic.stc.dynamic.allocation]p4:
6969 // If an allocation function declared with a non-throwing
6970 // exception-specification fails to allocate storage, it shall return
6971 // a null pointer. Any other allocation function that fails to allocate
6972 // storage shall indicate failure only by throwing an exception [...]
6973 if (FD) {
6974 OverloadedOperatorKind Op = FD->getOverloadedOperator();
6975 if (Op == OO_New || Op == OO_Array_New) {
6976 const FunctionProtoType *Proto
6977 = FD->getType()->castAs<FunctionProtoType>();
6978 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
6979 CheckNonNullExpr(*this, RetValExp))
6980 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
6981 << FD << getLangOpts().CPlusPlus11;
6982 }
6983 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006984}
6985
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006986//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
6987
6988/// Check for comparisons of floating point operands using != and ==.
6989/// Issue a warning if these are no self-comparisons, as they are not likely
6990/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00006991void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00006992 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
6993 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006994
6995 // Special case: check for x == x (which is OK).
6996 // Do not emit warnings for such cases.
6997 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
6998 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
6999 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00007000 return;
Mike Stump11289f42009-09-09 15:08:12 +00007001
Ted Kremenekeda40e22007-11-29 00:59:04 +00007002 // Special case: check for comparisons against literals that can be exactly
7003 // represented by APFloat. In such cases, do not emit a warning. This
7004 // is a heuristic: often comparison against such literals are used to
7005 // detect if a value in a variable has not changed. This clearly can
7006 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00007007 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
7008 if (FLL->isExact())
7009 return;
7010 } else
7011 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
7012 if (FLR->isExact())
7013 return;
Mike Stump11289f42009-09-09 15:08:12 +00007014
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007015 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00007016 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00007017 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00007018 return;
Mike Stump11289f42009-09-09 15:08:12 +00007019
David Blaikie1f4ff152012-07-16 20:47:22 +00007020 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00007021 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00007022 return;
Mike Stump11289f42009-09-09 15:08:12 +00007023
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007024 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00007025 Diag(Loc, diag::warn_floatingpoint_eq)
7026 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007027}
John McCallca01b222010-01-04 23:21:16 +00007028
John McCall70aa5392010-01-06 05:24:50 +00007029//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
7030//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00007031
John McCall70aa5392010-01-06 05:24:50 +00007032namespace {
John McCallca01b222010-01-04 23:21:16 +00007033
John McCall70aa5392010-01-06 05:24:50 +00007034/// Structure recording the 'active' range of an integer-valued
7035/// expression.
7036struct IntRange {
7037 /// The number of bits active in the int.
7038 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00007039
John McCall70aa5392010-01-06 05:24:50 +00007040 /// True if the int is known not to have negative values.
7041 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00007042
John McCall70aa5392010-01-06 05:24:50 +00007043 IntRange(unsigned Width, bool NonNegative)
7044 : Width(Width), NonNegative(NonNegative)
7045 {}
John McCallca01b222010-01-04 23:21:16 +00007046
John McCall817d4af2010-11-10 23:38:19 +00007047 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00007048 static IntRange forBoolType() {
7049 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00007050 }
7051
John McCall817d4af2010-11-10 23:38:19 +00007052 /// Returns the range of an opaque value of the given integral type.
7053 static IntRange forValueOfType(ASTContext &C, QualType T) {
7054 return forValueOfCanonicalType(C,
7055 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00007056 }
7057
John McCall817d4af2010-11-10 23:38:19 +00007058 /// Returns the range of an opaque value of a canonical integral type.
7059 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00007060 assert(T->isCanonicalUnqualified());
7061
7062 if (const VectorType *VT = dyn_cast<VectorType>(T))
7063 T = VT->getElementType().getTypePtr();
7064 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7065 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00007066 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7067 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00007068
David Majnemer6a426652013-06-07 22:07:20 +00007069 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00007070 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00007071 EnumDecl *Enum = ET->getDecl();
7072 if (!Enum->isCompleteDefinition())
7073 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00007074
David Majnemer6a426652013-06-07 22:07:20 +00007075 unsigned NumPositive = Enum->getNumPositiveBits();
7076 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00007077
David Majnemer6a426652013-06-07 22:07:20 +00007078 if (NumNegative == 0)
7079 return IntRange(NumPositive, true/*NonNegative*/);
7080 else
7081 return IntRange(std::max(NumPositive + 1, NumNegative),
7082 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00007083 }
John McCall70aa5392010-01-06 05:24:50 +00007084
7085 const BuiltinType *BT = cast<BuiltinType>(T);
7086 assert(BT->isInteger());
7087
7088 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7089 }
7090
John McCall817d4af2010-11-10 23:38:19 +00007091 /// Returns the "target" range of a canonical integral type, i.e.
7092 /// the range of values expressible in the type.
7093 ///
7094 /// This matches forValueOfCanonicalType except that enums have the
7095 /// full range of their type, not the range of their enumerators.
7096 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
7097 assert(T->isCanonicalUnqualified());
7098
7099 if (const VectorType *VT = dyn_cast<VectorType>(T))
7100 T = VT->getElementType().getTypePtr();
7101 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7102 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00007103 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7104 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00007105 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00007106 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00007107
7108 const BuiltinType *BT = cast<BuiltinType>(T);
7109 assert(BT->isInteger());
7110
7111 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7112 }
7113
7114 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00007115 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00007116 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00007117 L.NonNegative && R.NonNegative);
7118 }
7119
John McCall817d4af2010-11-10 23:38:19 +00007120 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00007121 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00007122 return IntRange(std::min(L.Width, R.Width),
7123 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00007124 }
7125};
7126
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007127IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00007128 if (value.isSigned() && value.isNegative())
7129 return IntRange(value.getMinSignedBits(), false);
7130
7131 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00007132 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00007133
7134 // isNonNegative() just checks the sign bit without considering
7135 // signedness.
7136 return IntRange(value.getActiveBits(), true);
7137}
7138
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007139IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
7140 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00007141 if (result.isInt())
7142 return GetValueRange(C, result.getInt(), MaxWidth);
7143
7144 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00007145 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
7146 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
7147 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
7148 R = IntRange::join(R, El);
7149 }
John McCall70aa5392010-01-06 05:24:50 +00007150 return R;
7151 }
7152
7153 if (result.isComplexInt()) {
7154 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
7155 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
7156 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00007157 }
7158
7159 // This can happen with lossless casts to intptr_t of "based" lvalues.
7160 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00007161 // FIXME: The only reason we need to pass the type in here is to get
7162 // the sign right on this one case. It would be nice if APValue
7163 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007164 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00007165 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00007166}
John McCall70aa5392010-01-06 05:24:50 +00007167
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007168QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00007169 QualType Ty = E->getType();
7170 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
7171 Ty = AtomicRHS->getValueType();
7172 return Ty;
7173}
7174
John McCall70aa5392010-01-06 05:24:50 +00007175/// Pseudo-evaluate the given integer expression, estimating the
7176/// range of values it might take.
7177///
7178/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007179IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00007180 E = E->IgnoreParens();
7181
7182 // Try a full evaluation first.
7183 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00007184 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00007185 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00007186
7187 // I think we only want to look through implicit casts here; if the
7188 // user has an explicit widening cast, we should treat the value as
7189 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007190 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00007191 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00007192 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
7193
Eli Friedmane6d33952013-07-08 20:20:06 +00007194 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00007195
George Burgess IVdf1ed002016-01-13 01:52:39 +00007196 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
7197 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00007198
John McCall70aa5392010-01-06 05:24:50 +00007199 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00007200 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00007201 return OutputTypeRange;
7202
7203 IntRange SubRange
7204 = GetExprRange(C, CE->getSubExpr(),
7205 std::min(MaxWidth, OutputTypeRange.Width));
7206
7207 // Bail out if the subexpr's range is as wide as the cast type.
7208 if (SubRange.Width >= OutputTypeRange.Width)
7209 return OutputTypeRange;
7210
7211 // Otherwise, we take the smaller width, and we're non-negative if
7212 // either the output type or the subexpr is.
7213 return IntRange(SubRange.Width,
7214 SubRange.NonNegative || OutputTypeRange.NonNegative);
7215 }
7216
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007217 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00007218 // If we can fold the condition, just take that operand.
7219 bool CondResult;
7220 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
7221 return GetExprRange(C, CondResult ? CO->getTrueExpr()
7222 : CO->getFalseExpr(),
7223 MaxWidth);
7224
7225 // Otherwise, conservatively merge.
7226 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
7227 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
7228 return IntRange::join(L, R);
7229 }
7230
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007231 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00007232 switch (BO->getOpcode()) {
7233
7234 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00007235 case BO_LAnd:
7236 case BO_LOr:
7237 case BO_LT:
7238 case BO_GT:
7239 case BO_LE:
7240 case BO_GE:
7241 case BO_EQ:
7242 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00007243 return IntRange::forBoolType();
7244
John McCallc3688382011-07-13 06:35:24 +00007245 // The type of the assignments is the type of the LHS, so the RHS
7246 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00007247 case BO_MulAssign:
7248 case BO_DivAssign:
7249 case BO_RemAssign:
7250 case BO_AddAssign:
7251 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00007252 case BO_XorAssign:
7253 case BO_OrAssign:
7254 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00007255 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00007256
John McCallc3688382011-07-13 06:35:24 +00007257 // Simple assignments just pass through the RHS, which will have
7258 // been coerced to the LHS type.
7259 case BO_Assign:
7260 // TODO: bitfields?
7261 return GetExprRange(C, BO->getRHS(), MaxWidth);
7262
John McCall70aa5392010-01-06 05:24:50 +00007263 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00007264 case BO_PtrMemD:
7265 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00007266 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00007267
John McCall2ce81ad2010-01-06 22:07:33 +00007268 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00007269 case BO_And:
7270 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00007271 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
7272 GetExprRange(C, BO->getRHS(), MaxWidth));
7273
John McCall70aa5392010-01-06 05:24:50 +00007274 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00007275 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00007276 // ...except that we want to treat '1 << (blah)' as logically
7277 // positive. It's an important idiom.
7278 if (IntegerLiteral *I
7279 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
7280 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00007281 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00007282 return IntRange(R.Width, /*NonNegative*/ true);
7283 }
7284 }
7285 // fallthrough
7286
John McCalle3027922010-08-25 11:45:40 +00007287 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00007288 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00007289
John McCall2ce81ad2010-01-06 22:07:33 +00007290 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00007291 case BO_Shr:
7292 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00007293 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
7294
7295 // If the shift amount is a positive constant, drop the width by
7296 // that much.
7297 llvm::APSInt shift;
7298 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
7299 shift.isNonNegative()) {
7300 unsigned zext = shift.getZExtValue();
7301 if (zext >= L.Width)
7302 L.Width = (L.NonNegative ? 0 : 1);
7303 else
7304 L.Width -= zext;
7305 }
7306
7307 return L;
7308 }
7309
7310 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00007311 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00007312 return GetExprRange(C, BO->getRHS(), MaxWidth);
7313
John McCall2ce81ad2010-01-06 22:07:33 +00007314 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00007315 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00007316 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00007317 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00007318 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007319
John McCall51431812011-07-14 22:39:48 +00007320 // The width of a division result is mostly determined by the size
7321 // of the LHS.
7322 case BO_Div: {
7323 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00007324 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00007325 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
7326
7327 // If the divisor is constant, use that.
7328 llvm::APSInt divisor;
7329 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
7330 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
7331 if (log2 >= L.Width)
7332 L.Width = (L.NonNegative ? 0 : 1);
7333 else
7334 L.Width = std::min(L.Width - log2, MaxWidth);
7335 return L;
7336 }
7337
7338 // Otherwise, just use the LHS's width.
7339 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
7340 return IntRange(L.Width, L.NonNegative && R.NonNegative);
7341 }
7342
7343 // The result of a remainder can't be larger than the result of
7344 // either side.
7345 case BO_Rem: {
7346 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00007347 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00007348 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
7349 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
7350
7351 IntRange meet = IntRange::meet(L, R);
7352 meet.Width = std::min(meet.Width, MaxWidth);
7353 return meet;
7354 }
7355
7356 // The default behavior is okay for these.
7357 case BO_Mul:
7358 case BO_Add:
7359 case BO_Xor:
7360 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00007361 break;
7362 }
7363
John McCall51431812011-07-14 22:39:48 +00007364 // The default case is to treat the operation as if it were closed
7365 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00007366 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
7367 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
7368 return IntRange::join(L, R);
7369 }
7370
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007371 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00007372 switch (UO->getOpcode()) {
7373 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00007374 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00007375 return IntRange::forBoolType();
7376
7377 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00007378 case UO_Deref:
7379 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00007380 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00007381
7382 default:
7383 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
7384 }
7385 }
7386
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007387 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00007388 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
7389
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007390 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00007391 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00007392 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00007393
Eli Friedmane6d33952013-07-08 20:20:06 +00007394 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00007395}
John McCall263a48b2010-01-04 23:31:57 +00007396
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007397IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00007398 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00007399}
7400
John McCall263a48b2010-01-04 23:31:57 +00007401/// Checks whether the given value, which currently has the given
7402/// source semantics, has the same value when coerced through the
7403/// target semantics.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007404bool IsSameFloatAfterCast(const llvm::APFloat &value,
7405 const llvm::fltSemantics &Src,
7406 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00007407 llvm::APFloat truncated = value;
7408
7409 bool ignored;
7410 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
7411 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
7412
7413 return truncated.bitwiseIsEqual(value);
7414}
7415
7416/// Checks whether the given value, which currently has the given
7417/// source semantics, has the same value when coerced through the
7418/// target semantics.
7419///
7420/// The value might be a vector of floats (or a complex number).
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007421bool IsSameFloatAfterCast(const APValue &value,
7422 const llvm::fltSemantics &Src,
7423 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00007424 if (value.isFloat())
7425 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
7426
7427 if (value.isVector()) {
7428 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
7429 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
7430 return false;
7431 return true;
7432 }
7433
7434 assert(value.isComplexFloat());
7435 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
7436 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
7437}
7438
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007439void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007440
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007441bool IsZero(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00007442 // Suppress cases where we are comparing against an enum constant.
7443 if (const DeclRefExpr *DR =
7444 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
7445 if (isa<EnumConstantDecl>(DR->getDecl()))
7446 return false;
7447
7448 // Suppress cases where the '0' value is expanded from a macro.
7449 if (E->getLocStart().isMacroID())
7450 return false;
7451
John McCallcc7e5bf2010-05-06 08:58:33 +00007452 llvm::APSInt Value;
7453 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
7454}
7455
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007456bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00007457 // Strip off implicit integral promotions.
7458 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00007459 if (ICE->getCastKind() != CK_IntegralCast &&
7460 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00007461 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00007462 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00007463 }
7464
7465 return E->getType()->isEnumeralType();
7466}
7467
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007468void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00007469 // Disable warning in template instantiations.
7470 if (!S.ActiveTemplateInstantiations.empty())
7471 return;
7472
John McCalle3027922010-08-25 11:45:40 +00007473 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00007474 if (E->isValueDependent())
7475 return;
7476
John McCalle3027922010-08-25 11:45:40 +00007477 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007478 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00007479 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00007480 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00007481 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007482 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00007483 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00007484 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00007485 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007486 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00007487 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00007488 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00007489 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007490 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00007491 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00007492 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
7493 }
7494}
7495
Benjamin Kramer7320b992016-06-15 14:20:56 +00007496void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant,
7497 Expr *Other, const llvm::APSInt &Value,
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007498 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00007499 // Disable warning in template instantiations.
7500 if (!S.ActiveTemplateInstantiations.empty())
7501 return;
7502
Richard Trieu0f097742014-04-04 04:13:47 +00007503 // TODO: Investigate using GetExprRange() to get tighter bounds
7504 // on the bit ranges.
7505 QualType OtherT = Other->getType();
David Majnemer7800f1f2015-05-23 01:32:17 +00007506 if (const auto *AT = OtherT->getAs<AtomicType>())
Justin Bogner4f42fc42014-07-21 18:01:53 +00007507 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00007508 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
7509 unsigned OtherWidth = OtherRange.Width;
7510
7511 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
7512
Richard Trieu560910c2012-11-14 22:50:24 +00007513 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00007514 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00007515 return;
7516
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007517 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00007518 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00007519
Richard Trieu0f097742014-04-04 04:13:47 +00007520 // Used for diagnostic printout.
7521 enum {
7522 LiteralConstant = 0,
7523 CXXBoolLiteralTrue,
7524 CXXBoolLiteralFalse
7525 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00007526
Richard Trieu0f097742014-04-04 04:13:47 +00007527 if (!OtherIsBooleanType) {
7528 QualType ConstantT = Constant->getType();
7529 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00007530
Richard Trieu0f097742014-04-04 04:13:47 +00007531 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
7532 return;
7533 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
7534 "comparison with non-integer type");
7535
7536 bool ConstantSigned = ConstantT->isSignedIntegerType();
7537 bool CommonSigned = CommonT->isSignedIntegerType();
7538
7539 bool EqualityOnly = false;
7540
7541 if (CommonSigned) {
7542 // The common type is signed, therefore no signed to unsigned conversion.
7543 if (!OtherRange.NonNegative) {
7544 // Check that the constant is representable in type OtherT.
7545 if (ConstantSigned) {
7546 if (OtherWidth >= Value.getMinSignedBits())
7547 return;
7548 } else { // !ConstantSigned
7549 if (OtherWidth >= Value.getActiveBits() + 1)
7550 return;
7551 }
7552 } else { // !OtherSigned
7553 // Check that the constant is representable in type OtherT.
7554 // Negative values are out of range.
7555 if (ConstantSigned) {
7556 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
7557 return;
7558 } else { // !ConstantSigned
7559 if (OtherWidth >= Value.getActiveBits())
7560 return;
7561 }
Richard Trieu560910c2012-11-14 22:50:24 +00007562 }
Richard Trieu0f097742014-04-04 04:13:47 +00007563 } else { // !CommonSigned
7564 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00007565 if (OtherWidth >= Value.getActiveBits())
7566 return;
Craig Toppercf360162014-06-18 05:13:11 +00007567 } else { // OtherSigned
7568 assert(!ConstantSigned &&
7569 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00007570 // Check to see if the constant is representable in OtherT.
7571 if (OtherWidth > Value.getActiveBits())
7572 return;
7573 // Check to see if the constant is equivalent to a negative value
7574 // cast to CommonT.
7575 if (S.Context.getIntWidth(ConstantT) ==
7576 S.Context.getIntWidth(CommonT) &&
7577 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
7578 return;
7579 // The constant value rests between values that OtherT can represent
7580 // after conversion. Relational comparison still works, but equality
7581 // comparisons will be tautological.
7582 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00007583 }
7584 }
Richard Trieu0f097742014-04-04 04:13:47 +00007585
7586 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
7587
7588 if (op == BO_EQ || op == BO_NE) {
7589 IsTrue = op == BO_NE;
7590 } else if (EqualityOnly) {
7591 return;
7592 } else if (RhsConstant) {
7593 if (op == BO_GT || op == BO_GE)
7594 IsTrue = !PositiveConstant;
7595 else // op == BO_LT || op == BO_LE
7596 IsTrue = PositiveConstant;
7597 } else {
7598 if (op == BO_LT || op == BO_LE)
7599 IsTrue = !PositiveConstant;
7600 else // op == BO_GT || op == BO_GE
7601 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00007602 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007603 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00007604 // Other isKnownToHaveBooleanValue
7605 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
7606 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
7607 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
7608
7609 static const struct LinkedConditions {
7610 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
7611 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
7612 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
7613 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
7614 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
7615 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
7616
7617 } TruthTable = {
7618 // Constant on LHS. | Constant on RHS. |
7619 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
7620 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
7621 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
7622 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
7623 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
7624 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
7625 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
7626 };
7627
7628 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
7629
7630 enum ConstantValue ConstVal = Zero;
7631 if (Value.isUnsigned() || Value.isNonNegative()) {
7632 if (Value == 0) {
7633 LiteralOrBoolConstant =
7634 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
7635 ConstVal = Zero;
7636 } else if (Value == 1) {
7637 LiteralOrBoolConstant =
7638 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
7639 ConstVal = One;
7640 } else {
7641 LiteralOrBoolConstant = LiteralConstant;
7642 ConstVal = GT_One;
7643 }
7644 } else {
7645 ConstVal = LT_Zero;
7646 }
7647
7648 CompareBoolWithConstantResult CmpRes;
7649
7650 switch (op) {
7651 case BO_LT:
7652 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
7653 break;
7654 case BO_GT:
7655 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
7656 break;
7657 case BO_LE:
7658 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
7659 break;
7660 case BO_GE:
7661 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
7662 break;
7663 case BO_EQ:
7664 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
7665 break;
7666 case BO_NE:
7667 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
7668 break;
7669 default:
7670 CmpRes = Unkwn;
7671 break;
7672 }
7673
7674 if (CmpRes == AFals) {
7675 IsTrue = false;
7676 } else if (CmpRes == ATrue) {
7677 IsTrue = true;
7678 } else {
7679 return;
7680 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007681 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00007682
7683 // If this is a comparison to an enum constant, include that
7684 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00007685 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00007686 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
7687 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
7688
7689 SmallString<64> PrettySourceValue;
7690 llvm::raw_svector_ostream OS(PrettySourceValue);
7691 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00007692 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00007693 else
7694 OS << Value;
7695
Richard Trieu0f097742014-04-04 04:13:47 +00007696 S.DiagRuntimeBehavior(
7697 E->getOperatorLoc(), E,
7698 S.PDiag(diag::warn_out_of_range_compare)
7699 << OS.str() << LiteralOrBoolConstant
7700 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
7701 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007702}
7703
John McCallcc7e5bf2010-05-06 08:58:33 +00007704/// Analyze the operands of the given comparison. Implements the
7705/// fallback case from AnalyzeComparison.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007706void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00007707 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
7708 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00007709}
John McCall263a48b2010-01-04 23:31:57 +00007710
John McCallca01b222010-01-04 23:21:16 +00007711/// \brief Implements -Wsign-compare.
7712///
Richard Trieu82402a02011-09-15 21:56:47 +00007713/// \param E the binary operator to check for warnings
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007714void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007715 // The type the comparison is being performed in.
7716 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00007717
7718 // Only analyze comparison operators where both sides have been converted to
7719 // the same type.
7720 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
7721 return AnalyzeImpConvsInComparison(S, E);
7722
7723 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00007724 if (E->isValueDependent())
7725 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007726
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007727 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
7728 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007729
7730 bool IsComparisonConstant = false;
7731
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007732 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007733 // of 'true' or 'false'.
7734 if (T->isIntegralType(S.Context)) {
7735 llvm::APSInt RHSValue;
7736 bool IsRHSIntegralLiteral =
7737 RHS->isIntegerConstantExpr(RHSValue, S.Context);
7738 llvm::APSInt LHSValue;
7739 bool IsLHSIntegralLiteral =
7740 LHS->isIntegerConstantExpr(LHSValue, S.Context);
7741 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
7742 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
7743 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
7744 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
7745 else
7746 IsComparisonConstant =
7747 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007748 } else if (!T->hasUnsignedIntegerRepresentation())
7749 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007750
John McCallcc7e5bf2010-05-06 08:58:33 +00007751 // We don't do anything special if this isn't an unsigned integral
7752 // comparison: we're only interested in integral comparisons, and
7753 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00007754 //
7755 // We also don't care about value-dependent expressions or expressions
7756 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007757 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00007758 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007759
John McCallcc7e5bf2010-05-06 08:58:33 +00007760 // Check to see if one of the (unmodified) operands is of different
7761 // signedness.
7762 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00007763 if (LHS->getType()->hasSignedIntegerRepresentation()) {
7764 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00007765 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00007766 signedOperand = LHS;
7767 unsignedOperand = RHS;
7768 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
7769 signedOperand = RHS;
7770 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00007771 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00007772 CheckTrivialUnsignedComparison(S, E);
7773 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007774 }
7775
John McCallcc7e5bf2010-05-06 08:58:33 +00007776 // Otherwise, calculate the effective range of the signed operand.
7777 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00007778
John McCallcc7e5bf2010-05-06 08:58:33 +00007779 // Go ahead and analyze implicit conversions in the operands. Note
7780 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00007781 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
7782 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00007783
John McCallcc7e5bf2010-05-06 08:58:33 +00007784 // If the signed range is non-negative, -Wsign-compare won't fire,
7785 // but we should still check for comparisons which are always true
7786 // or false.
7787 if (signedRange.NonNegative)
7788 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007789
7790 // For (in)equality comparisons, if the unsigned operand is a
7791 // constant which cannot collide with a overflowed signed operand,
7792 // then reinterpreting the signed operand as unsigned will not
7793 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00007794 if (E->isEqualityOp()) {
7795 unsigned comparisonWidth = S.Context.getIntWidth(T);
7796 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00007797
John McCallcc7e5bf2010-05-06 08:58:33 +00007798 // We should never be unable to prove that the unsigned operand is
7799 // non-negative.
7800 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
7801
7802 if (unsignedRange.Width < comparisonWidth)
7803 return;
7804 }
7805
Douglas Gregorbfb4a212012-05-01 01:53:49 +00007806 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
7807 S.PDiag(diag::warn_mixed_sign_comparison)
7808 << LHS->getType() << RHS->getType()
7809 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00007810}
7811
John McCall1f425642010-11-11 03:21:53 +00007812/// Analyzes an attempt to assign the given value to a bitfield.
7813///
7814/// Returns true if there was something fishy about the attempt.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007815bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
7816 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00007817 assert(Bitfield->isBitField());
7818 if (Bitfield->isInvalidDecl())
7819 return false;
7820
John McCalldeebbcf2010-11-11 05:33:51 +00007821 // White-list bool bitfields.
7822 if (Bitfield->getType()->isBooleanType())
7823 return false;
7824
Douglas Gregor789adec2011-02-04 13:09:01 +00007825 // Ignore value- or type-dependent expressions.
7826 if (Bitfield->getBitWidth()->isValueDependent() ||
7827 Bitfield->getBitWidth()->isTypeDependent() ||
7828 Init->isValueDependent() ||
7829 Init->isTypeDependent())
7830 return false;
7831
John McCall1f425642010-11-11 03:21:53 +00007832 Expr *OriginalInit = Init->IgnoreParenImpCasts();
7833
Richard Smith5fab0c92011-12-28 19:48:30 +00007834 llvm::APSInt Value;
7835 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00007836 return false;
7837
John McCall1f425642010-11-11 03:21:53 +00007838 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00007839 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00007840
Richard Trieu7561ed02016-08-05 02:39:30 +00007841 if (Value.isSigned() && Value.isNegative())
7842 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
7843 if (UO->getOpcode() == UO_Minus)
7844 if (isa<IntegerLiteral>(UO->getSubExpr()))
7845 OriginalWidth = Value.getMinSignedBits();
7846
John McCall1f425642010-11-11 03:21:53 +00007847 if (OriginalWidth <= FieldWidth)
7848 return false;
7849
Eli Friedmanc267a322012-01-26 23:11:39 +00007850 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00007851 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00007852 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00007853
Eli Friedmanc267a322012-01-26 23:11:39 +00007854 // Check whether the stored value is equal to the original value.
7855 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00007856 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00007857 return false;
7858
Eli Friedmanc267a322012-01-26 23:11:39 +00007859 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00007860 // therefore don't strictly fit into a signed bitfield of width 1.
7861 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00007862 return false;
7863
John McCall1f425642010-11-11 03:21:53 +00007864 std::string PrettyValue = Value.toString(10);
7865 std::string PrettyTrunc = TruncatedValue.toString(10);
7866
7867 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
7868 << PrettyValue << PrettyTrunc << OriginalInit->getType()
7869 << Init->getSourceRange();
7870
7871 return true;
7872}
7873
John McCalld2a53122010-11-09 23:24:47 +00007874/// Analyze the given simple or compound assignment for warning-worthy
7875/// operations.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007876void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00007877 // Just recurse on the LHS.
7878 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
7879
7880 // We want to recurse on the RHS as normal unless we're assigning to
7881 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00007882 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007883 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00007884 E->getOperatorLoc())) {
7885 // Recurse, ignoring any implicit conversions on the RHS.
7886 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
7887 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00007888 }
7889 }
7890
7891 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
7892}
7893
John McCall263a48b2010-01-04 23:31:57 +00007894/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007895void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
7896 SourceLocation CContext, unsigned diag,
7897 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00007898 if (pruneControlFlow) {
7899 S.DiagRuntimeBehavior(E->getExprLoc(), E,
7900 S.PDiag(diag)
7901 << SourceType << T << E->getSourceRange()
7902 << SourceRange(CContext));
7903 return;
7904 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00007905 S.Diag(E->getExprLoc(), diag)
7906 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
7907}
7908
Chandler Carruth7f3654f2011-04-05 06:47:57 +00007909/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007910void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
7911 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00007912 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00007913}
7914
Richard Trieube234c32016-04-21 21:04:55 +00007915
7916/// Diagnose an implicit cast from a floating point value to an integer value.
7917void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
7918
7919 SourceLocation CContext) {
7920 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
7921 const bool PruneWarnings = !S.ActiveTemplateInstantiations.empty();
7922
7923 Expr *InnerE = E->IgnoreParenImpCasts();
7924 // We also want to warn on, e.g., "int i = -1.234"
7925 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
7926 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
7927 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
7928
7929 const bool IsLiteral =
7930 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
7931
7932 llvm::APFloat Value(0.0);
7933 bool IsConstant =
7934 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
7935 if (!IsConstant) {
Richard Trieu891f0f12016-04-22 22:14:32 +00007936 return DiagnoseImpCast(S, E, T, CContext,
7937 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +00007938 }
7939
Chandler Carruth016ef402011-04-10 08:36:24 +00007940 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +00007941
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00007942 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
7943 T->hasUnsignedIntegerRepresentation());
Richard Trieube234c32016-04-21 21:04:55 +00007944 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
7945 &isExact) == llvm::APFloat::opOK &&
Richard Trieu891f0f12016-04-22 22:14:32 +00007946 isExact) {
Richard Trieube234c32016-04-21 21:04:55 +00007947 if (IsLiteral) return;
7948 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
7949 PruneWarnings);
7950 }
7951
7952 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +00007953 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +00007954 // Warn on floating point literal to integer.
7955 DiagID = diag::warn_impcast_literal_float_to_integer;
7956 } else if (IntegerValue == 0) {
7957 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
7958 return DiagnoseImpCast(S, E, T, CContext,
7959 diag::warn_impcast_float_integer, PruneWarnings);
7960 }
7961 // Warn on non-zero to zero conversion.
7962 DiagID = diag::warn_impcast_float_to_integer_zero;
7963 } else {
7964 if (IntegerValue.isUnsigned()) {
7965 if (!IntegerValue.isMaxValue()) {
7966 return DiagnoseImpCast(S, E, T, CContext,
7967 diag::warn_impcast_float_integer, PruneWarnings);
7968 }
7969 } else { // IntegerValue.isSigned()
7970 if (!IntegerValue.isMaxSignedValue() &&
7971 !IntegerValue.isMinSignedValue()) {
7972 return DiagnoseImpCast(S, E, T, CContext,
7973 diag::warn_impcast_float_integer, PruneWarnings);
7974 }
7975 }
7976 // Warn on evaluatable floating point expression to integer conversion.
7977 DiagID = diag::warn_impcast_float_to_integer;
7978 }
Chandler Carruth016ef402011-04-10 08:36:24 +00007979
Eli Friedman07185912013-08-29 23:44:43 +00007980 // FIXME: Force the precision of the source value down so we don't print
7981 // digits which are usually useless (we don't really care here if we
7982 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
7983 // would automatically print the shortest representation, but it's a bit
7984 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00007985 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00007986 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
7987 precision = (precision * 59 + 195) / 196;
7988 Value.toString(PrettySourceValue, precision);
7989
David Blaikie9b88cc02012-05-15 17:18:27 +00007990 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +00007991 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +00007992 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00007993 else
David Blaikie9b88cc02012-05-15 17:18:27 +00007994 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00007995
Richard Trieube234c32016-04-21 21:04:55 +00007996 if (PruneWarnings) {
7997 S.DiagRuntimeBehavior(E->getExprLoc(), E,
7998 S.PDiag(DiagID)
7999 << E->getType() << T.getUnqualifiedType()
8000 << PrettySourceValue << PrettyTargetValue
8001 << E->getSourceRange() << SourceRange(CContext));
8002 } else {
8003 S.Diag(E->getExprLoc(), DiagID)
8004 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
8005 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
8006 }
Chandler Carruth016ef402011-04-10 08:36:24 +00008007}
8008
John McCall18a2c2c2010-11-09 22:22:12 +00008009std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
8010 if (!Range.Width) return "0";
8011
8012 llvm::APSInt ValueInRange = Value;
8013 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00008014 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00008015 return ValueInRange.toString(10);
8016}
8017
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008018bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008019 if (!isa<ImplicitCastExpr>(Ex))
8020 return false;
8021
8022 Expr *InnerE = Ex->IgnoreParenImpCasts();
8023 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
8024 const Type *Source =
8025 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
8026 if (Target->isDependentType())
8027 return false;
8028
8029 const BuiltinType *FloatCandidateBT =
8030 dyn_cast<BuiltinType>(ToBool ? Source : Target);
8031 const Type *BoolCandidateType = ToBool ? Target : Source;
8032
8033 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
8034 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
8035}
8036
8037void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
8038 SourceLocation CC) {
8039 unsigned NumArgs = TheCall->getNumArgs();
8040 for (unsigned i = 0; i < NumArgs; ++i) {
8041 Expr *CurrA = TheCall->getArg(i);
8042 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
8043 continue;
8044
8045 bool IsSwapped = ((i > 0) &&
8046 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
8047 IsSwapped |= ((i < (NumArgs - 1)) &&
8048 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
8049 if (IsSwapped) {
8050 // Warn on this floating-point to bool conversion.
8051 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
8052 CurrA->getType(), CC,
8053 diag::warn_impcast_floating_point_to_bool);
8054 }
8055 }
8056}
8057
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008058void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00008059 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
8060 E->getExprLoc()))
8061 return;
8062
Richard Trieu09d6b802016-01-08 23:35:06 +00008063 // Don't warn on functions which have return type nullptr_t.
8064 if (isa<CallExpr>(E))
8065 return;
8066
Richard Trieu5b993502014-10-15 03:42:06 +00008067 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
8068 const Expr::NullPointerConstantKind NullKind =
8069 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
8070 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
8071 return;
8072
8073 // Return if target type is a safe conversion.
8074 if (T->isAnyPointerType() || T->isBlockPointerType() ||
8075 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
8076 return;
8077
8078 SourceLocation Loc = E->getSourceRange().getBegin();
8079
Richard Trieu0a5e1662016-02-13 00:58:53 +00008080 // Venture through the macro stacks to get to the source of macro arguments.
8081 // The new location is a better location than the complete location that was
8082 // passed in.
8083 while (S.SourceMgr.isMacroArgExpansion(Loc))
8084 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
8085
8086 while (S.SourceMgr.isMacroArgExpansion(CC))
8087 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
8088
Richard Trieu5b993502014-10-15 03:42:06 +00008089 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +00008090 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
8091 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
8092 Loc, S.SourceMgr, S.getLangOpts());
8093 if (MacroName == "NULL")
8094 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
Richard Trieu5b993502014-10-15 03:42:06 +00008095 }
8096
8097 // Only warn if the null and context location are in the same macro expansion.
8098 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
8099 return;
8100
8101 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
8102 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
8103 << FixItHint::CreateReplacement(Loc,
8104 S.getFixItZeroLiteralForType(T, Loc));
8105}
8106
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008107void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8108 ObjCArrayLiteral *ArrayLiteral);
8109void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8110 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +00008111
8112/// Check a single element within a collection literal against the
8113/// target element type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008114void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
8115 Expr *Element, unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00008116 // Skip a bitcast to 'id' or qualified 'id'.
8117 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
8118 if (ICE->getCastKind() == CK_BitCast &&
8119 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
8120 Element = ICE->getSubExpr();
8121 }
8122
8123 QualType ElementType = Element->getType();
8124 ExprResult ElementResult(Element);
8125 if (ElementType->getAs<ObjCObjectPointerType>() &&
8126 S.CheckSingleAssignmentConstraints(TargetElementType,
8127 ElementResult,
8128 false, false)
8129 != Sema::Compatible) {
8130 S.Diag(Element->getLocStart(),
8131 diag::warn_objc_collection_literal_element)
8132 << ElementType << ElementKind << TargetElementType
8133 << Element->getSourceRange();
8134 }
8135
8136 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
8137 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
8138 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
8139 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
8140}
8141
8142/// Check an Objective-C array literal being converted to the given
8143/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008144void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8145 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00008146 if (!S.NSArrayDecl)
8147 return;
8148
8149 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8150 if (!TargetObjCPtr)
8151 return;
8152
8153 if (TargetObjCPtr->isUnspecialized() ||
8154 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8155 != S.NSArrayDecl->getCanonicalDecl())
8156 return;
8157
8158 auto TypeArgs = TargetObjCPtr->getTypeArgs();
8159 if (TypeArgs.size() != 1)
8160 return;
8161
8162 QualType TargetElementType = TypeArgs[0];
8163 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
8164 checkObjCCollectionLiteralElement(S, TargetElementType,
8165 ArrayLiteral->getElement(I),
8166 0);
8167 }
8168}
8169
8170/// Check an Objective-C dictionary literal being converted to the given
8171/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008172void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8173 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00008174 if (!S.NSDictionaryDecl)
8175 return;
8176
8177 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8178 if (!TargetObjCPtr)
8179 return;
8180
8181 if (TargetObjCPtr->isUnspecialized() ||
8182 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8183 != S.NSDictionaryDecl->getCanonicalDecl())
8184 return;
8185
8186 auto TypeArgs = TargetObjCPtr->getTypeArgs();
8187 if (TypeArgs.size() != 2)
8188 return;
8189
8190 QualType TargetKeyType = TypeArgs[0];
8191 QualType TargetObjectType = TypeArgs[1];
8192 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
8193 auto Element = DictionaryLiteral->getKeyValueElement(I);
8194 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
8195 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
8196 }
8197}
8198
Richard Trieufc404c72016-02-05 23:02:38 +00008199// Helper function to filter out cases for constant width constant conversion.
8200// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008201bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
8202 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +00008203 // If initializing from a constant, and the constant starts with '0',
8204 // then it is a binary, octal, or hexadecimal. Allow these constants
8205 // to fill all the bits, even if there is a sign change.
8206 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
8207 const char FirstLiteralCharacter =
8208 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
8209 if (FirstLiteralCharacter == '0')
8210 return false;
8211 }
8212
8213 // If the CC location points to a '{', and the type is char, then assume
8214 // assume it is an array initialization.
8215 if (CC.isValid() && T->isCharType()) {
8216 const char FirstContextCharacter =
8217 S.getSourceManager().getCharacterData(CC)[0];
8218 if (FirstContextCharacter == '{')
8219 return false;
8220 }
8221
8222 return true;
8223}
8224
John McCallcc7e5bf2010-05-06 08:58:33 +00008225void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00008226 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008227 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00008228
John McCallcc7e5bf2010-05-06 08:58:33 +00008229 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
8230 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
8231 if (Source == Target) return;
8232 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00008233
Chandler Carruthc22845a2011-07-26 05:40:03 +00008234 // If the conversion context location is invalid don't complain. We also
8235 // don't want to emit a warning if the issue occurs from the expansion of
8236 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
8237 // delay this check as long as possible. Once we detect we are in that
8238 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008239 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00008240 return;
8241
Richard Trieu021baa32011-09-23 20:10:00 +00008242 // Diagnose implicit casts to bool.
8243 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
8244 if (isa<StringLiteral>(E))
8245 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00008246 // and expressions, for instance, assert(0 && "error here"), are
8247 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00008248 return DiagnoseImpCast(S, E, T, CC,
8249 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00008250 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
8251 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
8252 // This covers the literal expressions that evaluate to Objective-C
8253 // objects.
8254 return DiagnoseImpCast(S, E, T, CC,
8255 diag::warn_impcast_objective_c_literal_to_bool);
8256 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00008257 if (Source->isPointerType() || Source->canDecayToPointerType()) {
8258 // Warn on pointer to bool conversion that is always true.
8259 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
8260 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00008261 }
Richard Trieu021baa32011-09-23 20:10:00 +00008262 }
John McCall263a48b2010-01-04 23:31:57 +00008263
Douglas Gregor5054cb02015-07-07 03:58:22 +00008264 // Check implicit casts from Objective-C collection literals to specialized
8265 // collection types, e.g., NSArray<NSString *> *.
8266 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
8267 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
8268 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
8269 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
8270
John McCall263a48b2010-01-04 23:31:57 +00008271 // Strip vector types.
8272 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008273 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008274 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008275 return;
John McCallacf0ee52010-10-08 02:01:28 +00008276 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008277 }
Chris Lattneree7286f2011-06-14 04:51:15 +00008278
8279 // If the vector cast is cast between two vectors of the same size, it is
8280 // a bitcast, not a conversion.
8281 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
8282 return;
John McCall263a48b2010-01-04 23:31:57 +00008283
8284 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
8285 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
8286 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00008287 if (auto VecTy = dyn_cast<VectorType>(Target))
8288 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00008289
8290 // Strip complex types.
8291 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008292 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008293 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008294 return;
8295
John McCallacf0ee52010-10-08 02:01:28 +00008296 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008297 }
John McCall263a48b2010-01-04 23:31:57 +00008298
8299 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
8300 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
8301 }
8302
8303 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
8304 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
8305
8306 // If the source is floating point...
8307 if (SourceBT && SourceBT->isFloatingPoint()) {
8308 // ...and the target is floating point...
8309 if (TargetBT && TargetBT->isFloatingPoint()) {
8310 // ...then warn if we're dropping FP rank.
8311
8312 // Builtin FP kinds are ordered by increasing FP rank.
8313 if (SourceBT->getKind() > TargetBT->getKind()) {
8314 // Don't warn about float constants that are precisely
8315 // representable in the target type.
8316 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00008317 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00008318 // Value might be a float, a float vector, or a float complex.
8319 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00008320 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
8321 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00008322 return;
8323 }
8324
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008325 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008326 return;
8327
John McCallacf0ee52010-10-08 02:01:28 +00008328 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +00008329 }
8330 // ... or possibly if we're increasing rank, too
8331 else if (TargetBT->getKind() > SourceBT->getKind()) {
8332 if (S.SourceMgr.isInSystemMacro(CC))
8333 return;
8334
8335 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +00008336 }
8337 return;
8338 }
8339
Richard Trieube234c32016-04-21 21:04:55 +00008340 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00008341 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008342 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008343 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00008344
Richard Trieube234c32016-04-21 21:04:55 +00008345 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00008346 }
John McCall263a48b2010-01-04 23:31:57 +00008347
Richard Smith54894fd2015-12-30 01:06:52 +00008348 // Detect the case where a call result is converted from floating-point to
8349 // to bool, and the final argument to the call is converted from bool, to
8350 // discover this typo:
8351 //
8352 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
8353 //
8354 // FIXME: This is an incredibly special case; is there some more general
8355 // way to detect this class of misplaced-parentheses bug?
8356 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008357 // Check last argument of function call to see if it is an
8358 // implicit cast from a type matching the type the result
8359 // is being cast to.
8360 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +00008361 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008362 Expr *LastA = CEx->getArg(NumArgs - 1);
8363 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +00008364 if (isa<ImplicitCastExpr>(LastA) &&
8365 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008366 // Warn on this floating-point to bool conversion
8367 DiagnoseImpCast(S, E, T, CC,
8368 diag::warn_impcast_floating_point_to_bool);
8369 }
8370 }
8371 }
John McCall263a48b2010-01-04 23:31:57 +00008372 return;
8373 }
8374
Richard Trieu5b993502014-10-15 03:42:06 +00008375 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00008376
David Blaikie9366d2b2012-06-19 21:19:06 +00008377 if (!Source->isIntegerType() || !Target->isIntegerType())
8378 return;
8379
David Blaikie7555b6a2012-05-15 16:56:36 +00008380 // TODO: remove this early return once the false positives for constant->bool
8381 // in templates, macros, etc, are reduced or removed.
8382 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
8383 return;
8384
John McCallcc7e5bf2010-05-06 08:58:33 +00008385 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00008386 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00008387
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008388 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00008389 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008390 // TODO: this should happen for bitfield stores, too.
8391 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +00008392 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008393 if (S.SourceMgr.isInSystemMacro(CC))
8394 return;
8395
John McCall18a2c2c2010-11-09 22:22:12 +00008396 std::string PrettySourceValue = Value.toString(10);
8397 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008398
Ted Kremenek33ba9952011-10-22 02:37:33 +00008399 S.DiagRuntimeBehavior(E->getExprLoc(), E,
8400 S.PDiag(diag::warn_impcast_integer_precision_constant)
8401 << PrettySourceValue << PrettyTargetValue
8402 << E->getType() << T << E->getSourceRange()
8403 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00008404 return;
8405 }
8406
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008407 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
8408 if (S.SourceMgr.isInSystemMacro(CC))
8409 return;
8410
David Blaikie9455da02012-04-12 22:40:54 +00008411 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00008412 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
8413 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00008414 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00008415 }
8416
Richard Trieudcb55572016-01-29 23:51:16 +00008417 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
8418 SourceRange.NonNegative && Source->isSignedIntegerType()) {
8419 // Warn when doing a signed to signed conversion, warn if the positive
8420 // source value is exactly the width of the target type, which will
8421 // cause a negative value to be stored.
8422
8423 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +00008424 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
8425 !S.SourceMgr.isInSystemMacro(CC)) {
8426 if (isSameWidthConstantConversion(S, E, T, CC)) {
8427 std::string PrettySourceValue = Value.toString(10);
8428 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +00008429
Richard Trieufc404c72016-02-05 23:02:38 +00008430 S.DiagRuntimeBehavior(
8431 E->getExprLoc(), E,
8432 S.PDiag(diag::warn_impcast_integer_precision_constant)
8433 << PrettySourceValue << PrettyTargetValue << E->getType() << T
8434 << E->getSourceRange() << clang::SourceRange(CC));
8435 return;
Richard Trieudcb55572016-01-29 23:51:16 +00008436 }
8437 }
Richard Trieufc404c72016-02-05 23:02:38 +00008438
Richard Trieudcb55572016-01-29 23:51:16 +00008439 // Fall through for non-constants to give a sign conversion warning.
8440 }
8441
John McCallcc7e5bf2010-05-06 08:58:33 +00008442 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
8443 (!TargetRange.NonNegative && SourceRange.NonNegative &&
8444 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008445 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008446 return;
8447
John McCallcc7e5bf2010-05-06 08:58:33 +00008448 unsigned DiagID = diag::warn_impcast_integer_sign;
8449
8450 // Traditionally, gcc has warned about this under -Wsign-compare.
8451 // We also want to warn about it in -Wconversion.
8452 // So if -Wconversion is off, use a completely identical diagnostic
8453 // in the sign-compare group.
8454 // The conditional-checking code will
8455 if (ICContext) {
8456 DiagID = diag::warn_impcast_integer_sign_conditional;
8457 *ICContext = true;
8458 }
8459
John McCallacf0ee52010-10-08 02:01:28 +00008460 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00008461 }
8462
Douglas Gregora78f1932011-02-22 02:45:07 +00008463 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00008464 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
8465 // type, to give us better diagnostics.
8466 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00008467 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00008468 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8469 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
8470 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
8471 SourceType = S.Context.getTypeDeclType(Enum);
8472 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
8473 }
8474 }
8475
Douglas Gregora78f1932011-02-22 02:45:07 +00008476 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
8477 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00008478 if (SourceEnum->getDecl()->hasNameForLinkage() &&
8479 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008480 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008481 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008482 return;
8483
Douglas Gregor364f7db2011-03-12 00:14:31 +00008484 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00008485 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008486 }
John McCall263a48b2010-01-04 23:31:57 +00008487}
8488
David Blaikie18e9ac72012-05-15 21:57:38 +00008489void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
8490 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00008491
8492void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00008493 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008494 E = E->IgnoreParenImpCasts();
8495
8496 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00008497 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00008498
John McCallacf0ee52010-10-08 02:01:28 +00008499 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008500 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00008501 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00008502}
8503
David Blaikie18e9ac72012-05-15 21:57:38 +00008504void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
8505 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00008506 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00008507
8508 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00008509 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
8510 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00008511
8512 // If -Wconversion would have warned about either of the candidates
8513 // for a signedness conversion to the context type...
8514 if (!Suspicious) return;
8515
8516 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008517 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00008518 return;
8519
John McCallcc7e5bf2010-05-06 08:58:33 +00008520 // ...then check whether it would have warned about either of the
8521 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00008522 if (E->getType() == T) return;
8523
8524 Suspicious = false;
8525 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
8526 E->getType(), CC, &Suspicious);
8527 if (!Suspicious)
8528 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00008529 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00008530}
8531
Richard Trieu65724892014-11-15 06:37:39 +00008532/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
8533/// Input argument E is a logical expression.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008534void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +00008535 if (S.getLangOpts().Bool)
8536 return;
8537 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
8538}
8539
John McCallcc7e5bf2010-05-06 08:58:33 +00008540/// AnalyzeImplicitConversions - Find and report any interesting
8541/// implicit conversions in the given expression. There are a couple
8542/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00008543void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00008544 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00008545 Expr *E = OrigE->IgnoreParenImpCasts();
8546
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00008547 if (E->isTypeDependent() || E->isValueDependent())
8548 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00008549
John McCallcc7e5bf2010-05-06 08:58:33 +00008550 // For conditional operators, we analyze the arguments as if they
8551 // were being fed directly into the output.
8552 if (isa<ConditionalOperator>(E)) {
8553 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00008554 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00008555 return;
8556 }
8557
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008558 // Check implicit argument conversions for function calls.
8559 if (CallExpr *Call = dyn_cast<CallExpr>(E))
8560 CheckImplicitArgumentConversions(S, Call, CC);
8561
John McCallcc7e5bf2010-05-06 08:58:33 +00008562 // Go ahead and check any implicit conversions we might have skipped.
8563 // The non-canonical typecheck is just an optimization;
8564 // CheckImplicitConversion will filter out dead implicit conversions.
8565 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00008566 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008567
8568 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +00008569
8570 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
8571 // The bound subexpressions in a PseudoObjectExpr are not reachable
8572 // as transitive children.
8573 // FIXME: Use a more uniform representation for this.
8574 for (auto *SE : POE->semantics())
8575 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
8576 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00008577 }
Richard Smithd7bed4d2015-11-22 02:57:17 +00008578
John McCallcc7e5bf2010-05-06 08:58:33 +00008579 // Skip past explicit casts.
8580 if (isa<ExplicitCastExpr>(E)) {
8581 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00008582 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008583 }
8584
John McCalld2a53122010-11-09 23:24:47 +00008585 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8586 // Do a somewhat different check with comparison operators.
8587 if (BO->isComparisonOp())
8588 return AnalyzeComparison(S, BO);
8589
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008590 // And with simple assignments.
8591 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00008592 return AnalyzeAssignment(S, BO);
8593 }
John McCallcc7e5bf2010-05-06 08:58:33 +00008594
8595 // These break the otherwise-useful invariant below. Fortunately,
8596 // we don't really need to recurse into them, because any internal
8597 // expressions should have been analyzed already when they were
8598 // built into statements.
8599 if (isa<StmtExpr>(E)) return;
8600
8601 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00008602 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00008603
8604 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00008605 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00008606 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00008607 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +00008608 for (Stmt *SubStmt : E->children()) {
8609 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00008610 if (!ChildExpr)
8611 continue;
8612
Richard Trieu955231d2014-01-25 01:10:35 +00008613 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00008614 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00008615 // Ignore checking string literals that are in logical and operators.
8616 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00008617 continue;
8618 AnalyzeImplicitConversions(S, ChildExpr, CC);
8619 }
Richard Trieu791b86e2014-11-19 06:08:18 +00008620
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00008621 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00008622 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
8623 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00008624 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00008625
8626 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
8627 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00008628 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00008629 }
Richard Trieu791b86e2014-11-19 06:08:18 +00008630
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00008631 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
8632 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00008633 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008634}
8635
8636} // end anonymous namespace
8637
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00008638static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
8639 unsigned Start, unsigned End) {
8640 bool IllegalParams = false;
8641 for (unsigned I = Start; I <= End; ++I) {
8642 QualType Ty = TheCall->getArg(I)->getType();
8643 // Taking into account implicit conversions,
8644 // allow any integer within 32 bits range
8645 if (!Ty->isIntegerType() ||
8646 S.Context.getTypeSizeInChars(Ty).getQuantity() > 4) {
8647 S.Diag(TheCall->getArg(I)->getLocStart(),
8648 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
8649 IllegalParams = true;
8650 }
8651 // Potentially emit standard warnings for implicit conversions if enabled
8652 // using -Wconversion.
8653 CheckImplicitConversion(S, TheCall->getArg(I), S.Context.UnsignedIntTy,
8654 TheCall->getArg(I)->getLocStart());
8655 }
8656 return IllegalParams;
8657}
8658
Richard Trieuc1888e02014-06-28 23:25:37 +00008659// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
8660// Returns true when emitting a warning about taking the address of a reference.
8661static bool CheckForReference(Sema &SemaRef, const Expr *E,
Benjamin Kramer7320b992016-06-15 14:20:56 +00008662 const PartialDiagnostic &PD) {
Richard Trieuc1888e02014-06-28 23:25:37 +00008663 E = E->IgnoreParenImpCasts();
8664
8665 const FunctionDecl *FD = nullptr;
8666
8667 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8668 if (!DRE->getDecl()->getType()->isReferenceType())
8669 return false;
8670 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
8671 if (!M->getMemberDecl()->getType()->isReferenceType())
8672 return false;
8673 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00008674 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00008675 return false;
8676 FD = Call->getDirectCallee();
8677 } else {
8678 return false;
8679 }
8680
8681 SemaRef.Diag(E->getExprLoc(), PD);
8682
8683 // If possible, point to location of function.
8684 if (FD) {
8685 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
8686 }
8687
8688 return true;
8689}
8690
Richard Trieu4cbff5c2014-08-08 22:41:43 +00008691// Returns true if the SourceLocation is expanded from any macro body.
8692// Returns false if the SourceLocation is invalid, is from not in a macro
8693// expansion, or is from expanded from a top-level macro argument.
8694static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
8695 if (Loc.isInvalid())
8696 return false;
8697
8698 while (Loc.isMacroID()) {
8699 if (SM.isMacroBodyExpansion(Loc))
8700 return true;
8701 Loc = SM.getImmediateMacroCallerLoc(Loc);
8702 }
8703
8704 return false;
8705}
8706
Richard Trieu3bb8b562014-02-26 02:36:06 +00008707/// \brief Diagnose pointers that are always non-null.
8708/// \param E the expression containing the pointer
8709/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
8710/// compared to a null pointer
8711/// \param IsEqual True when the comparison is equal to a null pointer
8712/// \param Range Extra SourceRange to highlight in the diagnostic
8713void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
8714 Expr::NullPointerConstantKind NullKind,
8715 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00008716 if (!E)
8717 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008718
8719 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00008720 if (E->getExprLoc().isMacroID()) {
8721 const SourceManager &SM = getSourceManager();
8722 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
8723 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00008724 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00008725 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00008726 E = E->IgnoreImpCasts();
8727
8728 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
8729
Richard Trieuf7432752014-06-06 21:39:26 +00008730 if (isa<CXXThisExpr>(E)) {
8731 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
8732 : diag::warn_this_bool_conversion;
8733 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
8734 return;
8735 }
8736
Richard Trieu3bb8b562014-02-26 02:36:06 +00008737 bool IsAddressOf = false;
8738
8739 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
8740 if (UO->getOpcode() != UO_AddrOf)
8741 return;
8742 IsAddressOf = true;
8743 E = UO->getSubExpr();
8744 }
8745
Richard Trieuc1888e02014-06-28 23:25:37 +00008746 if (IsAddressOf) {
8747 unsigned DiagID = IsCompare
8748 ? diag::warn_address_of_reference_null_compare
8749 : diag::warn_address_of_reference_bool_conversion;
8750 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
8751 << IsEqual;
8752 if (CheckForReference(*this, E, PD)) {
8753 return;
8754 }
8755 }
8756
Nick Lewyckybc85ec82016-06-15 05:18:39 +00008757 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
8758 bool IsParam = isa<NonNullAttr>(NonnullAttr);
George Burgess IV850269a2015-12-08 22:02:00 +00008759 std::string Str;
8760 llvm::raw_string_ostream S(Str);
8761 E->printPretty(S, nullptr, getPrintingPolicy());
8762 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
8763 : diag::warn_cast_nonnull_to_bool;
8764 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
8765 << E->getSourceRange() << Range << IsEqual;
Nick Lewyckybc85ec82016-06-15 05:18:39 +00008766 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
George Burgess IV850269a2015-12-08 22:02:00 +00008767 };
8768
8769 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
8770 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
8771 if (auto *Callee = Call->getDirectCallee()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00008772 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
8773 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00008774 return;
8775 }
8776 }
8777 }
8778
Richard Trieu3bb8b562014-02-26 02:36:06 +00008779 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00008780 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008781 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
8782 D = R->getDecl();
8783 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
8784 D = M->getMemberDecl();
8785 }
8786
8787 // Weak Decls can be null.
8788 if (!D || D->isWeak())
8789 return;
George Burgess IV850269a2015-12-08 22:02:00 +00008790
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008791 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +00008792 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
8793 if (getCurFunction() &&
8794 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00008795 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
8796 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00008797 return;
8798 }
8799
8800 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
David Majnemera3debed2016-06-24 05:33:44 +00008801 auto ParamIter = llvm::find(FD->parameters(), PV);
George Burgess IV850269a2015-12-08 22:02:00 +00008802 assert(ParamIter != FD->param_end());
8803 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
8804
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008805 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
8806 if (!NonNull->args_size()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00008807 ComplainAboutNonnullParamOrCall(NonNull);
George Burgess IV850269a2015-12-08 22:02:00 +00008808 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008809 }
George Burgess IV850269a2015-12-08 22:02:00 +00008810
8811 for (unsigned ArgNo : NonNull->args()) {
8812 if (ArgNo == ParamNo) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00008813 ComplainAboutNonnullParamOrCall(NonNull);
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008814 return;
8815 }
George Burgess IV850269a2015-12-08 22:02:00 +00008816 }
8817 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008818 }
8819 }
George Burgess IV850269a2015-12-08 22:02:00 +00008820 }
8821
Richard Trieu3bb8b562014-02-26 02:36:06 +00008822 QualType T = D->getType();
8823 const bool IsArray = T->isArrayType();
8824 const bool IsFunction = T->isFunctionType();
8825
Richard Trieuc1888e02014-06-28 23:25:37 +00008826 // Address of function is used to silence the function warning.
8827 if (IsAddressOf && IsFunction) {
8828 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008829 }
8830
8831 // Found nothing.
8832 if (!IsAddressOf && !IsFunction && !IsArray)
8833 return;
8834
8835 // Pretty print the expression for the diagnostic.
8836 std::string Str;
8837 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00008838 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00008839
8840 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
8841 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +00008842 enum {
8843 AddressOf,
8844 FunctionPointer,
8845 ArrayPointer
8846 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008847 if (IsAddressOf)
8848 DiagType = AddressOf;
8849 else if (IsFunction)
8850 DiagType = FunctionPointer;
8851 else if (IsArray)
8852 DiagType = ArrayPointer;
8853 else
8854 llvm_unreachable("Could not determine diagnostic.");
8855 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
8856 << Range << IsEqual;
8857
8858 if (!IsFunction)
8859 return;
8860
8861 // Suggest '&' to silence the function warning.
8862 Diag(E->getExprLoc(), diag::note_function_warning_silence)
8863 << FixItHint::CreateInsertion(E->getLocStart(), "&");
8864
8865 // Check to see if '()' fixit should be emitted.
8866 QualType ReturnType;
8867 UnresolvedSet<4> NonTemplateOverloads;
8868 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
8869 if (ReturnType.isNull())
8870 return;
8871
8872 if (IsCompare) {
8873 // There are two cases here. If there is null constant, the only suggest
8874 // for a pointer return type. If the null is 0, then suggest if the return
8875 // type is a pointer or an integer type.
8876 if (!ReturnType->isPointerType()) {
8877 if (NullKind == Expr::NPCK_ZeroExpression ||
8878 NullKind == Expr::NPCK_ZeroLiteral) {
8879 if (!ReturnType->isIntegerType())
8880 return;
8881 } else {
8882 return;
8883 }
8884 }
8885 } else { // !IsCompare
8886 // For function to bool, only suggest if the function pointer has bool
8887 // return type.
8888 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
8889 return;
8890 }
8891 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00008892 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00008893}
8894
John McCallcc7e5bf2010-05-06 08:58:33 +00008895/// Diagnoses "dangerous" implicit conversions within the given
8896/// expression (which is a full expression). Implements -Wconversion
8897/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00008898///
8899/// \param CC the "context" location of the implicit conversion, i.e.
8900/// the most location of the syntactic entity requiring the implicit
8901/// conversion
8902void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008903 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00008904 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00008905 return;
8906
8907 // Don't diagnose for value- or type-dependent expressions.
8908 if (E->isTypeDependent() || E->isValueDependent())
8909 return;
8910
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008911 // Check for array bounds violations in cases where the check isn't triggered
8912 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
8913 // ArraySubscriptExpr is on the RHS of a variable initialization.
8914 CheckArrayAccess(E);
8915
John McCallacf0ee52010-10-08 02:01:28 +00008916 // This is not the right CC for (e.g.) a variable initialization.
8917 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008918}
8919
Richard Trieu65724892014-11-15 06:37:39 +00008920/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
8921/// Input argument E is a logical expression.
8922void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
8923 ::CheckBoolLikeConversion(*this, E, CC);
8924}
8925
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008926/// Diagnose when expression is an integer constant expression and its evaluation
8927/// results in integer overflow
8928void Sema::CheckForIntOverflow (Expr *E) {
Akira Hatanakadfe2156f2016-02-10 06:06:06 +00008929 // Use a work list to deal with nested struct initializers.
8930 SmallVector<Expr *, 2> Exprs(1, E);
8931
8932 do {
8933 Expr *E = Exprs.pop_back_val();
8934
8935 if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
8936 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
8937 continue;
8938 }
8939
8940 if (auto InitList = dyn_cast<InitListExpr>(E))
8941 Exprs.append(InitList->inits().begin(), InitList->inits().end());
8942 } while (!Exprs.empty());
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008943}
8944
Richard Smithc406cb72013-01-17 01:17:56 +00008945namespace {
8946/// \brief Visitor for expressions which looks for unsequenced operations on the
8947/// same object.
8948class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00008949 typedef EvaluatedExprVisitor<SequenceChecker> Base;
8950
Richard Smithc406cb72013-01-17 01:17:56 +00008951 /// \brief A tree of sequenced regions within an expression. Two regions are
8952 /// unsequenced if one is an ancestor or a descendent of the other. When we
8953 /// finish processing an expression with sequencing, such as a comma
8954 /// expression, we fold its tree nodes into its parent, since they are
8955 /// unsequenced with respect to nodes we will visit later.
8956 class SequenceTree {
8957 struct Value {
8958 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
8959 unsigned Parent : 31;
Aaron Ballmanaffa1c32016-07-06 18:33:01 +00008960 unsigned Merged : 1;
Richard Smithc406cb72013-01-17 01:17:56 +00008961 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008962 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00008963
8964 public:
8965 /// \brief A region within an expression which may be sequenced with respect
8966 /// to some other region.
8967 class Seq {
8968 explicit Seq(unsigned N) : Index(N) {}
8969 unsigned Index;
8970 friend class SequenceTree;
8971 public:
8972 Seq() : Index(0) {}
8973 };
8974
8975 SequenceTree() { Values.push_back(Value(0)); }
8976 Seq root() const { return Seq(0); }
8977
8978 /// \brief Create a new sequence of operations, which is an unsequenced
8979 /// subset of \p Parent. This sequence of operations is sequenced with
8980 /// respect to other children of \p Parent.
8981 Seq allocate(Seq Parent) {
8982 Values.push_back(Value(Parent.Index));
8983 return Seq(Values.size() - 1);
8984 }
8985
8986 /// \brief Merge a sequence of operations into its parent.
8987 void merge(Seq S) {
8988 Values[S.Index].Merged = true;
8989 }
8990
8991 /// \brief Determine whether two operations are unsequenced. This operation
8992 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
8993 /// should have been merged into its parent as appropriate.
8994 bool isUnsequenced(Seq Cur, Seq Old) {
8995 unsigned C = representative(Cur.Index);
8996 unsigned Target = representative(Old.Index);
8997 while (C >= Target) {
8998 if (C == Target)
8999 return true;
9000 C = Values[C].Parent;
9001 }
9002 return false;
9003 }
9004
9005 private:
9006 /// \brief Pick a representative for a sequence.
9007 unsigned representative(unsigned K) {
9008 if (Values[K].Merged)
9009 // Perform path compression as we go.
9010 return Values[K].Parent = representative(Values[K].Parent);
9011 return K;
9012 }
9013 };
9014
9015 /// An object for which we can track unsequenced uses.
9016 typedef NamedDecl *Object;
9017
9018 /// Different flavors of object usage which we track. We only track the
9019 /// least-sequenced usage of each kind.
9020 enum UsageKind {
9021 /// A read of an object. Multiple unsequenced reads are OK.
9022 UK_Use,
9023 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00009024 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00009025 UK_ModAsValue,
9026 /// A modification of an object which is not sequenced before the value
9027 /// computation of the expression, such as n++.
9028 UK_ModAsSideEffect,
9029
9030 UK_Count = UK_ModAsSideEffect + 1
9031 };
9032
9033 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00009034 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00009035 Expr *Use;
9036 SequenceTree::Seq Seq;
9037 };
9038
9039 struct UsageInfo {
9040 UsageInfo() : Diagnosed(false) {}
9041 Usage Uses[UK_Count];
9042 /// Have we issued a diagnostic for this variable already?
9043 bool Diagnosed;
9044 };
9045 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
9046
9047 Sema &SemaRef;
9048 /// Sequenced regions within the expression.
9049 SequenceTree Tree;
9050 /// Declaration modifications and references which we have seen.
9051 UsageInfoMap UsageMap;
9052 /// The region we are currently within.
9053 SequenceTree::Seq Region;
9054 /// Filled in with declarations which were modified as a side-effect
9055 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009056 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00009057 /// Expressions to check later. We defer checking these to reduce
9058 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009059 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00009060
9061 /// RAII object wrapping the visitation of a sequenced subexpression of an
9062 /// expression. At the end of this process, the side-effects of the evaluation
9063 /// become sequenced with respect to the value computation of the result, so
9064 /// we downgrade any UK_ModAsSideEffect within the evaluation to
9065 /// UK_ModAsValue.
9066 struct SequencedSubexpression {
9067 SequencedSubexpression(SequenceChecker &Self)
9068 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
9069 Self.ModAsSideEffect = &ModAsSideEffect;
9070 }
9071 ~SequencedSubexpression() {
David Majnemerf7e36092016-06-23 00:15:04 +00009072 for (auto &M : llvm::reverse(ModAsSideEffect)) {
9073 UsageInfo &U = Self.UsageMap[M.first];
Richard Smithe8efd992014-12-03 01:05:50 +00009074 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
David Majnemerf7e36092016-06-23 00:15:04 +00009075 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
9076 SideEffectUsage = M.second;
Richard Smithc406cb72013-01-17 01:17:56 +00009077 }
9078 Self.ModAsSideEffect = OldModAsSideEffect;
9079 }
9080
9081 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009082 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
9083 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00009084 };
9085
Richard Smith40238f02013-06-20 22:21:56 +00009086 /// RAII object wrapping the visitation of a subexpression which we might
9087 /// choose to evaluate as a constant. If any subexpression is evaluated and
9088 /// found to be non-constant, this allows us to suppress the evaluation of
9089 /// the outer expression.
9090 class EvaluationTracker {
9091 public:
9092 EvaluationTracker(SequenceChecker &Self)
9093 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
9094 Self.EvalTracker = this;
9095 }
9096 ~EvaluationTracker() {
9097 Self.EvalTracker = Prev;
9098 if (Prev)
9099 Prev->EvalOK &= EvalOK;
9100 }
9101
9102 bool evaluate(const Expr *E, bool &Result) {
9103 if (!EvalOK || E->isValueDependent())
9104 return false;
9105 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
9106 return EvalOK;
9107 }
9108
9109 private:
9110 SequenceChecker &Self;
9111 EvaluationTracker *Prev;
9112 bool EvalOK;
9113 } *EvalTracker;
9114
Richard Smithc406cb72013-01-17 01:17:56 +00009115 /// \brief Find the object which is produced by the specified expression,
9116 /// if any.
9117 Object getObject(Expr *E, bool Mod) const {
9118 E = E->IgnoreParenCasts();
9119 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9120 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
9121 return getObject(UO->getSubExpr(), Mod);
9122 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9123 if (BO->getOpcode() == BO_Comma)
9124 return getObject(BO->getRHS(), Mod);
9125 if (Mod && BO->isAssignmentOp())
9126 return getObject(BO->getLHS(), Mod);
9127 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9128 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
9129 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
9130 return ME->getMemberDecl();
9131 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9132 // FIXME: If this is a reference, map through to its value.
9133 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00009134 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00009135 }
9136
9137 /// \brief Note that an object was modified or used by an expression.
9138 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
9139 Usage &U = UI.Uses[UK];
9140 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
9141 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
9142 ModAsSideEffect->push_back(std::make_pair(O, U));
9143 U.Use = Ref;
9144 U.Seq = Region;
9145 }
9146 }
9147 /// \brief Check whether a modification or use conflicts with a prior usage.
9148 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
9149 bool IsModMod) {
9150 if (UI.Diagnosed)
9151 return;
9152
9153 const Usage &U = UI.Uses[OtherKind];
9154 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
9155 return;
9156
9157 Expr *Mod = U.Use;
9158 Expr *ModOrUse = Ref;
9159 if (OtherKind == UK_Use)
9160 std::swap(Mod, ModOrUse);
9161
9162 SemaRef.Diag(Mod->getExprLoc(),
9163 IsModMod ? diag::warn_unsequenced_mod_mod
9164 : diag::warn_unsequenced_mod_use)
9165 << O << SourceRange(ModOrUse->getExprLoc());
9166 UI.Diagnosed = true;
9167 }
9168
9169 void notePreUse(Object O, Expr *Use) {
9170 UsageInfo &U = UsageMap[O];
9171 // Uses conflict with other modifications.
9172 checkUsage(O, U, Use, UK_ModAsValue, false);
9173 }
9174 void notePostUse(Object O, Expr *Use) {
9175 UsageInfo &U = UsageMap[O];
9176 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
9177 addUsage(U, O, Use, UK_Use);
9178 }
9179
9180 void notePreMod(Object O, Expr *Mod) {
9181 UsageInfo &U = UsageMap[O];
9182 // Modifications conflict with other modifications and with uses.
9183 checkUsage(O, U, Mod, UK_ModAsValue, true);
9184 checkUsage(O, U, Mod, UK_Use, false);
9185 }
9186 void notePostMod(Object O, Expr *Use, UsageKind UK) {
9187 UsageInfo &U = UsageMap[O];
9188 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
9189 addUsage(U, O, Use, UK);
9190 }
9191
9192public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009193 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00009194 : Base(S.Context), SemaRef(S), Region(Tree.root()),
9195 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00009196 Visit(E);
9197 }
9198
9199 void VisitStmt(Stmt *S) {
9200 // Skip all statements which aren't expressions for now.
9201 }
9202
9203 void VisitExpr(Expr *E) {
9204 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00009205 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00009206 }
9207
9208 void VisitCastExpr(CastExpr *E) {
9209 Object O = Object();
9210 if (E->getCastKind() == CK_LValueToRValue)
9211 O = getObject(E->getSubExpr(), false);
9212
9213 if (O)
9214 notePreUse(O, E);
9215 VisitExpr(E);
9216 if (O)
9217 notePostUse(O, E);
9218 }
9219
9220 void VisitBinComma(BinaryOperator *BO) {
9221 // C++11 [expr.comma]p1:
9222 // Every value computation and side effect associated with the left
9223 // expression is sequenced before every value computation and side
9224 // effect associated with the right expression.
9225 SequenceTree::Seq LHS = Tree.allocate(Region);
9226 SequenceTree::Seq RHS = Tree.allocate(Region);
9227 SequenceTree::Seq OldRegion = Region;
9228
9229 {
9230 SequencedSubexpression SeqLHS(*this);
9231 Region = LHS;
9232 Visit(BO->getLHS());
9233 }
9234
9235 Region = RHS;
9236 Visit(BO->getRHS());
9237
9238 Region = OldRegion;
9239
9240 // Forget that LHS and RHS are sequenced. They are both unsequenced
9241 // with respect to other stuff.
9242 Tree.merge(LHS);
9243 Tree.merge(RHS);
9244 }
9245
9246 void VisitBinAssign(BinaryOperator *BO) {
9247 // The modification is sequenced after the value computation of the LHS
9248 // and RHS, so check it before inspecting the operands and update the
9249 // map afterwards.
9250 Object O = getObject(BO->getLHS(), true);
9251 if (!O)
9252 return VisitExpr(BO);
9253
9254 notePreMod(O, BO);
9255
9256 // C++11 [expr.ass]p7:
9257 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
9258 // only once.
9259 //
9260 // Therefore, for a compound assignment operator, O is considered used
9261 // everywhere except within the evaluation of E1 itself.
9262 if (isa<CompoundAssignOperator>(BO))
9263 notePreUse(O, BO);
9264
9265 Visit(BO->getLHS());
9266
9267 if (isa<CompoundAssignOperator>(BO))
9268 notePostUse(O, BO);
9269
9270 Visit(BO->getRHS());
9271
Richard Smith83e37bee2013-06-26 23:16:51 +00009272 // C++11 [expr.ass]p1:
9273 // the assignment is sequenced [...] before the value computation of the
9274 // assignment expression.
9275 // C11 6.5.16/3 has no such rule.
9276 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
9277 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00009278 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009279
Richard Smithc406cb72013-01-17 01:17:56 +00009280 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
9281 VisitBinAssign(CAO);
9282 }
9283
9284 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
9285 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
9286 void VisitUnaryPreIncDec(UnaryOperator *UO) {
9287 Object O = getObject(UO->getSubExpr(), true);
9288 if (!O)
9289 return VisitExpr(UO);
9290
9291 notePreMod(O, UO);
9292 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00009293 // C++11 [expr.pre.incr]p1:
9294 // the expression ++x is equivalent to x+=1
9295 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
9296 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00009297 }
9298
9299 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
9300 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
9301 void VisitUnaryPostIncDec(UnaryOperator *UO) {
9302 Object O = getObject(UO->getSubExpr(), true);
9303 if (!O)
9304 return VisitExpr(UO);
9305
9306 notePreMod(O, UO);
9307 Visit(UO->getSubExpr());
9308 notePostMod(O, UO, UK_ModAsSideEffect);
9309 }
9310
9311 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
9312 void VisitBinLOr(BinaryOperator *BO) {
9313 // The side-effects of the LHS of an '&&' are sequenced before the
9314 // value computation of the RHS, and hence before the value computation
9315 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
9316 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00009317 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00009318 {
9319 SequencedSubexpression Sequenced(*this);
9320 Visit(BO->getLHS());
9321 }
9322
9323 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00009324 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00009325 if (!Result)
9326 Visit(BO->getRHS());
9327 } else {
9328 // Check for unsequenced operations in the RHS, treating it as an
9329 // entirely separate evaluation.
9330 //
9331 // FIXME: If there are operations in the RHS which are unsequenced
9332 // with respect to operations outside the RHS, and those operations
9333 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00009334 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00009335 }
Richard Smithc406cb72013-01-17 01:17:56 +00009336 }
9337 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00009338 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00009339 {
9340 SequencedSubexpression Sequenced(*this);
9341 Visit(BO->getLHS());
9342 }
9343
9344 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00009345 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00009346 if (Result)
9347 Visit(BO->getRHS());
9348 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00009349 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00009350 }
Richard Smithc406cb72013-01-17 01:17:56 +00009351 }
9352
9353 // Only visit the condition, unless we can be sure which subexpression will
9354 // be chosen.
9355 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00009356 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00009357 {
9358 SequencedSubexpression Sequenced(*this);
9359 Visit(CO->getCond());
9360 }
Richard Smithc406cb72013-01-17 01:17:56 +00009361
9362 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00009363 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00009364 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00009365 else {
Richard Smithd33f5202013-01-17 23:18:09 +00009366 WorkList.push_back(CO->getTrueExpr());
9367 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00009368 }
Richard Smithc406cb72013-01-17 01:17:56 +00009369 }
9370
Richard Smithe3dbfe02013-06-30 10:40:20 +00009371 void VisitCallExpr(CallExpr *CE) {
9372 // C++11 [intro.execution]p15:
9373 // When calling a function [...], every value computation and side effect
9374 // associated with any argument expression, or with the postfix expression
9375 // designating the called function, is sequenced before execution of every
9376 // expression or statement in the body of the function [and thus before
9377 // the value computation of its result].
9378 SequencedSubexpression Sequenced(*this);
9379 Base::VisitCallExpr(CE);
9380
9381 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
9382 }
9383
Richard Smithc406cb72013-01-17 01:17:56 +00009384 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00009385 // This is a call, so all subexpressions are sequenced before the result.
9386 SequencedSubexpression Sequenced(*this);
9387
Richard Smithc406cb72013-01-17 01:17:56 +00009388 if (!CCE->isListInitialization())
9389 return VisitExpr(CCE);
9390
9391 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009392 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00009393 SequenceTree::Seq Parent = Region;
9394 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
9395 E = CCE->arg_end();
9396 I != E; ++I) {
9397 Region = Tree.allocate(Parent);
9398 Elts.push_back(Region);
9399 Visit(*I);
9400 }
9401
9402 // Forget that the initializers are sequenced.
9403 Region = Parent;
9404 for (unsigned I = 0; I < Elts.size(); ++I)
9405 Tree.merge(Elts[I]);
9406 }
9407
9408 void VisitInitListExpr(InitListExpr *ILE) {
9409 if (!SemaRef.getLangOpts().CPlusPlus11)
9410 return VisitExpr(ILE);
9411
9412 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009413 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00009414 SequenceTree::Seq Parent = Region;
9415 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
9416 Expr *E = ILE->getInit(I);
9417 if (!E) continue;
9418 Region = Tree.allocate(Parent);
9419 Elts.push_back(Region);
9420 Visit(E);
9421 }
9422
9423 // Forget that the initializers are sequenced.
9424 Region = Parent;
9425 for (unsigned I = 0; I < Elts.size(); ++I)
9426 Tree.merge(Elts[I]);
9427 }
9428};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009429} // end anonymous namespace
Richard Smithc406cb72013-01-17 01:17:56 +00009430
9431void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009432 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00009433 WorkList.push_back(E);
9434 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00009435 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00009436 SequenceChecker(*this, Item, WorkList);
9437 }
Richard Smithc406cb72013-01-17 01:17:56 +00009438}
9439
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009440void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
9441 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00009442 CheckImplicitConversions(E, CheckLoc);
Richard Trieu71d74d42016-08-05 21:02:34 +00009443 if (!E->isInstantiationDependent())
9444 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009445 if (!IsConstexpr && !E->isValueDependent())
9446 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00009447}
9448
John McCall1f425642010-11-11 03:21:53 +00009449void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
9450 FieldDecl *BitField,
9451 Expr *Init) {
9452 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
9453}
9454
David Majnemer61a5bbf2015-04-07 22:08:51 +00009455static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
9456 SourceLocation Loc) {
9457 if (!PType->isVariablyModifiedType())
9458 return;
9459 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
9460 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
9461 return;
9462 }
David Majnemerdf8f73f2015-04-09 19:53:25 +00009463 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
9464 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
9465 return;
9466 }
David Majnemer61a5bbf2015-04-07 22:08:51 +00009467 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
9468 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
9469 return;
9470 }
9471
9472 const ArrayType *AT = S.Context.getAsArrayType(PType);
9473 if (!AT)
9474 return;
9475
9476 if (AT->getSizeModifier() != ArrayType::Star) {
9477 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
9478 return;
9479 }
9480
9481 S.Diag(Loc, diag::err_array_star_in_function_definition);
9482}
9483
Mike Stump0c2ec772010-01-21 03:59:47 +00009484/// CheckParmsForFunctionDef - Check that the parameters of the given
9485/// function are appropriate for the definition of a function. This
9486/// takes care of any checks that cannot be performed on the
9487/// declaration itself, e.g., that the types of each of the function
9488/// parameters are complete.
David Majnemer59f77922016-06-24 04:05:48 +00009489bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
Douglas Gregorb524d902010-11-01 18:37:59 +00009490 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00009491 bool HasInvalidParm = false;
David Majnemer59f77922016-06-24 04:05:48 +00009492 for (ParmVarDecl *Param : Parameters) {
Mike Stump0c2ec772010-01-21 03:59:47 +00009493 // C99 6.7.5.3p4: the parameters in a parameter type list in a
9494 // function declarator that is part of a function definition of
9495 // that function shall not have incomplete type.
9496 //
9497 // This is also C++ [dcl.fct]p6.
9498 if (!Param->isInvalidDecl() &&
9499 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00009500 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00009501 Param->setInvalidDecl();
9502 HasInvalidParm = true;
9503 }
9504
9505 // C99 6.9.1p5: If the declarator includes a parameter type list, the
9506 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00009507 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00009508 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00009509 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00009510 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00009511 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00009512
9513 // C99 6.7.5.3p12:
9514 // If the function declarator is not part of a definition of that
9515 // function, parameters may have incomplete type and may use the [*]
9516 // notation in their sequences of declarator specifiers to specify
9517 // variable length array types.
9518 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +00009519 // FIXME: This diagnostic should point the '[*]' if source-location
9520 // information is added for it.
9521 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00009522
9523 // MSVC destroys objects passed by value in the callee. Therefore a
9524 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00009525 // object's destructor. However, we don't perform any direct access check
9526 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00009527 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
9528 .getCXXABI()
9529 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00009530 if (!Param->isInvalidDecl()) {
9531 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
9532 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
9533 if (!ClassDecl->isInvalidDecl() &&
9534 !ClassDecl->hasIrrelevantDestructor() &&
9535 !ClassDecl->isDependentContext()) {
9536 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
9537 MarkFunctionReferenced(Param->getLocation(), Destructor);
9538 DiagnoseUseOfDecl(Destructor, Param->getLocation());
9539 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00009540 }
9541 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00009542 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009543
9544 // Parameters with the pass_object_size attribute only need to be marked
9545 // constant at function definitions. Because we lack information about
9546 // whether we're on a declaration or definition when we're instantiating the
9547 // attribute, we need to check for constness here.
9548 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
9549 if (!Param->getType().isConstQualified())
9550 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
9551 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +00009552 }
9553
9554 return HasInvalidParm;
9555}
John McCall2b5c1b22010-08-12 21:44:57 +00009556
9557/// CheckCastAlign - Implements -Wcast-align, which warns when a
9558/// pointer cast increases the alignment requirements.
9559void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
9560 // This is actually a lot of work to potentially be doing on every
9561 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009562 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00009563 return;
9564
9565 // Ignore dependent types.
9566 if (T->isDependentType() || Op->getType()->isDependentType())
9567 return;
9568
9569 // Require that the destination be a pointer type.
9570 const PointerType *DestPtr = T->getAs<PointerType>();
9571 if (!DestPtr) return;
9572
9573 // If the destination has alignment 1, we're done.
9574 QualType DestPointee = DestPtr->getPointeeType();
9575 if (DestPointee->isIncompleteType()) return;
9576 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
9577 if (DestAlign.isOne()) return;
9578
9579 // Require that the source be a pointer type.
9580 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
9581 if (!SrcPtr) return;
9582 QualType SrcPointee = SrcPtr->getPointeeType();
9583
9584 // Whitelist casts from cv void*. We already implicitly
9585 // whitelisted casts to cv void*, since they have alignment 1.
9586 // Also whitelist casts involving incomplete types, which implicitly
9587 // includes 'void'.
9588 if (SrcPointee->isIncompleteType()) return;
9589
9590 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
9591 if (SrcAlign >= DestAlign) return;
9592
9593 Diag(TRange.getBegin(), diag::warn_cast_align)
9594 << Op->getType() << T
9595 << static_cast<unsigned>(SrcAlign.getQuantity())
9596 << static_cast<unsigned>(DestAlign.getQuantity())
9597 << TRange << Op->getSourceRange();
9598}
9599
Chandler Carruth28389f02011-08-05 09:10:50 +00009600/// \brief Check whether this array fits the idiom of a size-one tail padded
9601/// array member of a struct.
9602///
9603/// We avoid emitting out-of-bounds access warnings for such arrays as they are
9604/// commonly used to emulate flexible arrays in C89 code.
Benjamin Kramer7320b992016-06-15 14:20:56 +00009605static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
Chandler Carruth28389f02011-08-05 09:10:50 +00009606 const NamedDecl *ND) {
9607 if (Size != 1 || !ND) return false;
9608
9609 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
9610 if (!FD) return false;
9611
9612 // Don't consider sizes resulting from macro expansions or template argument
9613 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00009614
9615 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00009616 while (TInfo) {
9617 TypeLoc TL = TInfo->getTypeLoc();
9618 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00009619 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
9620 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00009621 TInfo = TDL->getTypeSourceInfo();
9622 continue;
9623 }
David Blaikie6adc78e2013-02-18 22:06:02 +00009624 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
9625 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00009626 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
9627 return false;
9628 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00009629 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00009630 }
Chandler Carruth28389f02011-08-05 09:10:50 +00009631
9632 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00009633 if (!RD) return false;
9634 if (RD->isUnion()) return false;
9635 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
9636 if (!CRD->isStandardLayout()) return false;
9637 }
Chandler Carruth28389f02011-08-05 09:10:50 +00009638
Benjamin Kramer8c543672011-08-06 03:04:42 +00009639 // See if this is the last field decl in the record.
9640 const Decl *D = FD;
9641 while ((D = D->getNextDeclInContext()))
9642 if (isa<FieldDecl>(D))
9643 return false;
9644 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00009645}
9646
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009647void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009648 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00009649 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009650 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009651 if (IndexExpr->isValueDependent())
9652 return;
9653
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009654 const Type *EffectiveType =
9655 BaseExpr->getType()->getPointeeOrArrayElementType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009656 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009657 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009658 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009659 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00009660 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00009661
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009662 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +00009663 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +00009664 return;
Richard Smith13f67182011-12-16 19:31:14 +00009665 if (IndexNegated)
9666 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00009667
Craig Topperc3ec1492014-05-26 06:22:03 +00009668 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00009669 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
9670 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00009671 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00009672 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00009673
Ted Kremeneke4b316c2011-02-23 23:06:04 +00009674 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00009675 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00009676 if (!size.isStrictlyPositive())
9677 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009678
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009679 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
Nico Weber7c299802011-09-17 22:59:41 +00009680 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009681 // Make sure we're comparing apples to apples when comparing index to size
9682 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
9683 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00009684 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00009685 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009686 if (ptrarith_typesize != array_typesize) {
9687 // There's a cast to a different size type involved
9688 uint64_t ratio = array_typesize / ptrarith_typesize;
9689 // TODO: Be smarter about handling cases where array_typesize is not a
9690 // multiple of ptrarith_typesize
9691 if (ptrarith_typesize * ratio == array_typesize)
9692 size *= llvm::APInt(size.getBitWidth(), ratio);
9693 }
9694 }
9695
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009696 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009697 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00009698 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009699 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00009700
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009701 // For array subscripting the index must be less than size, but for pointer
9702 // arithmetic also allow the index (offset) to be equal to size since
9703 // computing the next address after the end of the array is legal and
9704 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009705 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00009706 return;
9707
9708 // Also don't warn for arrays of size 1 which are members of some
9709 // structure. These are often used to approximate flexible arrays in C89
9710 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009711 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00009712 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009713
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009714 // Suppress the warning if the subscript expression (as identified by the
9715 // ']' location) and the index expression are both from macro expansions
9716 // within a system header.
9717 if (ASE) {
9718 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
9719 ASE->getRBracketLoc());
9720 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
9721 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
9722 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00009723 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009724 return;
9725 }
9726 }
9727
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009728 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009729 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009730 DiagID = diag::warn_array_index_exceeds_bounds;
9731
9732 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
9733 PDiag(DiagID) << index.toString(10, true)
9734 << size.toString(10, true)
9735 << (unsigned)size.getLimitedValue(~0U)
9736 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009737 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009738 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009739 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009740 DiagID = diag::warn_ptr_arith_precedes_bounds;
9741 if (index.isNegative()) index = -index;
9742 }
9743
9744 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
9745 PDiag(DiagID) << index.toString(10, true)
9746 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00009747 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00009748
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00009749 if (!ND) {
9750 // Try harder to find a NamedDecl to point at in the note.
9751 while (const ArraySubscriptExpr *ASE =
9752 dyn_cast<ArraySubscriptExpr>(BaseExpr))
9753 BaseExpr = ASE->getBase()->IgnoreParenCasts();
9754 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
9755 ND = dyn_cast<NamedDecl>(DRE->getDecl());
9756 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
9757 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
9758 }
9759
Chandler Carruth1af88f12011-02-17 21:10:52 +00009760 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009761 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
9762 PDiag(diag::note_array_index_out_of_bounds)
9763 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00009764}
9765
Ted Kremenekdf26df72011-03-01 18:41:00 +00009766void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009767 int AllowOnePastEnd = 0;
9768 while (expr) {
9769 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00009770 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009771 case Stmt::ArraySubscriptExprClass: {
9772 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009773 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009774 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00009775 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009776 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +00009777 case Stmt::OMPArraySectionExprClass: {
9778 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
9779 if (ASE->getLowerBound())
9780 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
9781 /*ASE=*/nullptr, AllowOnePastEnd > 0);
9782 return;
9783 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009784 case Stmt::UnaryOperatorClass: {
9785 // Only unwrap the * and & unary operators
9786 const UnaryOperator *UO = cast<UnaryOperator>(expr);
9787 expr = UO->getSubExpr();
9788 switch (UO->getOpcode()) {
9789 case UO_AddrOf:
9790 AllowOnePastEnd++;
9791 break;
9792 case UO_Deref:
9793 AllowOnePastEnd--;
9794 break;
9795 default:
9796 return;
9797 }
9798 break;
9799 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00009800 case Stmt::ConditionalOperatorClass: {
9801 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
9802 if (const Expr *lhs = cond->getLHS())
9803 CheckArrayAccess(lhs);
9804 if (const Expr *rhs = cond->getRHS())
9805 CheckArrayAccess(rhs);
9806 return;
9807 }
9808 default:
9809 return;
9810 }
Peter Collingbourne91147592011-04-15 00:35:48 +00009811 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00009812}
John McCall31168b02011-06-15 23:02:42 +00009813
9814//===--- CHECK: Objective-C retain cycles ----------------------------------//
9815
9816namespace {
9817 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00009818 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00009819 VarDecl *Variable;
9820 SourceRange Range;
9821 SourceLocation Loc;
9822 bool Indirect;
9823
9824 void setLocsFrom(Expr *e) {
9825 Loc = e->getExprLoc();
9826 Range = e->getSourceRange();
9827 }
9828 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009829} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +00009830
9831/// Consider whether capturing the given variable can possibly lead to
9832/// a retain cycle.
9833static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00009834 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00009835 // lifetime. In MRR, it's captured strongly if the variable is
9836 // __block and has an appropriate type.
9837 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
9838 return false;
9839
9840 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009841 if (ref)
9842 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00009843 return true;
9844}
9845
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009846static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00009847 while (true) {
9848 e = e->IgnoreParens();
9849 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
9850 switch (cast->getCastKind()) {
9851 case CK_BitCast:
9852 case CK_LValueBitCast:
9853 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00009854 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00009855 e = cast->getSubExpr();
9856 continue;
9857
John McCall31168b02011-06-15 23:02:42 +00009858 default:
9859 return false;
9860 }
9861 }
9862
9863 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
9864 ObjCIvarDecl *ivar = ref->getDecl();
9865 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
9866 return false;
9867
9868 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009869 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00009870 return false;
9871
9872 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
9873 owner.Indirect = true;
9874 return true;
9875 }
9876
9877 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
9878 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
9879 if (!var) return false;
9880 return considerVariable(var, ref, owner);
9881 }
9882
John McCall31168b02011-06-15 23:02:42 +00009883 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
9884 if (member->isArrow()) return false;
9885
9886 // Don't count this as an indirect ownership.
9887 e = member->getBase();
9888 continue;
9889 }
9890
John McCallfe96e0b2011-11-06 09:01:30 +00009891 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
9892 // Only pay attention to pseudo-objects on property references.
9893 ObjCPropertyRefExpr *pre
9894 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
9895 ->IgnoreParens());
9896 if (!pre) return false;
9897 if (pre->isImplicitProperty()) return false;
9898 ObjCPropertyDecl *property = pre->getExplicitProperty();
9899 if (!property->isRetaining() &&
9900 !(property->getPropertyIvarDecl() &&
9901 property->getPropertyIvarDecl()->getType()
9902 .getObjCLifetime() == Qualifiers::OCL_Strong))
9903 return false;
9904
9905 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009906 if (pre->isSuperReceiver()) {
9907 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
9908 if (!owner.Variable)
9909 return false;
9910 owner.Loc = pre->getLocation();
9911 owner.Range = pre->getSourceRange();
9912 return true;
9913 }
John McCallfe96e0b2011-11-06 09:01:30 +00009914 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
9915 ->getSourceExpr());
9916 continue;
9917 }
9918
John McCall31168b02011-06-15 23:02:42 +00009919 // Array ivars?
9920
9921 return false;
9922 }
9923}
9924
9925namespace {
9926 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
9927 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
9928 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009929 Context(Context), Variable(variable), Capturer(nullptr),
9930 VarWillBeReased(false) {}
9931 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +00009932 VarDecl *Variable;
9933 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009934 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +00009935
9936 void VisitDeclRefExpr(DeclRefExpr *ref) {
9937 if (ref->getDecl() == Variable && !Capturer)
9938 Capturer = ref;
9939 }
9940
John McCall31168b02011-06-15 23:02:42 +00009941 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
9942 if (Capturer) return;
9943 Visit(ref->getBase());
9944 if (Capturer && ref->isFreeIvar())
9945 Capturer = ref;
9946 }
9947
9948 void VisitBlockExpr(BlockExpr *block) {
9949 // Look inside nested blocks
9950 if (block->getBlockDecl()->capturesVariable(Variable))
9951 Visit(block->getBlockDecl()->getBody());
9952 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00009953
9954 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
9955 if (Capturer) return;
9956 if (OVE->getSourceExpr())
9957 Visit(OVE->getSourceExpr());
9958 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009959 void VisitBinaryOperator(BinaryOperator *BinOp) {
9960 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
9961 return;
9962 Expr *LHS = BinOp->getLHS();
9963 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
9964 if (DRE->getDecl() != Variable)
9965 return;
9966 if (Expr *RHS = BinOp->getRHS()) {
9967 RHS = RHS->IgnoreParenCasts();
9968 llvm::APSInt Value;
9969 VarWillBeReased =
9970 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
9971 }
9972 }
9973 }
John McCall31168b02011-06-15 23:02:42 +00009974 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009975} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +00009976
9977/// Check whether the given argument is a block which captures a
9978/// variable.
9979static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
9980 assert(owner.Variable && owner.Loc.isValid());
9981
9982 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00009983
9984 // Look through [^{...} copy] and Block_copy(^{...}).
9985 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
9986 Selector Cmd = ME->getSelector();
9987 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
9988 e = ME->getInstanceReceiver();
9989 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +00009990 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +00009991 e = e->IgnoreParenCasts();
9992 }
9993 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
9994 if (CE->getNumArgs() == 1) {
9995 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00009996 if (Fn) {
9997 const IdentifierInfo *FnI = Fn->getIdentifier();
9998 if (FnI && FnI->isStr("_Block_copy")) {
9999 e = CE->getArg(0)->IgnoreParenCasts();
10000 }
10001 }
Jordan Rose67e887c2012-09-17 17:54:30 +000010002 }
10003 }
10004
John McCall31168b02011-06-15 23:02:42 +000010005 BlockExpr *block = dyn_cast<BlockExpr>(e);
10006 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +000010007 return nullptr;
John McCall31168b02011-06-15 23:02:42 +000010008
10009 FindCaptureVisitor visitor(S.Context, owner.Variable);
10010 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010011 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +000010012}
10013
10014static void diagnoseRetainCycle(Sema &S, Expr *capturer,
10015 RetainCycleOwner &owner) {
10016 assert(capturer);
10017 assert(owner.Variable && owner.Loc.isValid());
10018
10019 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
10020 << owner.Variable << capturer->getSourceRange();
10021 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
10022 << owner.Indirect << owner.Range;
10023}
10024
10025/// Check for a keyword selector that starts with the word 'add' or
10026/// 'set'.
10027static bool isSetterLikeSelector(Selector sel) {
10028 if (sel.isUnarySelector()) return false;
10029
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010030 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +000010031 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +000010032 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +000010033 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +000010034 else if (str.startswith("add")) {
10035 // Specially whitelist 'addOperationWithBlock:'.
10036 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
10037 return false;
10038 str = str.substr(3);
10039 }
John McCall31168b02011-06-15 23:02:42 +000010040 else
10041 return false;
10042
10043 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +000010044 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +000010045}
10046
Benjamin Kramer3a743452015-03-09 15:03:32 +000010047static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
10048 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010049 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
10050 Message->getReceiverInterface(),
10051 NSAPI::ClassId_NSMutableArray);
10052 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010053 return None;
10054 }
10055
10056 Selector Sel = Message->getSelector();
10057
10058 Optional<NSAPI::NSArrayMethodKind> MKOpt =
10059 S.NSAPIObj->getNSArrayMethodKind(Sel);
10060 if (!MKOpt) {
10061 return None;
10062 }
10063
10064 NSAPI::NSArrayMethodKind MK = *MKOpt;
10065
10066 switch (MK) {
10067 case NSAPI::NSMutableArr_addObject:
10068 case NSAPI::NSMutableArr_insertObjectAtIndex:
10069 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
10070 return 0;
10071 case NSAPI::NSMutableArr_replaceObjectAtIndex:
10072 return 1;
10073
10074 default:
10075 return None;
10076 }
10077
10078 return None;
10079}
10080
10081static
10082Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
10083 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010084 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
10085 Message->getReceiverInterface(),
10086 NSAPI::ClassId_NSMutableDictionary);
10087 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010088 return None;
10089 }
10090
10091 Selector Sel = Message->getSelector();
10092
10093 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
10094 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
10095 if (!MKOpt) {
10096 return None;
10097 }
10098
10099 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
10100
10101 switch (MK) {
10102 case NSAPI::NSMutableDict_setObjectForKey:
10103 case NSAPI::NSMutableDict_setValueForKey:
10104 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
10105 return 0;
10106
10107 default:
10108 return None;
10109 }
10110
10111 return None;
10112}
10113
10114static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010115 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
10116 Message->getReceiverInterface(),
10117 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +000010118
Alex Denisov5dfac812015-08-06 04:51:14 +000010119 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
10120 Message->getReceiverInterface(),
10121 NSAPI::ClassId_NSMutableOrderedSet);
10122 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010123 return None;
10124 }
10125
10126 Selector Sel = Message->getSelector();
10127
10128 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
10129 if (!MKOpt) {
10130 return None;
10131 }
10132
10133 NSAPI::NSSetMethodKind MK = *MKOpt;
10134
10135 switch (MK) {
10136 case NSAPI::NSMutableSet_addObject:
10137 case NSAPI::NSOrderedSet_setObjectAtIndex:
10138 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
10139 case NSAPI::NSOrderedSet_insertObjectAtIndex:
10140 return 0;
10141 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
10142 return 1;
10143 }
10144
10145 return None;
10146}
10147
10148void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
10149 if (!Message->isInstanceMessage()) {
10150 return;
10151 }
10152
10153 Optional<int> ArgOpt;
10154
10155 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
10156 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
10157 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
10158 return;
10159 }
10160
10161 int ArgIndex = *ArgOpt;
10162
Alex Denisove1d882c2015-03-04 17:55:52 +000010163 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
10164 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
10165 Arg = OE->getSourceExpr()->IgnoreImpCasts();
10166 }
10167
Alex Denisov5dfac812015-08-06 04:51:14 +000010168 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010169 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010170 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010171 Diag(Message->getSourceRange().getBegin(),
10172 diag::warn_objc_circular_container)
Alex Denisov5dfac812015-08-06 04:51:14 +000010173 << ArgRE->getDecl()->getName() << StringRef("super");
Alex Denisove1d882c2015-03-04 17:55:52 +000010174 }
10175 }
Alex Denisov5dfac812015-08-06 04:51:14 +000010176 } else {
10177 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
10178
10179 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
10180 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
10181 }
10182
10183 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
10184 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
10185 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
10186 ValueDecl *Decl = ReceiverRE->getDecl();
10187 Diag(Message->getSourceRange().getBegin(),
10188 diag::warn_objc_circular_container)
10189 << Decl->getName() << Decl->getName();
10190 if (!ArgRE->isObjCSelfExpr()) {
10191 Diag(Decl->getLocation(),
10192 diag::note_objc_circular_container_declared_here)
10193 << Decl->getName();
10194 }
10195 }
10196 }
10197 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
10198 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
10199 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
10200 ObjCIvarDecl *Decl = IvarRE->getDecl();
10201 Diag(Message->getSourceRange().getBegin(),
10202 diag::warn_objc_circular_container)
10203 << Decl->getName() << Decl->getName();
10204 Diag(Decl->getLocation(),
10205 diag::note_objc_circular_container_declared_here)
10206 << Decl->getName();
10207 }
Alex Denisove1d882c2015-03-04 17:55:52 +000010208 }
10209 }
10210 }
Alex Denisove1d882c2015-03-04 17:55:52 +000010211}
10212
John McCall31168b02011-06-15 23:02:42 +000010213/// Check a message send to see if it's likely to cause a retain cycle.
10214void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
10215 // Only check instance methods whose selector looks like a setter.
10216 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
10217 return;
10218
10219 // Try to find a variable that the receiver is strongly owned by.
10220 RetainCycleOwner owner;
10221 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010222 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +000010223 return;
10224 } else {
10225 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
10226 owner.Variable = getCurMethodDecl()->getSelfDecl();
10227 owner.Loc = msg->getSuperLoc();
10228 owner.Range = msg->getSuperLoc();
10229 }
10230
10231 // Check whether the receiver is captured by any of the arguments.
10232 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
10233 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
10234 return diagnoseRetainCycle(*this, capturer, owner);
10235}
10236
10237/// Check a property assign to see if it's likely to cause a retain cycle.
10238void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
10239 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010240 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +000010241 return;
10242
10243 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
10244 diagnoseRetainCycle(*this, capturer, owner);
10245}
10246
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000010247void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
10248 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +000010249 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000010250 return;
10251
10252 // Because we don't have an expression for the variable, we have to set the
10253 // location explicitly here.
10254 Owner.Loc = Var->getLocation();
10255 Owner.Range = Var->getSourceRange();
10256
10257 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
10258 diagnoseRetainCycle(*this, Capturer, Owner);
10259}
10260
Ted Kremenek9304da92012-12-21 08:04:28 +000010261static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
10262 Expr *RHS, bool isProperty) {
10263 // Check if RHS is an Objective-C object literal, which also can get
10264 // immediately zapped in a weak reference. Note that we explicitly
10265 // allow ObjCStringLiterals, since those are designed to never really die.
10266 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000010267
Ted Kremenek64873352012-12-21 22:46:35 +000010268 // This enum needs to match with the 'select' in
10269 // warn_objc_arc_literal_assign (off-by-1).
10270 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
10271 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
10272 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000010273
10274 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +000010275 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +000010276 << (isProperty ? 0 : 1)
10277 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000010278
10279 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +000010280}
10281
Ted Kremenekc1f014a2012-12-21 19:45:30 +000010282static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
10283 Qualifiers::ObjCLifetime LT,
10284 Expr *RHS, bool isProperty) {
10285 // Strip off any implicit cast added to get to the one ARC-specific.
10286 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
10287 if (cast->getCastKind() == CK_ARCConsumeObject) {
10288 S.Diag(Loc, diag::warn_arc_retained_assign)
10289 << (LT == Qualifiers::OCL_ExplicitNone)
10290 << (isProperty ? 0 : 1)
10291 << RHS->getSourceRange();
10292 return true;
10293 }
10294 RHS = cast->getSubExpr();
10295 }
10296
10297 if (LT == Qualifiers::OCL_Weak &&
10298 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
10299 return true;
10300
10301 return false;
10302}
10303
Ted Kremenekb36234d2012-12-21 08:04:20 +000010304bool Sema::checkUnsafeAssigns(SourceLocation Loc,
10305 QualType LHS, Expr *RHS) {
10306 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
10307
10308 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
10309 return false;
10310
10311 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
10312 return true;
10313
10314 return false;
10315}
10316
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010317void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
10318 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010319 QualType LHSType;
10320 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +000010321 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010322 ObjCPropertyRefExpr *PRE
10323 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
10324 if (PRE && !PRE->isImplicitProperty()) {
10325 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
10326 if (PD)
10327 LHSType = PD->getType();
10328 }
10329
10330 if (LHSType.isNull())
10331 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +000010332
10333 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
10334
10335 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010336 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +000010337 getCurFunction()->markSafeWeakUse(LHS);
10338 }
10339
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010340 if (checkUnsafeAssigns(Loc, LHSType, RHS))
10341 return;
Jordan Rose657b5f42012-09-28 22:21:35 +000010342
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010343 // FIXME. Check for other life times.
10344 if (LT != Qualifiers::OCL_None)
10345 return;
10346
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010347 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010348 if (PRE->isImplicitProperty())
10349 return;
10350 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
10351 if (!PD)
10352 return;
10353
Bill Wendling44426052012-12-20 19:22:21 +000010354 unsigned Attributes = PD->getPropertyAttributes();
10355 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010356 // when 'assign' attribute was not explicitly specified
10357 // by user, ignore it and rely on property type itself
10358 // for lifetime info.
10359 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
10360 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
10361 LHSType->isObjCRetainableType())
10362 return;
10363
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010364 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +000010365 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010366 Diag(Loc, diag::warn_arc_retained_property_assign)
10367 << RHS->getSourceRange();
10368 return;
10369 }
10370 RHS = cast->getSubExpr();
10371 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010372 }
Bill Wendling44426052012-12-20 19:22:21 +000010373 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +000010374 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
10375 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +000010376 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010377 }
10378}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010379
10380//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
10381
10382namespace {
10383bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
10384 SourceLocation StmtLoc,
10385 const NullStmt *Body) {
10386 // Do not warn if the body is a macro that expands to nothing, e.g:
10387 //
10388 // #define CALL(x)
10389 // if (condition)
10390 // CALL(0);
10391 //
10392 if (Body->hasLeadingEmptyMacro())
10393 return false;
10394
10395 // Get line numbers of statement and body.
10396 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +000010397 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010398 &StmtLineInvalid);
10399 if (StmtLineInvalid)
10400 return false;
10401
10402 bool BodyLineInvalid;
10403 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
10404 &BodyLineInvalid);
10405 if (BodyLineInvalid)
10406 return false;
10407
10408 // Warn if null statement and body are on the same line.
10409 if (StmtLine != BodyLine)
10410 return false;
10411
10412 return true;
10413}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010414} // end anonymous namespace
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010415
10416void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
10417 const Stmt *Body,
10418 unsigned DiagID) {
10419 // Since this is a syntactic check, don't emit diagnostic for template
10420 // instantiations, this just adds noise.
10421 if (CurrentInstantiationScope)
10422 return;
10423
10424 // The body should be a null statement.
10425 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
10426 if (!NBody)
10427 return;
10428
10429 // Do the usual checks.
10430 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
10431 return;
10432
10433 Diag(NBody->getSemiLoc(), DiagID);
10434 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
10435}
10436
10437void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
10438 const Stmt *PossibleBody) {
10439 assert(!CurrentInstantiationScope); // Ensured by caller
10440
10441 SourceLocation StmtLoc;
10442 const Stmt *Body;
10443 unsigned DiagID;
10444 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
10445 StmtLoc = FS->getRParenLoc();
10446 Body = FS->getBody();
10447 DiagID = diag::warn_empty_for_body;
10448 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
10449 StmtLoc = WS->getCond()->getSourceRange().getEnd();
10450 Body = WS->getBody();
10451 DiagID = diag::warn_empty_while_body;
10452 } else
10453 return; // Neither `for' nor `while'.
10454
10455 // The body should be a null statement.
10456 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
10457 if (!NBody)
10458 return;
10459
10460 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010461 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010462 return;
10463
10464 // Do the usual checks.
10465 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
10466 return;
10467
10468 // `for(...);' and `while(...);' are popular idioms, so in order to keep
10469 // noise level low, emit diagnostics only if for/while is followed by a
10470 // CompoundStmt, e.g.:
10471 // for (int i = 0; i < n; i++);
10472 // {
10473 // a(i);
10474 // }
10475 // or if for/while is followed by a statement with more indentation
10476 // than for/while itself:
10477 // for (int i = 0; i < n; i++);
10478 // a(i);
10479 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
10480 if (!ProbableTypo) {
10481 bool BodyColInvalid;
10482 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
10483 PossibleBody->getLocStart(),
10484 &BodyColInvalid);
10485 if (BodyColInvalid)
10486 return;
10487
10488 bool StmtColInvalid;
10489 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
10490 S->getLocStart(),
10491 &StmtColInvalid);
10492 if (StmtColInvalid)
10493 return;
10494
10495 if (BodyCol > StmtCol)
10496 ProbableTypo = true;
10497 }
10498
10499 if (ProbableTypo) {
10500 Diag(NBody->getSemiLoc(), DiagID);
10501 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
10502 }
10503}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010504
Richard Trieu36d0b2b2015-01-13 02:32:02 +000010505//===--- CHECK: Warn on self move with std::move. -------------------------===//
10506
10507/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
10508void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
10509 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +000010510 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
10511 return;
10512
10513 if (!ActiveTemplateInstantiations.empty())
10514 return;
10515
10516 // Strip parens and casts away.
10517 LHSExpr = LHSExpr->IgnoreParenImpCasts();
10518 RHSExpr = RHSExpr->IgnoreParenImpCasts();
10519
10520 // Check for a call expression
10521 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
10522 if (!CE || CE->getNumArgs() != 1)
10523 return;
10524
10525 // Check for a call to std::move
10526 const FunctionDecl *FD = CE->getDirectCallee();
10527 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
10528 !FD->getIdentifier()->isStr("move"))
10529 return;
10530
10531 // Get argument from std::move
10532 RHSExpr = CE->getArg(0);
10533
10534 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
10535 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
10536
10537 // Two DeclRefExpr's, check that the decls are the same.
10538 if (LHSDeclRef && RHSDeclRef) {
10539 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
10540 return;
10541 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
10542 RHSDeclRef->getDecl()->getCanonicalDecl())
10543 return;
10544
10545 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10546 << LHSExpr->getSourceRange()
10547 << RHSExpr->getSourceRange();
10548 return;
10549 }
10550
10551 // Member variables require a different approach to check for self moves.
10552 // MemberExpr's are the same if every nested MemberExpr refers to the same
10553 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
10554 // the base Expr's are CXXThisExpr's.
10555 const Expr *LHSBase = LHSExpr;
10556 const Expr *RHSBase = RHSExpr;
10557 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
10558 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
10559 if (!LHSME || !RHSME)
10560 return;
10561
10562 while (LHSME && RHSME) {
10563 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
10564 RHSME->getMemberDecl()->getCanonicalDecl())
10565 return;
10566
10567 LHSBase = LHSME->getBase();
10568 RHSBase = RHSME->getBase();
10569 LHSME = dyn_cast<MemberExpr>(LHSBase);
10570 RHSME = dyn_cast<MemberExpr>(RHSBase);
10571 }
10572
10573 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
10574 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
10575 if (LHSDeclRef && RHSDeclRef) {
10576 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
10577 return;
10578 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
10579 RHSDeclRef->getDecl()->getCanonicalDecl())
10580 return;
10581
10582 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10583 << LHSExpr->getSourceRange()
10584 << RHSExpr->getSourceRange();
10585 return;
10586 }
10587
10588 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
10589 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10590 << LHSExpr->getSourceRange()
10591 << RHSExpr->getSourceRange();
10592}
10593
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010594//===--- Layout compatibility ----------------------------------------------//
10595
10596namespace {
10597
10598bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
10599
10600/// \brief Check if two enumeration types are layout-compatible.
10601bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
10602 // C++11 [dcl.enum] p8:
10603 // Two enumeration types are layout-compatible if they have the same
10604 // underlying type.
10605 return ED1->isComplete() && ED2->isComplete() &&
10606 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
10607}
10608
10609/// \brief Check if two fields are layout-compatible.
10610bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
10611 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
10612 return false;
10613
10614 if (Field1->isBitField() != Field2->isBitField())
10615 return false;
10616
10617 if (Field1->isBitField()) {
10618 // Make sure that the bit-fields are the same length.
10619 unsigned Bits1 = Field1->getBitWidthValue(C);
10620 unsigned Bits2 = Field2->getBitWidthValue(C);
10621
10622 if (Bits1 != Bits2)
10623 return false;
10624 }
10625
10626 return true;
10627}
10628
10629/// \brief Check if two standard-layout structs are layout-compatible.
10630/// (C++11 [class.mem] p17)
10631bool isLayoutCompatibleStruct(ASTContext &C,
10632 RecordDecl *RD1,
10633 RecordDecl *RD2) {
10634 // If both records are C++ classes, check that base classes match.
10635 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
10636 // If one of records is a CXXRecordDecl we are in C++ mode,
10637 // thus the other one is a CXXRecordDecl, too.
10638 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
10639 // Check number of base classes.
10640 if (D1CXX->getNumBases() != D2CXX->getNumBases())
10641 return false;
10642
10643 // Check the base classes.
10644 for (CXXRecordDecl::base_class_const_iterator
10645 Base1 = D1CXX->bases_begin(),
10646 BaseEnd1 = D1CXX->bases_end(),
10647 Base2 = D2CXX->bases_begin();
10648 Base1 != BaseEnd1;
10649 ++Base1, ++Base2) {
10650 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
10651 return false;
10652 }
10653 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
10654 // If only RD2 is a C++ class, it should have zero base classes.
10655 if (D2CXX->getNumBases() > 0)
10656 return false;
10657 }
10658
10659 // Check the fields.
10660 RecordDecl::field_iterator Field2 = RD2->field_begin(),
10661 Field2End = RD2->field_end(),
10662 Field1 = RD1->field_begin(),
10663 Field1End = RD1->field_end();
10664 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
10665 if (!isLayoutCompatible(C, *Field1, *Field2))
10666 return false;
10667 }
10668 if (Field1 != Field1End || Field2 != Field2End)
10669 return false;
10670
10671 return true;
10672}
10673
10674/// \brief Check if two standard-layout unions are layout-compatible.
10675/// (C++11 [class.mem] p18)
10676bool isLayoutCompatibleUnion(ASTContext &C,
10677 RecordDecl *RD1,
10678 RecordDecl *RD2) {
10679 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010680 for (auto *Field2 : RD2->fields())
10681 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010682
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010683 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010684 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
10685 I = UnmatchedFields.begin(),
10686 E = UnmatchedFields.end();
10687
10688 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010689 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010690 bool Result = UnmatchedFields.erase(*I);
10691 (void) Result;
10692 assert(Result);
10693 break;
10694 }
10695 }
10696 if (I == E)
10697 return false;
10698 }
10699
10700 return UnmatchedFields.empty();
10701}
10702
10703bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
10704 if (RD1->isUnion() != RD2->isUnion())
10705 return false;
10706
10707 if (RD1->isUnion())
10708 return isLayoutCompatibleUnion(C, RD1, RD2);
10709 else
10710 return isLayoutCompatibleStruct(C, RD1, RD2);
10711}
10712
10713/// \brief Check if two types are layout-compatible in C++11 sense.
10714bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
10715 if (T1.isNull() || T2.isNull())
10716 return false;
10717
10718 // C++11 [basic.types] p11:
10719 // If two types T1 and T2 are the same type, then T1 and T2 are
10720 // layout-compatible types.
10721 if (C.hasSameType(T1, T2))
10722 return true;
10723
10724 T1 = T1.getCanonicalType().getUnqualifiedType();
10725 T2 = T2.getCanonicalType().getUnqualifiedType();
10726
10727 const Type::TypeClass TC1 = T1->getTypeClass();
10728 const Type::TypeClass TC2 = T2->getTypeClass();
10729
10730 if (TC1 != TC2)
10731 return false;
10732
10733 if (TC1 == Type::Enum) {
10734 return isLayoutCompatible(C,
10735 cast<EnumType>(T1)->getDecl(),
10736 cast<EnumType>(T2)->getDecl());
10737 } else if (TC1 == Type::Record) {
10738 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
10739 return false;
10740
10741 return isLayoutCompatible(C,
10742 cast<RecordType>(T1)->getDecl(),
10743 cast<RecordType>(T2)->getDecl());
10744 }
10745
10746 return false;
10747}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010748} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010749
10750//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
10751
10752namespace {
10753/// \brief Given a type tag expression find the type tag itself.
10754///
10755/// \param TypeExpr Type tag expression, as it appears in user's code.
10756///
10757/// \param VD Declaration of an identifier that appears in a type tag.
10758///
10759/// \param MagicValue Type tag magic value.
10760bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
10761 const ValueDecl **VD, uint64_t *MagicValue) {
10762 while(true) {
10763 if (!TypeExpr)
10764 return false;
10765
10766 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
10767
10768 switch (TypeExpr->getStmtClass()) {
10769 case Stmt::UnaryOperatorClass: {
10770 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
10771 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
10772 TypeExpr = UO->getSubExpr();
10773 continue;
10774 }
10775 return false;
10776 }
10777
10778 case Stmt::DeclRefExprClass: {
10779 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
10780 *VD = DRE->getDecl();
10781 return true;
10782 }
10783
10784 case Stmt::IntegerLiteralClass: {
10785 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
10786 llvm::APInt MagicValueAPInt = IL->getValue();
10787 if (MagicValueAPInt.getActiveBits() <= 64) {
10788 *MagicValue = MagicValueAPInt.getZExtValue();
10789 return true;
10790 } else
10791 return false;
10792 }
10793
10794 case Stmt::BinaryConditionalOperatorClass:
10795 case Stmt::ConditionalOperatorClass: {
10796 const AbstractConditionalOperator *ACO =
10797 cast<AbstractConditionalOperator>(TypeExpr);
10798 bool Result;
10799 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
10800 if (Result)
10801 TypeExpr = ACO->getTrueExpr();
10802 else
10803 TypeExpr = ACO->getFalseExpr();
10804 continue;
10805 }
10806 return false;
10807 }
10808
10809 case Stmt::BinaryOperatorClass: {
10810 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
10811 if (BO->getOpcode() == BO_Comma) {
10812 TypeExpr = BO->getRHS();
10813 continue;
10814 }
10815 return false;
10816 }
10817
10818 default:
10819 return false;
10820 }
10821 }
10822}
10823
10824/// \brief Retrieve the C type corresponding to type tag TypeExpr.
10825///
10826/// \param TypeExpr Expression that specifies a type tag.
10827///
10828/// \param MagicValues Registered magic values.
10829///
10830/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
10831/// kind.
10832///
10833/// \param TypeInfo Information about the corresponding C type.
10834///
10835/// \returns true if the corresponding C type was found.
10836bool GetMatchingCType(
10837 const IdentifierInfo *ArgumentKind,
10838 const Expr *TypeExpr, const ASTContext &Ctx,
10839 const llvm::DenseMap<Sema::TypeTagMagicValue,
10840 Sema::TypeTagData> *MagicValues,
10841 bool &FoundWrongKind,
10842 Sema::TypeTagData &TypeInfo) {
10843 FoundWrongKind = false;
10844
10845 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000010846 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010847
10848 uint64_t MagicValue;
10849
10850 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
10851 return false;
10852
10853 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000010854 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010855 if (I->getArgumentKind() != ArgumentKind) {
10856 FoundWrongKind = true;
10857 return false;
10858 }
10859 TypeInfo.Type = I->getMatchingCType();
10860 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
10861 TypeInfo.MustBeNull = I->getMustBeNull();
10862 return true;
10863 }
10864 return false;
10865 }
10866
10867 if (!MagicValues)
10868 return false;
10869
10870 llvm::DenseMap<Sema::TypeTagMagicValue,
10871 Sema::TypeTagData>::const_iterator I =
10872 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
10873 if (I == MagicValues->end())
10874 return false;
10875
10876 TypeInfo = I->second;
10877 return true;
10878}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010879} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010880
10881void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
10882 uint64_t MagicValue, QualType Type,
10883 bool LayoutCompatible,
10884 bool MustBeNull) {
10885 if (!TypeTagForDatatypeMagicValues)
10886 TypeTagForDatatypeMagicValues.reset(
10887 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
10888
10889 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
10890 (*TypeTagForDatatypeMagicValues)[Magic] =
10891 TypeTagData(Type, LayoutCompatible, MustBeNull);
10892}
10893
10894namespace {
10895bool IsSameCharType(QualType T1, QualType T2) {
10896 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
10897 if (!BT1)
10898 return false;
10899
10900 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
10901 if (!BT2)
10902 return false;
10903
10904 BuiltinType::Kind T1Kind = BT1->getKind();
10905 BuiltinType::Kind T2Kind = BT2->getKind();
10906
10907 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
10908 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
10909 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
10910 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
10911}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010912} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010913
10914void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
10915 const Expr * const *ExprArgs) {
10916 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
10917 bool IsPointerAttr = Attr->getIsPointer();
10918
10919 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
10920 bool FoundWrongKind;
10921 TypeTagData TypeInfo;
10922 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
10923 TypeTagForDatatypeMagicValues.get(),
10924 FoundWrongKind, TypeInfo)) {
10925 if (FoundWrongKind)
10926 Diag(TypeTagExpr->getExprLoc(),
10927 diag::warn_type_tag_for_datatype_wrong_kind)
10928 << TypeTagExpr->getSourceRange();
10929 return;
10930 }
10931
10932 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
10933 if (IsPointerAttr) {
10934 // Skip implicit cast of pointer to `void *' (as a function argument).
10935 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000010936 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000010937 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010938 ArgumentExpr = ICE->getSubExpr();
10939 }
10940 QualType ArgumentType = ArgumentExpr->getType();
10941
10942 // Passing a `void*' pointer shouldn't trigger a warning.
10943 if (IsPointerAttr && ArgumentType->isVoidPointerType())
10944 return;
10945
10946 if (TypeInfo.MustBeNull) {
10947 // Type tag with matching void type requires a null pointer.
10948 if (!ArgumentExpr->isNullPointerConstant(Context,
10949 Expr::NPC_ValueDependentIsNotNull)) {
10950 Diag(ArgumentExpr->getExprLoc(),
10951 diag::warn_type_safety_null_pointer_required)
10952 << ArgumentKind->getName()
10953 << ArgumentExpr->getSourceRange()
10954 << TypeTagExpr->getSourceRange();
10955 }
10956 return;
10957 }
10958
10959 QualType RequiredType = TypeInfo.Type;
10960 if (IsPointerAttr)
10961 RequiredType = Context.getPointerType(RequiredType);
10962
10963 bool mismatch = false;
10964 if (!TypeInfo.LayoutCompatible) {
10965 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
10966
10967 // C++11 [basic.fundamental] p1:
10968 // Plain char, signed char, and unsigned char are three distinct types.
10969 //
10970 // But we treat plain `char' as equivalent to `signed char' or `unsigned
10971 // char' depending on the current char signedness mode.
10972 if (mismatch)
10973 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
10974 RequiredType->getPointeeType())) ||
10975 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
10976 mismatch = false;
10977 } else
10978 if (IsPointerAttr)
10979 mismatch = !isLayoutCompatible(Context,
10980 ArgumentType->getPointeeType(),
10981 RequiredType->getPointeeType());
10982 else
10983 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
10984
10985 if (mismatch)
10986 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000010987 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010988 << TypeInfo.LayoutCompatible << RequiredType
10989 << ArgumentExpr->getSourceRange()
10990 << TypeTagExpr->getSourceRange();
10991}