blob: c1781c269d9751743aad40232d58876257066af0 [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 Lopes7ea9fd22016-08-10 18:34:47 +00006182 unsigned ExpectedNumArgs =
6183 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00006184 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00006185 return;
6186
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00006187 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
Anna Zaks22122702012-01-17 00:37:07 +00006188 BId == Builtin::BIstrndup ? 1 : 2);
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00006189 unsigned LenArg =
6190 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00006191 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006192
Nico Weber0e6daef2013-12-26 23:38:39 +00006193 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
6194 Call->getLocStart(), Call->getRParenLoc()))
6195 return;
6196
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006197 // We have special checking when the length is a sizeof expression.
6198 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
6199 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
6200 llvm::FoldingSetNodeID SizeOfArgID;
6201
Bruno Cardoso Lopesc73e4c32016-08-11 18:33:15 +00006202 // Although widely used, 'bzero' is not a standard function. Be more strict
6203 // with the argument types before allowing diagnostics and only allow the
6204 // form bzero(ptr, sizeof(...)).
6205 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6206 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
6207 return;
6208
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006209 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
6210 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00006211 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006212
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006213 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00006214 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006215 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00006216 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00006217
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006218 // Never warn about void type pointers. This can be used to suppress
6219 // false positives.
6220 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006221 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006222
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006223 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
6224 // actually comparing the expressions for equality. Because computing the
6225 // expression IDs can be expensive, we only do this if the diagnostic is
6226 // enabled.
6227 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006228 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
6229 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006230 // We only compute IDs for expressions if the warning is enabled, and
6231 // cache the sizeof arg's ID.
6232 if (SizeOfArgID == llvm::FoldingSetNodeID())
6233 SizeOfArg->Profile(SizeOfArgID, Context, true);
6234 llvm::FoldingSetNodeID DestID;
6235 Dest->Profile(DestID, Context, true);
6236 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00006237 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
6238 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006239 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00006240 StringRef ReadableName = FnName->getName();
6241
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006242 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00006243 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006244 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00006245 if (!PointeeTy->isIncompleteType() &&
6246 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006247 ActionIdx = 2; // If the pointee's size is sizeof(char),
6248 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00006249
6250 // If the function is defined as a builtin macro, do not show macro
6251 // expansion.
6252 SourceLocation SL = SizeOfArg->getExprLoc();
6253 SourceRange DSR = Dest->getSourceRange();
6254 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00006255 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00006256
6257 if (SM.isMacroArgExpansion(SL)) {
6258 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
6259 SL = SM.getSpellingLoc(SL);
6260 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
6261 SM.getSpellingLoc(DSR.getEnd()));
6262 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
6263 SM.getSpellingLoc(SSR.getEnd()));
6264 }
6265
Anna Zaksd08d9152012-05-30 23:14:52 +00006266 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006267 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00006268 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00006269 << PointeeTy
6270 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00006271 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00006272 << SSR);
6273 DiagRuntimeBehavior(SL, SizeOfArg,
6274 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
6275 << ActionIdx
6276 << SSR);
6277
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006278 break;
6279 }
6280 }
6281
6282 // Also check for cases where the sizeof argument is the exact same
6283 // type as the memory argument, and where it points to a user-defined
6284 // record type.
6285 if (SizeOfArgTy != QualType()) {
6286 if (PointeeTy->isRecordType() &&
6287 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
6288 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
6289 PDiag(diag::warn_sizeof_pointer_type_memaccess)
6290 << FnName << SizeOfArgTy << ArgIdx
6291 << PointeeTy << Dest->getSourceRange()
6292 << LenExpr->getSourceRange());
6293 break;
6294 }
Nico Weberc5e73862011-06-14 16:14:58 +00006295 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00006296 } else if (DestTy->isArrayType()) {
6297 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00006298 }
Nico Weberc5e73862011-06-14 16:14:58 +00006299
Nico Weberc44b35e2015-03-21 17:37:46 +00006300 if (PointeeTy == QualType())
6301 continue;
Anna Zaks22122702012-01-17 00:37:07 +00006302
Nico Weberc44b35e2015-03-21 17:37:46 +00006303 // Always complain about dynamic classes.
6304 bool IsContained;
6305 if (const CXXRecordDecl *ContainedRD =
6306 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00006307
Nico Weberc44b35e2015-03-21 17:37:46 +00006308 unsigned OperationType = 0;
6309 // "overwritten" if we're warning about the destination for any call
6310 // but memcmp; otherwise a verb appropriate to the call.
6311 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
6312 if (BId == Builtin::BImemcpy)
6313 OperationType = 1;
6314 else if(BId == Builtin::BImemmove)
6315 OperationType = 2;
6316 else if (BId == Builtin::BImemcmp)
6317 OperationType = 3;
6318 }
6319
John McCall31168b02011-06-15 23:02:42 +00006320 DiagRuntimeBehavior(
6321 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00006322 PDiag(diag::warn_dyn_class_memaccess)
6323 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
6324 << FnName << IsContained << ContainedRD << OperationType
6325 << Call->getCallee()->getSourceRange());
6326 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
6327 BId != Builtin::BImemset)
6328 DiagRuntimeBehavior(
6329 Dest->getExprLoc(), Dest,
6330 PDiag(diag::warn_arc_object_memaccess)
6331 << ArgIdx << FnName << PointeeTy
6332 << Call->getCallee()->getSourceRange());
6333 else
6334 continue;
6335
6336 DiagRuntimeBehavior(
6337 Dest->getExprLoc(), Dest,
6338 PDiag(diag::note_bad_memaccess_silence)
6339 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
6340 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006341 }
6342}
6343
Ted Kremenek6865f772011-08-18 20:55:45 +00006344// A little helper routine: ignore addition and subtraction of integer literals.
6345// This intentionally does not ignore all integer constant expressions because
6346// we don't want to remove sizeof().
6347static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
6348 Ex = Ex->IgnoreParenCasts();
6349
6350 for (;;) {
6351 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
6352 if (!BO || !BO->isAdditiveOp())
6353 break;
6354
6355 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
6356 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
6357
6358 if (isa<IntegerLiteral>(RHS))
6359 Ex = LHS;
6360 else if (isa<IntegerLiteral>(LHS))
6361 Ex = RHS;
6362 else
6363 break;
6364 }
6365
6366 return Ex;
6367}
6368
Anna Zaks13b08572012-08-08 21:42:23 +00006369static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
6370 ASTContext &Context) {
6371 // Only handle constant-sized or VLAs, but not flexible members.
6372 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
6373 // Only issue the FIXIT for arrays of size > 1.
6374 if (CAT->getSize().getSExtValue() <= 1)
6375 return false;
6376 } else if (!Ty->isVariableArrayType()) {
6377 return false;
6378 }
6379 return true;
6380}
6381
Ted Kremenek6865f772011-08-18 20:55:45 +00006382// Warn if the user has made the 'size' argument to strlcpy or strlcat
6383// be the size of the source, instead of the destination.
6384void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
6385 IdentifierInfo *FnName) {
6386
6387 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00006388 unsigned NumArgs = Call->getNumArgs();
6389 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00006390 return;
6391
6392 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
6393 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00006394 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00006395
6396 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
6397 Call->getLocStart(), Call->getRParenLoc()))
6398 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00006399
6400 // Look for 'strlcpy(dst, x, sizeof(x))'
6401 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
6402 CompareWithSrc = Ex;
6403 else {
6404 // Look for 'strlcpy(dst, x, strlen(x))'
6405 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00006406 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
6407 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00006408 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
6409 }
6410 }
6411
6412 if (!CompareWithSrc)
6413 return;
6414
6415 // Determine if the argument to sizeof/strlen is equal to the source
6416 // argument. In principle there's all kinds of things you could do
6417 // here, for instance creating an == expression and evaluating it with
6418 // EvaluateAsBooleanCondition, but this uses a more direct technique:
6419 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
6420 if (!SrcArgDRE)
6421 return;
6422
6423 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
6424 if (!CompareWithSrcDRE ||
6425 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
6426 return;
6427
6428 const Expr *OriginalSizeArg = Call->getArg(2);
6429 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
6430 << OriginalSizeArg->getSourceRange() << FnName;
6431
6432 // Output a FIXIT hint if the destination is an array (rather than a
6433 // pointer to an array). This could be enhanced to handle some
6434 // pointers if we know the actual size, like if DstArg is 'array+2'
6435 // we could say 'sizeof(array)-2'.
6436 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00006437 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00006438 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00006439
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00006440 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00006441 llvm::raw_svector_ostream OS(sizeString);
6442 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00006443 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00006444 OS << ")";
6445
6446 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
6447 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
6448 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00006449}
6450
Anna Zaks314cd092012-02-01 19:08:57 +00006451/// Check if two expressions refer to the same declaration.
6452static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
6453 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
6454 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
6455 return D1->getDecl() == D2->getDecl();
6456 return false;
6457}
6458
6459static const Expr *getStrlenExprArg(const Expr *E) {
6460 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6461 const FunctionDecl *FD = CE->getDirectCallee();
6462 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00006463 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00006464 return CE->getArg(0)->IgnoreParenCasts();
6465 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006466 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00006467}
6468
6469// Warn on anti-patterns as the 'size' argument to strncat.
6470// The correct size argument should look like following:
6471// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
6472void Sema::CheckStrncatArguments(const CallExpr *CE,
6473 IdentifierInfo *FnName) {
6474 // Don't crash if the user has the wrong number of arguments.
6475 if (CE->getNumArgs() < 3)
6476 return;
6477 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
6478 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
6479 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
6480
Nico Weber0e6daef2013-12-26 23:38:39 +00006481 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
6482 CE->getRParenLoc()))
6483 return;
6484
Anna Zaks314cd092012-02-01 19:08:57 +00006485 // Identify common expressions, which are wrongly used as the size argument
6486 // to strncat and may lead to buffer overflows.
6487 unsigned PatternType = 0;
6488 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
6489 // - sizeof(dst)
6490 if (referToTheSameDecl(SizeOfArg, DstArg))
6491 PatternType = 1;
6492 // - sizeof(src)
6493 else if (referToTheSameDecl(SizeOfArg, SrcArg))
6494 PatternType = 2;
6495 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
6496 if (BE->getOpcode() == BO_Sub) {
6497 const Expr *L = BE->getLHS()->IgnoreParenCasts();
6498 const Expr *R = BE->getRHS()->IgnoreParenCasts();
6499 // - sizeof(dst) - strlen(dst)
6500 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
6501 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
6502 PatternType = 1;
6503 // - sizeof(src) - (anything)
6504 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
6505 PatternType = 2;
6506 }
6507 }
6508
6509 if (PatternType == 0)
6510 return;
6511
Anna Zaks5069aa32012-02-03 01:27:37 +00006512 // Generate the diagnostic.
6513 SourceLocation SL = LenArg->getLocStart();
6514 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00006515 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00006516
6517 // If the function is defined as a builtin macro, do not show macro expansion.
6518 if (SM.isMacroArgExpansion(SL)) {
6519 SL = SM.getSpellingLoc(SL);
6520 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
6521 SM.getSpellingLoc(SR.getEnd()));
6522 }
6523
Anna Zaks13b08572012-08-08 21:42:23 +00006524 // Check if the destination is an array (rather than a pointer to an array).
6525 QualType DstTy = DstArg->getType();
6526 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
6527 Context);
6528 if (!isKnownSizeArray) {
6529 if (PatternType == 1)
6530 Diag(SL, diag::warn_strncat_wrong_size) << SR;
6531 else
6532 Diag(SL, diag::warn_strncat_src_size) << SR;
6533 return;
6534 }
6535
Anna Zaks314cd092012-02-01 19:08:57 +00006536 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00006537 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00006538 else
Anna Zaks5069aa32012-02-03 01:27:37 +00006539 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00006540
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00006541 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00006542 llvm::raw_svector_ostream OS(sizeString);
6543 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00006544 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00006545 OS << ") - ";
6546 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00006547 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00006548 OS << ") - 1";
6549
Anna Zaks5069aa32012-02-03 01:27:37 +00006550 Diag(SL, diag::note_strncat_wrong_size)
6551 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00006552}
6553
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006554//===--- CHECK: Return Address of Stack Variable --------------------------===//
6555
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006556static const Expr *EvalVal(const Expr *E,
6557 SmallVectorImpl<const DeclRefExpr *> &refVars,
6558 const Decl *ParentDecl);
6559static const Expr *EvalAddr(const Expr *E,
6560 SmallVectorImpl<const DeclRefExpr *> &refVars,
6561 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006562
6563/// CheckReturnStackAddr - Check if a return statement returns the address
6564/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006565static void
6566CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
6567 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00006568
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006569 const Expr *stackE = nullptr;
6570 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006571
6572 // Perform checking for returned stack addresses, local blocks,
6573 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00006574 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006575 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006576 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00006577 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006578 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006579 }
6580
Craig Topperc3ec1492014-05-26 06:22:03 +00006581 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006582 return; // Nothing suspicious was found.
6583
Richard Trieu81b6c562016-08-05 23:24:47 +00006584 // Parameters are initalized in the calling scope, so taking the address
6585 // of a parameter reference doesn't need a warning.
6586 for (auto *DRE : refVars)
6587 if (isa<ParmVarDecl>(DRE->getDecl()))
6588 return;
6589
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006590 SourceLocation diagLoc;
6591 SourceRange diagRange;
6592 if (refVars.empty()) {
6593 diagLoc = stackE->getLocStart();
6594 diagRange = stackE->getSourceRange();
6595 } else {
6596 // We followed through a reference variable. 'stackE' contains the
6597 // problematic expression but we will warn at the return statement pointing
6598 // at the reference variable. We will later display the "trail" of
6599 // reference variables using notes.
6600 diagLoc = refVars[0]->getLocStart();
6601 diagRange = refVars[0]->getSourceRange();
6602 }
6603
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006604 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
6605 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00006606 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006607 << DR->getDecl()->getDeclName() << diagRange;
6608 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006609 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006610 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006611 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006612 } else { // local temporary.
Richard Trieu81b6c562016-08-05 23:24:47 +00006613 // If there is an LValue->RValue conversion, then the value of the
6614 // reference type is used, not the reference.
6615 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
6616 if (ICE->getCastKind() == CK_LValueToRValue) {
6617 return;
6618 }
6619 }
Craig Topperda7b27f2015-11-17 05:40:09 +00006620 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
6621 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006622 }
6623
6624 // Display the "trail" of reference variables that we followed until we
6625 // found the problematic expression using notes.
6626 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006627 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006628 // If this var binds to another reference var, show the range of the next
6629 // var, otherwise the var binds to the problematic expression, in which case
6630 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006631 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
6632 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006633 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
6634 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006635 }
6636}
6637
6638/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
6639/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006640/// to a location on the stack, a local block, an address of a label, or a
6641/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006642/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006643/// encounter a subexpression that (1) clearly does not lead to one of the
6644/// above problematic expressions (2) is something we cannot determine leads to
6645/// a problematic expression based on such local checking.
6646///
6647/// Both EvalAddr and EvalVal follow through reference variables to evaluate
6648/// the expression that they point to. Such variables are added to the
6649/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006650///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00006651/// EvalAddr processes expressions that are pointers that are used as
6652/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006653/// At the base case of the recursion is a check for the above problematic
6654/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006655///
6656/// This implementation handles:
6657///
6658/// * pointer-to-pointer casts
6659/// * implicit conversions from array references to pointers
6660/// * taking the address of fields
6661/// * arbitrary interplay between "&" and "*" operators
6662/// * pointer arithmetic from an address of a stack variable
6663/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006664static const Expr *EvalAddr(const Expr *E,
6665 SmallVectorImpl<const DeclRefExpr *> &refVars,
6666 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006667 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00006668 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006669
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006670 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00006671 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00006672 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006673 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00006674 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00006675
Peter Collingbourne91147592011-04-15 00:35:48 +00006676 E = E->IgnoreParens();
6677
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006678 // Our "symbolic interpreter" is just a dispatch off the currently
6679 // viewed AST node. We then recursively traverse the AST by calling
6680 // EvalAddr and EvalVal appropriately.
6681 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006682 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006683 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006684
Richard Smith40f08eb2014-01-30 22:05:38 +00006685 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00006686 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00006687 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00006688
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006689 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006690 // If this is a reference variable, follow through to the expression that
6691 // it points to.
6692 if (V->hasLocalStorage() &&
6693 V->getType()->isReferenceType() && V->hasInit()) {
6694 // Add the reference variable to the "trail".
6695 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006696 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006697 }
6698
Craig Topperc3ec1492014-05-26 06:22:03 +00006699 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006700 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006701
Chris Lattner934edb22007-12-28 05:31:15 +00006702 case Stmt::UnaryOperatorClass: {
6703 // The only unary operator that make sense to handle here
6704 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006705 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006706
John McCalle3027922010-08-25 11:45:40 +00006707 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006708 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006709 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006710 }
Mike Stump11289f42009-09-09 15:08:12 +00006711
Chris Lattner934edb22007-12-28 05:31:15 +00006712 case Stmt::BinaryOperatorClass: {
6713 // Handle pointer arithmetic. All other binary operators are not valid
6714 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006715 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00006716 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00006717
John McCalle3027922010-08-25 11:45:40 +00006718 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00006719 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006720
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006721 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00006722
6723 // Determine which argument is the real pointer base. It could be
6724 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006725 if (!Base->getType()->isPointerType())
6726 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00006727
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006728 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006729 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00006730 }
Steve Naroff2752a172008-09-10 19:17:48 +00006731
Chris Lattner934edb22007-12-28 05:31:15 +00006732 // For conditional operators we need to see if either the LHS or RHS are
6733 // valid DeclRefExpr*s. If one of them is valid, we return it.
6734 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006735 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006736
Chris Lattner934edb22007-12-28 05:31:15 +00006737 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006738 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006739 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006740 // In C++, we can have a throw-expression, which has 'void' type.
6741 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006742 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006743 return LHS;
6744 }
Chris Lattner934edb22007-12-28 05:31:15 +00006745
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006746 // In C++, we can have a throw-expression, which has 'void' type.
6747 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00006748 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006749
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006750 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00006751 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006752
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006753 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00006754 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006755 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00006756 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006757
6758 case Stmt::AddrLabelExprClass:
6759 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00006760
John McCall28fc7092011-11-10 05:35:25 +00006761 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006762 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
6763 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00006764
Ted Kremenekc3b4c522008-08-07 00:49:01 +00006765 // For casts, we need to handle conversions from arrays to
6766 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00006767 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00006768 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00006769 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00006770 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00006771 case Stmt::CXXStaticCastExprClass:
6772 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00006773 case Stmt::CXXConstCastExprClass:
6774 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006775 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00006776 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00006777 case CK_LValueToRValue:
6778 case CK_NoOp:
6779 case CK_BaseToDerived:
6780 case CK_DerivedToBase:
6781 case CK_UncheckedDerivedToBase:
6782 case CK_Dynamic:
6783 case CK_CPointerToObjCPointerCast:
6784 case CK_BlockPointerToObjCPointerCast:
6785 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006786 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00006787
6788 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006789 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00006790
Richard Trieudadefde2014-07-02 04:39:38 +00006791 case CK_BitCast:
6792 if (SubExpr->getType()->isAnyPointerType() ||
6793 SubExpr->getType()->isBlockPointerType() ||
6794 SubExpr->getType()->isObjCQualifiedIdType())
6795 return EvalAddr(SubExpr, refVars, ParentDecl);
6796 else
6797 return nullptr;
6798
Eli Friedman8195ad72012-02-23 23:04:32 +00006799 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00006800 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00006801 }
Chris Lattner934edb22007-12-28 05:31:15 +00006802 }
Mike Stump11289f42009-09-09 15:08:12 +00006803
Douglas Gregorfe314812011-06-21 17:03:29 +00006804 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006805 if (const Expr *Result =
6806 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
6807 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00006808 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00006809 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006810
Chris Lattner934edb22007-12-28 05:31:15 +00006811 // Everything else: we simply don't reason about them.
6812 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00006813 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00006814 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006815}
Mike Stump11289f42009-09-09 15:08:12 +00006816
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006817/// EvalVal - This function is complements EvalAddr in the mutual recursion.
6818/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006819static const Expr *EvalVal(const Expr *E,
6820 SmallVectorImpl<const DeclRefExpr *> &refVars,
6821 const Decl *ParentDecl) {
6822 do {
6823 // We should only be called for evaluating non-pointer expressions, or
6824 // expressions with a pointer type that are not used as references but
6825 // instead
6826 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00006827
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006828 // Our "symbolic interpreter" is just a dispatch off the currently
6829 // viewed AST node. We then recursively traverse the AST by calling
6830 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00006831
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006832 E = E->IgnoreParens();
6833 switch (E->getStmtClass()) {
6834 case Stmt::ImplicitCastExprClass: {
6835 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
6836 if (IE->getValueKind() == VK_LValue) {
6837 E = IE->getSubExpr();
6838 continue;
6839 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006840 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006841 }
Richard Smith40f08eb2014-01-30 22:05:38 +00006842
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006843 case Stmt::ExprWithCleanupsClass:
6844 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
6845 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006846
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006847 case Stmt::DeclRefExprClass: {
6848 // When we hit a DeclRefExpr we are looking at code that refers to a
6849 // variable's name. If it's not a reference variable we check if it has
6850 // local storage within the function, and if so, return the expression.
6851 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6852
6853 // If we leave the immediate function, the lifetime isn't about to end.
6854 if (DR->refersToEnclosingVariableOrCapture())
6855 return nullptr;
6856
6857 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
6858 // Check if it refers to itself, e.g. "int& i = i;".
6859 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006860 return DR;
6861
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006862 if (V->hasLocalStorage()) {
6863 if (!V->getType()->isReferenceType())
6864 return DR;
6865
6866 // Reference variable, follow through to the expression that
6867 // it points to.
6868 if (V->hasInit()) {
6869 // Add the reference variable to the "trail".
6870 refVars.push_back(DR);
6871 return EvalVal(V->getInit(), refVars, V);
6872 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006873 }
6874 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006875
6876 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006877 }
Mike Stump11289f42009-09-09 15:08:12 +00006878
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006879 case Stmt::UnaryOperatorClass: {
6880 // The only unary operator that make sense to handle here
6881 // is Deref. All others don't resolve to a "name." This includes
6882 // handling all sorts of rvalues passed to a unary operator.
6883 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006884
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006885 if (U->getOpcode() == UO_Deref)
6886 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00006887
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006888 return nullptr;
6889 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006890
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006891 case Stmt::ArraySubscriptExprClass: {
6892 // Array subscripts are potential references to data on the stack. We
6893 // retrieve the DeclRefExpr* for the array variable if it indeed
6894 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00006895 const auto *ASE = cast<ArraySubscriptExpr>(E);
6896 if (ASE->isTypeDependent())
6897 return nullptr;
6898 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006899 }
Mike Stump11289f42009-09-09 15:08:12 +00006900
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006901 case Stmt::OMPArraySectionExprClass: {
6902 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
6903 ParentDecl);
6904 }
Mike Stump11289f42009-09-09 15:08:12 +00006905
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006906 case Stmt::ConditionalOperatorClass: {
6907 // For conditional operators we need to see if either the LHS or RHS are
6908 // non-NULL Expr's. If one is non-NULL, we return it.
6909 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00006910
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006911 // Handle the GNU extension for missing LHS.
6912 if (const Expr *LHSExpr = C->getLHS()) {
6913 // In C++, we can have a throw-expression, which has 'void' type.
6914 if (!LHSExpr->getType()->isVoidType())
6915 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
6916 return LHS;
6917 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006918
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006919 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006920 if (C->getRHS()->getType()->isVoidType())
6921 return nullptr;
6922
6923 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006924 }
6925
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006926 // Accesses to members are potential references to data on the stack.
6927 case Stmt::MemberExprClass: {
6928 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00006929
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006930 // Check for indirect access. We only want direct field accesses.
6931 if (M->isArrow())
6932 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006933
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006934 // Check whether the member type is itself a reference, in which case
6935 // we're not going to refer to the member, but to what the member refers
6936 // to.
6937 if (M->getMemberDecl()->getType()->isReferenceType())
6938 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006939
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006940 return EvalVal(M->getBase(), refVars, ParentDecl);
6941 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00006942
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006943 case Stmt::MaterializeTemporaryExprClass:
6944 if (const Expr *Result =
6945 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
6946 refVars, ParentDecl))
6947 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006948 return E;
6949
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006950 default:
6951 // Check that we don't return or take the address of a reference to a
6952 // temporary. This is only useful in C++.
6953 if (!E->isTypeDependent() && E->isRValue())
6954 return E;
6955
6956 // Everything else: we simply don't reason about them.
6957 return nullptr;
6958 }
6959 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006960}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006961
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006962void
6963Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
6964 SourceLocation ReturnLoc,
6965 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00006966 const AttrVec *Attrs,
6967 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006968 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
6969
6970 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00006971 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
6972 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00006973 CheckNonNullExpr(*this, RetValExp))
6974 Diag(ReturnLoc, diag::warn_null_ret)
6975 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00006976
6977 // C++11 [basic.stc.dynamic.allocation]p4:
6978 // If an allocation function declared with a non-throwing
6979 // exception-specification fails to allocate storage, it shall return
6980 // a null pointer. Any other allocation function that fails to allocate
6981 // storage shall indicate failure only by throwing an exception [...]
6982 if (FD) {
6983 OverloadedOperatorKind Op = FD->getOverloadedOperator();
6984 if (Op == OO_New || Op == OO_Array_New) {
6985 const FunctionProtoType *Proto
6986 = FD->getType()->castAs<FunctionProtoType>();
6987 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
6988 CheckNonNullExpr(*this, RetValExp))
6989 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
6990 << FD << getLangOpts().CPlusPlus11;
6991 }
6992 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006993}
6994
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006995//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
6996
6997/// Check for comparisons of floating point operands using != and ==.
6998/// Issue a warning if these are no self-comparisons, as they are not likely
6999/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00007000void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00007001 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
7002 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007003
7004 // Special case: check for x == x (which is OK).
7005 // Do not emit warnings for such cases.
7006 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
7007 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
7008 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00007009 return;
Mike Stump11289f42009-09-09 15:08:12 +00007010
Ted Kremenekeda40e22007-11-29 00:59:04 +00007011 // Special case: check for comparisons against literals that can be exactly
7012 // represented by APFloat. In such cases, do not emit a warning. This
7013 // is a heuristic: often comparison against such literals are used to
7014 // detect if a value in a variable has not changed. This clearly can
7015 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00007016 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
7017 if (FLL->isExact())
7018 return;
7019 } else
7020 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
7021 if (FLR->isExact())
7022 return;
Mike Stump11289f42009-09-09 15:08:12 +00007023
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007024 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00007025 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00007026 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00007027 return;
Mike Stump11289f42009-09-09 15:08:12 +00007028
David Blaikie1f4ff152012-07-16 20:47:22 +00007029 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00007030 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00007031 return;
Mike Stump11289f42009-09-09 15:08:12 +00007032
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007033 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00007034 Diag(Loc, diag::warn_floatingpoint_eq)
7035 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007036}
John McCallca01b222010-01-04 23:21:16 +00007037
John McCall70aa5392010-01-06 05:24:50 +00007038//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
7039//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00007040
John McCall70aa5392010-01-06 05:24:50 +00007041namespace {
John McCallca01b222010-01-04 23:21:16 +00007042
John McCall70aa5392010-01-06 05:24:50 +00007043/// Structure recording the 'active' range of an integer-valued
7044/// expression.
7045struct IntRange {
7046 /// The number of bits active in the int.
7047 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00007048
John McCall70aa5392010-01-06 05:24:50 +00007049 /// True if the int is known not to have negative values.
7050 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00007051
John McCall70aa5392010-01-06 05:24:50 +00007052 IntRange(unsigned Width, bool NonNegative)
7053 : Width(Width), NonNegative(NonNegative)
7054 {}
John McCallca01b222010-01-04 23:21:16 +00007055
John McCall817d4af2010-11-10 23:38:19 +00007056 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00007057 static IntRange forBoolType() {
7058 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00007059 }
7060
John McCall817d4af2010-11-10 23:38:19 +00007061 /// Returns the range of an opaque value of the given integral type.
7062 static IntRange forValueOfType(ASTContext &C, QualType T) {
7063 return forValueOfCanonicalType(C,
7064 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00007065 }
7066
John McCall817d4af2010-11-10 23:38:19 +00007067 /// Returns the range of an opaque value of a canonical integral type.
7068 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00007069 assert(T->isCanonicalUnqualified());
7070
7071 if (const VectorType *VT = dyn_cast<VectorType>(T))
7072 T = VT->getElementType().getTypePtr();
7073 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7074 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00007075 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7076 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00007077
David Majnemer6a426652013-06-07 22:07:20 +00007078 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00007079 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00007080 EnumDecl *Enum = ET->getDecl();
7081 if (!Enum->isCompleteDefinition())
7082 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00007083
David Majnemer6a426652013-06-07 22:07:20 +00007084 unsigned NumPositive = Enum->getNumPositiveBits();
7085 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00007086
David Majnemer6a426652013-06-07 22:07:20 +00007087 if (NumNegative == 0)
7088 return IntRange(NumPositive, true/*NonNegative*/);
7089 else
7090 return IntRange(std::max(NumPositive + 1, NumNegative),
7091 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00007092 }
John McCall70aa5392010-01-06 05:24:50 +00007093
7094 const BuiltinType *BT = cast<BuiltinType>(T);
7095 assert(BT->isInteger());
7096
7097 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7098 }
7099
John McCall817d4af2010-11-10 23:38:19 +00007100 /// Returns the "target" range of a canonical integral type, i.e.
7101 /// the range of values expressible in the type.
7102 ///
7103 /// This matches forValueOfCanonicalType except that enums have the
7104 /// full range of their type, not the range of their enumerators.
7105 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
7106 assert(T->isCanonicalUnqualified());
7107
7108 if (const VectorType *VT = dyn_cast<VectorType>(T))
7109 T = VT->getElementType().getTypePtr();
7110 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7111 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00007112 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7113 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00007114 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00007115 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00007116
7117 const BuiltinType *BT = cast<BuiltinType>(T);
7118 assert(BT->isInteger());
7119
7120 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7121 }
7122
7123 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00007124 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00007125 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00007126 L.NonNegative && R.NonNegative);
7127 }
7128
John McCall817d4af2010-11-10 23:38:19 +00007129 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00007130 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00007131 return IntRange(std::min(L.Width, R.Width),
7132 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00007133 }
7134};
7135
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007136IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00007137 if (value.isSigned() && value.isNegative())
7138 return IntRange(value.getMinSignedBits(), false);
7139
7140 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00007141 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00007142
7143 // isNonNegative() just checks the sign bit without considering
7144 // signedness.
7145 return IntRange(value.getActiveBits(), true);
7146}
7147
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007148IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
7149 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00007150 if (result.isInt())
7151 return GetValueRange(C, result.getInt(), MaxWidth);
7152
7153 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00007154 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
7155 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
7156 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
7157 R = IntRange::join(R, El);
7158 }
John McCall70aa5392010-01-06 05:24:50 +00007159 return R;
7160 }
7161
7162 if (result.isComplexInt()) {
7163 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
7164 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
7165 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00007166 }
7167
7168 // This can happen with lossless casts to intptr_t of "based" lvalues.
7169 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00007170 // FIXME: The only reason we need to pass the type in here is to get
7171 // the sign right on this one case. It would be nice if APValue
7172 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007173 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00007174 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00007175}
John McCall70aa5392010-01-06 05:24:50 +00007176
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007177QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00007178 QualType Ty = E->getType();
7179 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
7180 Ty = AtomicRHS->getValueType();
7181 return Ty;
7182}
7183
John McCall70aa5392010-01-06 05:24:50 +00007184/// Pseudo-evaluate the given integer expression, estimating the
7185/// range of values it might take.
7186///
7187/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007188IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00007189 E = E->IgnoreParens();
7190
7191 // Try a full evaluation first.
7192 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00007193 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00007194 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00007195
7196 // I think we only want to look through implicit casts here; if the
7197 // user has an explicit widening cast, we should treat the value as
7198 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007199 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00007200 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00007201 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
7202
Eli Friedmane6d33952013-07-08 20:20:06 +00007203 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00007204
George Burgess IVdf1ed002016-01-13 01:52:39 +00007205 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
7206 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00007207
John McCall70aa5392010-01-06 05:24:50 +00007208 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00007209 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00007210 return OutputTypeRange;
7211
7212 IntRange SubRange
7213 = GetExprRange(C, CE->getSubExpr(),
7214 std::min(MaxWidth, OutputTypeRange.Width));
7215
7216 // Bail out if the subexpr's range is as wide as the cast type.
7217 if (SubRange.Width >= OutputTypeRange.Width)
7218 return OutputTypeRange;
7219
7220 // Otherwise, we take the smaller width, and we're non-negative if
7221 // either the output type or the subexpr is.
7222 return IntRange(SubRange.Width,
7223 SubRange.NonNegative || OutputTypeRange.NonNegative);
7224 }
7225
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007226 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00007227 // If we can fold the condition, just take that operand.
7228 bool CondResult;
7229 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
7230 return GetExprRange(C, CondResult ? CO->getTrueExpr()
7231 : CO->getFalseExpr(),
7232 MaxWidth);
7233
7234 // Otherwise, conservatively merge.
7235 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
7236 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
7237 return IntRange::join(L, R);
7238 }
7239
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007240 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00007241 switch (BO->getOpcode()) {
7242
7243 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00007244 case BO_LAnd:
7245 case BO_LOr:
7246 case BO_LT:
7247 case BO_GT:
7248 case BO_LE:
7249 case BO_GE:
7250 case BO_EQ:
7251 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00007252 return IntRange::forBoolType();
7253
John McCallc3688382011-07-13 06:35:24 +00007254 // The type of the assignments is the type of the LHS, so the RHS
7255 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00007256 case BO_MulAssign:
7257 case BO_DivAssign:
7258 case BO_RemAssign:
7259 case BO_AddAssign:
7260 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00007261 case BO_XorAssign:
7262 case BO_OrAssign:
7263 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00007264 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00007265
John McCallc3688382011-07-13 06:35:24 +00007266 // Simple assignments just pass through the RHS, which will have
7267 // been coerced to the LHS type.
7268 case BO_Assign:
7269 // TODO: bitfields?
7270 return GetExprRange(C, BO->getRHS(), MaxWidth);
7271
John McCall70aa5392010-01-06 05:24:50 +00007272 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00007273 case BO_PtrMemD:
7274 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00007275 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00007276
John McCall2ce81ad2010-01-06 22:07:33 +00007277 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00007278 case BO_And:
7279 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00007280 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
7281 GetExprRange(C, BO->getRHS(), MaxWidth));
7282
John McCall70aa5392010-01-06 05:24:50 +00007283 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00007284 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00007285 // ...except that we want to treat '1 << (blah)' as logically
7286 // positive. It's an important idiom.
7287 if (IntegerLiteral *I
7288 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
7289 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00007290 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00007291 return IntRange(R.Width, /*NonNegative*/ true);
7292 }
7293 }
7294 // fallthrough
7295
John McCalle3027922010-08-25 11:45:40 +00007296 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00007297 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00007298
John McCall2ce81ad2010-01-06 22:07:33 +00007299 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00007300 case BO_Shr:
7301 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00007302 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
7303
7304 // If the shift amount is a positive constant, drop the width by
7305 // that much.
7306 llvm::APSInt shift;
7307 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
7308 shift.isNonNegative()) {
7309 unsigned zext = shift.getZExtValue();
7310 if (zext >= L.Width)
7311 L.Width = (L.NonNegative ? 0 : 1);
7312 else
7313 L.Width -= zext;
7314 }
7315
7316 return L;
7317 }
7318
7319 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00007320 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00007321 return GetExprRange(C, BO->getRHS(), MaxWidth);
7322
John McCall2ce81ad2010-01-06 22:07:33 +00007323 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00007324 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00007325 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00007326 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00007327 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007328
John McCall51431812011-07-14 22:39:48 +00007329 // The width of a division result is mostly determined by the size
7330 // of the LHS.
7331 case BO_Div: {
7332 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00007333 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00007334 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
7335
7336 // If the divisor is constant, use that.
7337 llvm::APSInt divisor;
7338 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
7339 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
7340 if (log2 >= L.Width)
7341 L.Width = (L.NonNegative ? 0 : 1);
7342 else
7343 L.Width = std::min(L.Width - log2, MaxWidth);
7344 return L;
7345 }
7346
7347 // Otherwise, just use the LHS's width.
7348 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
7349 return IntRange(L.Width, L.NonNegative && R.NonNegative);
7350 }
7351
7352 // The result of a remainder can't be larger than the result of
7353 // either side.
7354 case BO_Rem: {
7355 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00007356 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00007357 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
7358 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
7359
7360 IntRange meet = IntRange::meet(L, R);
7361 meet.Width = std::min(meet.Width, MaxWidth);
7362 return meet;
7363 }
7364
7365 // The default behavior is okay for these.
7366 case BO_Mul:
7367 case BO_Add:
7368 case BO_Xor:
7369 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00007370 break;
7371 }
7372
John McCall51431812011-07-14 22:39:48 +00007373 // The default case is to treat the operation as if it were closed
7374 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00007375 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
7376 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
7377 return IntRange::join(L, R);
7378 }
7379
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007380 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00007381 switch (UO->getOpcode()) {
7382 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00007383 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00007384 return IntRange::forBoolType();
7385
7386 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00007387 case UO_Deref:
7388 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00007389 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00007390
7391 default:
7392 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
7393 }
7394 }
7395
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007396 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00007397 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
7398
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007399 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00007400 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00007401 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00007402
Eli Friedmane6d33952013-07-08 20:20:06 +00007403 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00007404}
John McCall263a48b2010-01-04 23:31:57 +00007405
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007406IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00007407 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00007408}
7409
John McCall263a48b2010-01-04 23:31:57 +00007410/// Checks whether the given value, which currently has the given
7411/// source semantics, has the same value when coerced through the
7412/// target semantics.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007413bool IsSameFloatAfterCast(const llvm::APFloat &value,
7414 const llvm::fltSemantics &Src,
7415 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00007416 llvm::APFloat truncated = value;
7417
7418 bool ignored;
7419 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
7420 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
7421
7422 return truncated.bitwiseIsEqual(value);
7423}
7424
7425/// Checks whether the given value, which currently has the given
7426/// source semantics, has the same value when coerced through the
7427/// target semantics.
7428///
7429/// The value might be a vector of floats (or a complex number).
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007430bool IsSameFloatAfterCast(const APValue &value,
7431 const llvm::fltSemantics &Src,
7432 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00007433 if (value.isFloat())
7434 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
7435
7436 if (value.isVector()) {
7437 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
7438 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
7439 return false;
7440 return true;
7441 }
7442
7443 assert(value.isComplexFloat());
7444 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
7445 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
7446}
7447
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007448void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007449
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007450bool IsZero(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00007451 // Suppress cases where we are comparing against an enum constant.
7452 if (const DeclRefExpr *DR =
7453 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
7454 if (isa<EnumConstantDecl>(DR->getDecl()))
7455 return false;
7456
7457 // Suppress cases where the '0' value is expanded from a macro.
7458 if (E->getLocStart().isMacroID())
7459 return false;
7460
John McCallcc7e5bf2010-05-06 08:58:33 +00007461 llvm::APSInt Value;
7462 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
7463}
7464
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007465bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00007466 // Strip off implicit integral promotions.
7467 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00007468 if (ICE->getCastKind() != CK_IntegralCast &&
7469 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00007470 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00007471 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00007472 }
7473
7474 return E->getType()->isEnumeralType();
7475}
7476
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007477void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00007478 // Disable warning in template instantiations.
7479 if (!S.ActiveTemplateInstantiations.empty())
7480 return;
7481
John McCalle3027922010-08-25 11:45:40 +00007482 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00007483 if (E->isValueDependent())
7484 return;
7485
John McCalle3027922010-08-25 11:45:40 +00007486 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007487 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00007488 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00007489 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00007490 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007491 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00007492 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00007493 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00007494 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007495 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00007496 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00007497 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00007498 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007499 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00007500 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00007501 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
7502 }
7503}
7504
Benjamin Kramer7320b992016-06-15 14:20:56 +00007505void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant,
7506 Expr *Other, const llvm::APSInt &Value,
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007507 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00007508 // Disable warning in template instantiations.
7509 if (!S.ActiveTemplateInstantiations.empty())
7510 return;
7511
Richard Trieu0f097742014-04-04 04:13:47 +00007512 // TODO: Investigate using GetExprRange() to get tighter bounds
7513 // on the bit ranges.
7514 QualType OtherT = Other->getType();
David Majnemer7800f1f2015-05-23 01:32:17 +00007515 if (const auto *AT = OtherT->getAs<AtomicType>())
Justin Bogner4f42fc42014-07-21 18:01:53 +00007516 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00007517 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
7518 unsigned OtherWidth = OtherRange.Width;
7519
7520 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
7521
Richard Trieu560910c2012-11-14 22:50:24 +00007522 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00007523 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00007524 return;
7525
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007526 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00007527 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00007528
Richard Trieu0f097742014-04-04 04:13:47 +00007529 // Used for diagnostic printout.
7530 enum {
7531 LiteralConstant = 0,
7532 CXXBoolLiteralTrue,
7533 CXXBoolLiteralFalse
7534 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00007535
Richard Trieu0f097742014-04-04 04:13:47 +00007536 if (!OtherIsBooleanType) {
7537 QualType ConstantT = Constant->getType();
7538 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00007539
Richard Trieu0f097742014-04-04 04:13:47 +00007540 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
7541 return;
7542 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
7543 "comparison with non-integer type");
7544
7545 bool ConstantSigned = ConstantT->isSignedIntegerType();
7546 bool CommonSigned = CommonT->isSignedIntegerType();
7547
7548 bool EqualityOnly = false;
7549
7550 if (CommonSigned) {
7551 // The common type is signed, therefore no signed to unsigned conversion.
7552 if (!OtherRange.NonNegative) {
7553 // Check that the constant is representable in type OtherT.
7554 if (ConstantSigned) {
7555 if (OtherWidth >= Value.getMinSignedBits())
7556 return;
7557 } else { // !ConstantSigned
7558 if (OtherWidth >= Value.getActiveBits() + 1)
7559 return;
7560 }
7561 } else { // !OtherSigned
7562 // Check that the constant is representable in type OtherT.
7563 // Negative values are out of range.
7564 if (ConstantSigned) {
7565 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
7566 return;
7567 } else { // !ConstantSigned
7568 if (OtherWidth >= Value.getActiveBits())
7569 return;
7570 }
Richard Trieu560910c2012-11-14 22:50:24 +00007571 }
Richard Trieu0f097742014-04-04 04:13:47 +00007572 } else { // !CommonSigned
7573 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00007574 if (OtherWidth >= Value.getActiveBits())
7575 return;
Craig Toppercf360162014-06-18 05:13:11 +00007576 } else { // OtherSigned
7577 assert(!ConstantSigned &&
7578 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00007579 // Check to see if the constant is representable in OtherT.
7580 if (OtherWidth > Value.getActiveBits())
7581 return;
7582 // Check to see if the constant is equivalent to a negative value
7583 // cast to CommonT.
7584 if (S.Context.getIntWidth(ConstantT) ==
7585 S.Context.getIntWidth(CommonT) &&
7586 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
7587 return;
7588 // The constant value rests between values that OtherT can represent
7589 // after conversion. Relational comparison still works, but equality
7590 // comparisons will be tautological.
7591 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00007592 }
7593 }
Richard Trieu0f097742014-04-04 04:13:47 +00007594
7595 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
7596
7597 if (op == BO_EQ || op == BO_NE) {
7598 IsTrue = op == BO_NE;
7599 } else if (EqualityOnly) {
7600 return;
7601 } else if (RhsConstant) {
7602 if (op == BO_GT || op == BO_GE)
7603 IsTrue = !PositiveConstant;
7604 else // op == BO_LT || op == BO_LE
7605 IsTrue = PositiveConstant;
7606 } else {
7607 if (op == BO_LT || op == BO_LE)
7608 IsTrue = !PositiveConstant;
7609 else // op == BO_GT || op == BO_GE
7610 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00007611 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007612 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00007613 // Other isKnownToHaveBooleanValue
7614 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
7615 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
7616 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
7617
7618 static const struct LinkedConditions {
7619 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
7620 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
7621 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
7622 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
7623 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
7624 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
7625
7626 } TruthTable = {
7627 // Constant on LHS. | Constant on RHS. |
7628 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
7629 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
7630 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
7631 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
7632 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
7633 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
7634 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
7635 };
7636
7637 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
7638
7639 enum ConstantValue ConstVal = Zero;
7640 if (Value.isUnsigned() || Value.isNonNegative()) {
7641 if (Value == 0) {
7642 LiteralOrBoolConstant =
7643 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
7644 ConstVal = Zero;
7645 } else if (Value == 1) {
7646 LiteralOrBoolConstant =
7647 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
7648 ConstVal = One;
7649 } else {
7650 LiteralOrBoolConstant = LiteralConstant;
7651 ConstVal = GT_One;
7652 }
7653 } else {
7654 ConstVal = LT_Zero;
7655 }
7656
7657 CompareBoolWithConstantResult CmpRes;
7658
7659 switch (op) {
7660 case BO_LT:
7661 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
7662 break;
7663 case BO_GT:
7664 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
7665 break;
7666 case BO_LE:
7667 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
7668 break;
7669 case BO_GE:
7670 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
7671 break;
7672 case BO_EQ:
7673 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
7674 break;
7675 case BO_NE:
7676 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
7677 break;
7678 default:
7679 CmpRes = Unkwn;
7680 break;
7681 }
7682
7683 if (CmpRes == AFals) {
7684 IsTrue = false;
7685 } else if (CmpRes == ATrue) {
7686 IsTrue = true;
7687 } else {
7688 return;
7689 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007690 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00007691
7692 // If this is a comparison to an enum constant, include that
7693 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00007694 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00007695 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
7696 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
7697
7698 SmallString<64> PrettySourceValue;
7699 llvm::raw_svector_ostream OS(PrettySourceValue);
7700 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00007701 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00007702 else
7703 OS << Value;
7704
Richard Trieu0f097742014-04-04 04:13:47 +00007705 S.DiagRuntimeBehavior(
7706 E->getOperatorLoc(), E,
7707 S.PDiag(diag::warn_out_of_range_compare)
7708 << OS.str() << LiteralOrBoolConstant
7709 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
7710 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007711}
7712
John McCallcc7e5bf2010-05-06 08:58:33 +00007713/// Analyze the operands of the given comparison. Implements the
7714/// fallback case from AnalyzeComparison.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007715void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00007716 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
7717 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00007718}
John McCall263a48b2010-01-04 23:31:57 +00007719
John McCallca01b222010-01-04 23:21:16 +00007720/// \brief Implements -Wsign-compare.
7721///
Richard Trieu82402a02011-09-15 21:56:47 +00007722/// \param E the binary operator to check for warnings
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007723void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007724 // The type the comparison is being performed in.
7725 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00007726
7727 // Only analyze comparison operators where both sides have been converted to
7728 // the same type.
7729 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
7730 return AnalyzeImpConvsInComparison(S, E);
7731
7732 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00007733 if (E->isValueDependent())
7734 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007735
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007736 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
7737 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007738
7739 bool IsComparisonConstant = false;
7740
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007741 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007742 // of 'true' or 'false'.
7743 if (T->isIntegralType(S.Context)) {
7744 llvm::APSInt RHSValue;
7745 bool IsRHSIntegralLiteral =
7746 RHS->isIntegerConstantExpr(RHSValue, S.Context);
7747 llvm::APSInt LHSValue;
7748 bool IsLHSIntegralLiteral =
7749 LHS->isIntegerConstantExpr(LHSValue, S.Context);
7750 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
7751 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
7752 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
7753 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
7754 else
7755 IsComparisonConstant =
7756 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007757 } else if (!T->hasUnsignedIntegerRepresentation())
7758 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007759
John McCallcc7e5bf2010-05-06 08:58:33 +00007760 // We don't do anything special if this isn't an unsigned integral
7761 // comparison: we're only interested in integral comparisons, and
7762 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00007763 //
7764 // We also don't care about value-dependent expressions or expressions
7765 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007766 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00007767 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007768
John McCallcc7e5bf2010-05-06 08:58:33 +00007769 // Check to see if one of the (unmodified) operands is of different
7770 // signedness.
7771 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00007772 if (LHS->getType()->hasSignedIntegerRepresentation()) {
7773 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00007774 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00007775 signedOperand = LHS;
7776 unsignedOperand = RHS;
7777 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
7778 signedOperand = RHS;
7779 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00007780 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00007781 CheckTrivialUnsignedComparison(S, E);
7782 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007783 }
7784
John McCallcc7e5bf2010-05-06 08:58:33 +00007785 // Otherwise, calculate the effective range of the signed operand.
7786 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00007787
John McCallcc7e5bf2010-05-06 08:58:33 +00007788 // Go ahead and analyze implicit conversions in the operands. Note
7789 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00007790 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
7791 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00007792
John McCallcc7e5bf2010-05-06 08:58:33 +00007793 // If the signed range is non-negative, -Wsign-compare won't fire,
7794 // but we should still check for comparisons which are always true
7795 // or false.
7796 if (signedRange.NonNegative)
7797 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007798
7799 // For (in)equality comparisons, if the unsigned operand is a
7800 // constant which cannot collide with a overflowed signed operand,
7801 // then reinterpreting the signed operand as unsigned will not
7802 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00007803 if (E->isEqualityOp()) {
7804 unsigned comparisonWidth = S.Context.getIntWidth(T);
7805 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00007806
John McCallcc7e5bf2010-05-06 08:58:33 +00007807 // We should never be unable to prove that the unsigned operand is
7808 // non-negative.
7809 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
7810
7811 if (unsignedRange.Width < comparisonWidth)
7812 return;
7813 }
7814
Douglas Gregorbfb4a212012-05-01 01:53:49 +00007815 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
7816 S.PDiag(diag::warn_mixed_sign_comparison)
7817 << LHS->getType() << RHS->getType()
7818 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00007819}
7820
John McCall1f425642010-11-11 03:21:53 +00007821/// Analyzes an attempt to assign the given value to a bitfield.
7822///
7823/// Returns true if there was something fishy about the attempt.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007824bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
7825 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00007826 assert(Bitfield->isBitField());
7827 if (Bitfield->isInvalidDecl())
7828 return false;
7829
John McCalldeebbcf2010-11-11 05:33:51 +00007830 // White-list bool bitfields.
7831 if (Bitfield->getType()->isBooleanType())
7832 return false;
7833
Douglas Gregor789adec2011-02-04 13:09:01 +00007834 // Ignore value- or type-dependent expressions.
7835 if (Bitfield->getBitWidth()->isValueDependent() ||
7836 Bitfield->getBitWidth()->isTypeDependent() ||
7837 Init->isValueDependent() ||
7838 Init->isTypeDependent())
7839 return false;
7840
John McCall1f425642010-11-11 03:21:53 +00007841 Expr *OriginalInit = Init->IgnoreParenImpCasts();
7842
Richard Smith5fab0c92011-12-28 19:48:30 +00007843 llvm::APSInt Value;
7844 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00007845 return false;
7846
John McCall1f425642010-11-11 03:21:53 +00007847 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00007848 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00007849
Richard Trieu7561ed02016-08-05 02:39:30 +00007850 if (Value.isSigned() && Value.isNegative())
7851 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
7852 if (UO->getOpcode() == UO_Minus)
7853 if (isa<IntegerLiteral>(UO->getSubExpr()))
7854 OriginalWidth = Value.getMinSignedBits();
7855
John McCall1f425642010-11-11 03:21:53 +00007856 if (OriginalWidth <= FieldWidth)
7857 return false;
7858
Eli Friedmanc267a322012-01-26 23:11:39 +00007859 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00007860 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00007861 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00007862
Eli Friedmanc267a322012-01-26 23:11:39 +00007863 // Check whether the stored value is equal to the original value.
7864 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00007865 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00007866 return false;
7867
Eli Friedmanc267a322012-01-26 23:11:39 +00007868 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00007869 // therefore don't strictly fit into a signed bitfield of width 1.
7870 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00007871 return false;
7872
John McCall1f425642010-11-11 03:21:53 +00007873 std::string PrettyValue = Value.toString(10);
7874 std::string PrettyTrunc = TruncatedValue.toString(10);
7875
7876 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
7877 << PrettyValue << PrettyTrunc << OriginalInit->getType()
7878 << Init->getSourceRange();
7879
7880 return true;
7881}
7882
John McCalld2a53122010-11-09 23:24:47 +00007883/// Analyze the given simple or compound assignment for warning-worthy
7884/// operations.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007885void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00007886 // Just recurse on the LHS.
7887 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
7888
7889 // We want to recurse on the RHS as normal unless we're assigning to
7890 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00007891 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007892 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00007893 E->getOperatorLoc())) {
7894 // Recurse, ignoring any implicit conversions on the RHS.
7895 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
7896 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00007897 }
7898 }
7899
7900 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
7901}
7902
John McCall263a48b2010-01-04 23:31:57 +00007903/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007904void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
7905 SourceLocation CContext, unsigned diag,
7906 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00007907 if (pruneControlFlow) {
7908 S.DiagRuntimeBehavior(E->getExprLoc(), E,
7909 S.PDiag(diag)
7910 << SourceType << T << E->getSourceRange()
7911 << SourceRange(CContext));
7912 return;
7913 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00007914 S.Diag(E->getExprLoc(), diag)
7915 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
7916}
7917
Chandler Carruth7f3654f2011-04-05 06:47:57 +00007918/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007919void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
7920 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00007921 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00007922}
7923
Richard Trieube234c32016-04-21 21:04:55 +00007924
7925/// Diagnose an implicit cast from a floating point value to an integer value.
7926void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
7927
7928 SourceLocation CContext) {
7929 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
7930 const bool PruneWarnings = !S.ActiveTemplateInstantiations.empty();
7931
7932 Expr *InnerE = E->IgnoreParenImpCasts();
7933 // We also want to warn on, e.g., "int i = -1.234"
7934 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
7935 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
7936 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
7937
7938 const bool IsLiteral =
7939 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
7940
7941 llvm::APFloat Value(0.0);
7942 bool IsConstant =
7943 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
7944 if (!IsConstant) {
Richard Trieu891f0f12016-04-22 22:14:32 +00007945 return DiagnoseImpCast(S, E, T, CContext,
7946 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +00007947 }
7948
Chandler Carruth016ef402011-04-10 08:36:24 +00007949 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +00007950
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00007951 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
7952 T->hasUnsignedIntegerRepresentation());
Richard Trieube234c32016-04-21 21:04:55 +00007953 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
7954 &isExact) == llvm::APFloat::opOK &&
Richard Trieu891f0f12016-04-22 22:14:32 +00007955 isExact) {
Richard Trieube234c32016-04-21 21:04:55 +00007956 if (IsLiteral) return;
7957 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
7958 PruneWarnings);
7959 }
7960
7961 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +00007962 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +00007963 // Warn on floating point literal to integer.
7964 DiagID = diag::warn_impcast_literal_float_to_integer;
7965 } else if (IntegerValue == 0) {
7966 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
7967 return DiagnoseImpCast(S, E, T, CContext,
7968 diag::warn_impcast_float_integer, PruneWarnings);
7969 }
7970 // Warn on non-zero to zero conversion.
7971 DiagID = diag::warn_impcast_float_to_integer_zero;
7972 } else {
7973 if (IntegerValue.isUnsigned()) {
7974 if (!IntegerValue.isMaxValue()) {
7975 return DiagnoseImpCast(S, E, T, CContext,
7976 diag::warn_impcast_float_integer, PruneWarnings);
7977 }
7978 } else { // IntegerValue.isSigned()
7979 if (!IntegerValue.isMaxSignedValue() &&
7980 !IntegerValue.isMinSignedValue()) {
7981 return DiagnoseImpCast(S, E, T, CContext,
7982 diag::warn_impcast_float_integer, PruneWarnings);
7983 }
7984 }
7985 // Warn on evaluatable floating point expression to integer conversion.
7986 DiagID = diag::warn_impcast_float_to_integer;
7987 }
Chandler Carruth016ef402011-04-10 08:36:24 +00007988
Eli Friedman07185912013-08-29 23:44:43 +00007989 // FIXME: Force the precision of the source value down so we don't print
7990 // digits which are usually useless (we don't really care here if we
7991 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
7992 // would automatically print the shortest representation, but it's a bit
7993 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00007994 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00007995 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
7996 precision = (precision * 59 + 195) / 196;
7997 Value.toString(PrettySourceValue, precision);
7998
David Blaikie9b88cc02012-05-15 17:18:27 +00007999 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +00008000 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +00008001 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00008002 else
David Blaikie9b88cc02012-05-15 17:18:27 +00008003 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00008004
Richard Trieube234c32016-04-21 21:04:55 +00008005 if (PruneWarnings) {
8006 S.DiagRuntimeBehavior(E->getExprLoc(), E,
8007 S.PDiag(DiagID)
8008 << E->getType() << T.getUnqualifiedType()
8009 << PrettySourceValue << PrettyTargetValue
8010 << E->getSourceRange() << SourceRange(CContext));
8011 } else {
8012 S.Diag(E->getExprLoc(), DiagID)
8013 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
8014 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
8015 }
Chandler Carruth016ef402011-04-10 08:36:24 +00008016}
8017
John McCall18a2c2c2010-11-09 22:22:12 +00008018std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
8019 if (!Range.Width) return "0";
8020
8021 llvm::APSInt ValueInRange = Value;
8022 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00008023 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00008024 return ValueInRange.toString(10);
8025}
8026
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008027bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008028 if (!isa<ImplicitCastExpr>(Ex))
8029 return false;
8030
8031 Expr *InnerE = Ex->IgnoreParenImpCasts();
8032 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
8033 const Type *Source =
8034 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
8035 if (Target->isDependentType())
8036 return false;
8037
8038 const BuiltinType *FloatCandidateBT =
8039 dyn_cast<BuiltinType>(ToBool ? Source : Target);
8040 const Type *BoolCandidateType = ToBool ? Target : Source;
8041
8042 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
8043 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
8044}
8045
8046void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
8047 SourceLocation CC) {
8048 unsigned NumArgs = TheCall->getNumArgs();
8049 for (unsigned i = 0; i < NumArgs; ++i) {
8050 Expr *CurrA = TheCall->getArg(i);
8051 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
8052 continue;
8053
8054 bool IsSwapped = ((i > 0) &&
8055 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
8056 IsSwapped |= ((i < (NumArgs - 1)) &&
8057 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
8058 if (IsSwapped) {
8059 // Warn on this floating-point to bool conversion.
8060 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
8061 CurrA->getType(), CC,
8062 diag::warn_impcast_floating_point_to_bool);
8063 }
8064 }
8065}
8066
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008067void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00008068 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
8069 E->getExprLoc()))
8070 return;
8071
Richard Trieu09d6b802016-01-08 23:35:06 +00008072 // Don't warn on functions which have return type nullptr_t.
8073 if (isa<CallExpr>(E))
8074 return;
8075
Richard Trieu5b993502014-10-15 03:42:06 +00008076 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
8077 const Expr::NullPointerConstantKind NullKind =
8078 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
8079 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
8080 return;
8081
8082 // Return if target type is a safe conversion.
8083 if (T->isAnyPointerType() || T->isBlockPointerType() ||
8084 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
8085 return;
8086
8087 SourceLocation Loc = E->getSourceRange().getBegin();
8088
Richard Trieu0a5e1662016-02-13 00:58:53 +00008089 // Venture through the macro stacks to get to the source of macro arguments.
8090 // The new location is a better location than the complete location that was
8091 // passed in.
8092 while (S.SourceMgr.isMacroArgExpansion(Loc))
8093 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
8094
8095 while (S.SourceMgr.isMacroArgExpansion(CC))
8096 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
8097
Richard Trieu5b993502014-10-15 03:42:06 +00008098 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +00008099 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
8100 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
8101 Loc, S.SourceMgr, S.getLangOpts());
8102 if (MacroName == "NULL")
8103 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
Richard Trieu5b993502014-10-15 03:42:06 +00008104 }
8105
8106 // Only warn if the null and context location are in the same macro expansion.
8107 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
8108 return;
8109
8110 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
8111 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
8112 << FixItHint::CreateReplacement(Loc,
8113 S.getFixItZeroLiteralForType(T, Loc));
8114}
8115
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008116void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8117 ObjCArrayLiteral *ArrayLiteral);
8118void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8119 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +00008120
8121/// Check a single element within a collection literal against the
8122/// target element type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008123void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
8124 Expr *Element, unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00008125 // Skip a bitcast to 'id' or qualified 'id'.
8126 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
8127 if (ICE->getCastKind() == CK_BitCast &&
8128 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
8129 Element = ICE->getSubExpr();
8130 }
8131
8132 QualType ElementType = Element->getType();
8133 ExprResult ElementResult(Element);
8134 if (ElementType->getAs<ObjCObjectPointerType>() &&
8135 S.CheckSingleAssignmentConstraints(TargetElementType,
8136 ElementResult,
8137 false, false)
8138 != Sema::Compatible) {
8139 S.Diag(Element->getLocStart(),
8140 diag::warn_objc_collection_literal_element)
8141 << ElementType << ElementKind << TargetElementType
8142 << Element->getSourceRange();
8143 }
8144
8145 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
8146 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
8147 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
8148 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
8149}
8150
8151/// Check an Objective-C array literal being converted to the given
8152/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008153void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8154 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00008155 if (!S.NSArrayDecl)
8156 return;
8157
8158 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8159 if (!TargetObjCPtr)
8160 return;
8161
8162 if (TargetObjCPtr->isUnspecialized() ||
8163 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8164 != S.NSArrayDecl->getCanonicalDecl())
8165 return;
8166
8167 auto TypeArgs = TargetObjCPtr->getTypeArgs();
8168 if (TypeArgs.size() != 1)
8169 return;
8170
8171 QualType TargetElementType = TypeArgs[0];
8172 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
8173 checkObjCCollectionLiteralElement(S, TargetElementType,
8174 ArrayLiteral->getElement(I),
8175 0);
8176 }
8177}
8178
8179/// Check an Objective-C dictionary literal being converted to the given
8180/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008181void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8182 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00008183 if (!S.NSDictionaryDecl)
8184 return;
8185
8186 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8187 if (!TargetObjCPtr)
8188 return;
8189
8190 if (TargetObjCPtr->isUnspecialized() ||
8191 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8192 != S.NSDictionaryDecl->getCanonicalDecl())
8193 return;
8194
8195 auto TypeArgs = TargetObjCPtr->getTypeArgs();
8196 if (TypeArgs.size() != 2)
8197 return;
8198
8199 QualType TargetKeyType = TypeArgs[0];
8200 QualType TargetObjectType = TypeArgs[1];
8201 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
8202 auto Element = DictionaryLiteral->getKeyValueElement(I);
8203 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
8204 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
8205 }
8206}
8207
Richard Trieufc404c72016-02-05 23:02:38 +00008208// Helper function to filter out cases for constant width constant conversion.
8209// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008210bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
8211 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +00008212 // If initializing from a constant, and the constant starts with '0',
8213 // then it is a binary, octal, or hexadecimal. Allow these constants
8214 // to fill all the bits, even if there is a sign change.
8215 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
8216 const char FirstLiteralCharacter =
8217 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
8218 if (FirstLiteralCharacter == '0')
8219 return false;
8220 }
8221
8222 // If the CC location points to a '{', and the type is char, then assume
8223 // assume it is an array initialization.
8224 if (CC.isValid() && T->isCharType()) {
8225 const char FirstContextCharacter =
8226 S.getSourceManager().getCharacterData(CC)[0];
8227 if (FirstContextCharacter == '{')
8228 return false;
8229 }
8230
8231 return true;
8232}
8233
John McCallcc7e5bf2010-05-06 08:58:33 +00008234void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00008235 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008236 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00008237
John McCallcc7e5bf2010-05-06 08:58:33 +00008238 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
8239 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
8240 if (Source == Target) return;
8241 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00008242
Chandler Carruthc22845a2011-07-26 05:40:03 +00008243 // If the conversion context location is invalid don't complain. We also
8244 // don't want to emit a warning if the issue occurs from the expansion of
8245 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
8246 // delay this check as long as possible. Once we detect we are in that
8247 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008248 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00008249 return;
8250
Richard Trieu021baa32011-09-23 20:10:00 +00008251 // Diagnose implicit casts to bool.
8252 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
8253 if (isa<StringLiteral>(E))
8254 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00008255 // and expressions, for instance, assert(0 && "error here"), are
8256 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00008257 return DiagnoseImpCast(S, E, T, CC,
8258 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00008259 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
8260 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
8261 // This covers the literal expressions that evaluate to Objective-C
8262 // objects.
8263 return DiagnoseImpCast(S, E, T, CC,
8264 diag::warn_impcast_objective_c_literal_to_bool);
8265 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00008266 if (Source->isPointerType() || Source->canDecayToPointerType()) {
8267 // Warn on pointer to bool conversion that is always true.
8268 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
8269 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00008270 }
Richard Trieu021baa32011-09-23 20:10:00 +00008271 }
John McCall263a48b2010-01-04 23:31:57 +00008272
Douglas Gregor5054cb02015-07-07 03:58:22 +00008273 // Check implicit casts from Objective-C collection literals to specialized
8274 // collection types, e.g., NSArray<NSString *> *.
8275 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
8276 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
8277 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
8278 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
8279
John McCall263a48b2010-01-04 23:31:57 +00008280 // Strip vector types.
8281 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008282 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008283 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008284 return;
John McCallacf0ee52010-10-08 02:01:28 +00008285 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008286 }
Chris Lattneree7286f2011-06-14 04:51:15 +00008287
8288 // If the vector cast is cast between two vectors of the same size, it is
8289 // a bitcast, not a conversion.
8290 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
8291 return;
John McCall263a48b2010-01-04 23:31:57 +00008292
8293 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
8294 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
8295 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00008296 if (auto VecTy = dyn_cast<VectorType>(Target))
8297 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00008298
8299 // Strip complex types.
8300 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008301 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008302 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008303 return;
8304
John McCallacf0ee52010-10-08 02:01:28 +00008305 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008306 }
John McCall263a48b2010-01-04 23:31:57 +00008307
8308 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
8309 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
8310 }
8311
8312 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
8313 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
8314
8315 // If the source is floating point...
8316 if (SourceBT && SourceBT->isFloatingPoint()) {
8317 // ...and the target is floating point...
8318 if (TargetBT && TargetBT->isFloatingPoint()) {
8319 // ...then warn if we're dropping FP rank.
8320
8321 // Builtin FP kinds are ordered by increasing FP rank.
8322 if (SourceBT->getKind() > TargetBT->getKind()) {
8323 // Don't warn about float constants that are precisely
8324 // representable in the target type.
8325 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00008326 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00008327 // Value might be a float, a float vector, or a float complex.
8328 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00008329 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
8330 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00008331 return;
8332 }
8333
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008334 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008335 return;
8336
John McCallacf0ee52010-10-08 02:01:28 +00008337 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +00008338 }
8339 // ... or possibly if we're increasing rank, too
8340 else if (TargetBT->getKind() > SourceBT->getKind()) {
8341 if (S.SourceMgr.isInSystemMacro(CC))
8342 return;
8343
8344 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +00008345 }
8346 return;
8347 }
8348
Richard Trieube234c32016-04-21 21:04:55 +00008349 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00008350 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008351 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008352 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00008353
Richard Trieube234c32016-04-21 21:04:55 +00008354 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00008355 }
John McCall263a48b2010-01-04 23:31:57 +00008356
Richard Smith54894fd2015-12-30 01:06:52 +00008357 // Detect the case where a call result is converted from floating-point to
8358 // to bool, and the final argument to the call is converted from bool, to
8359 // discover this typo:
8360 //
8361 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
8362 //
8363 // FIXME: This is an incredibly special case; is there some more general
8364 // way to detect this class of misplaced-parentheses bug?
8365 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008366 // Check last argument of function call to see if it is an
8367 // implicit cast from a type matching the type the result
8368 // is being cast to.
8369 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +00008370 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008371 Expr *LastA = CEx->getArg(NumArgs - 1);
8372 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +00008373 if (isa<ImplicitCastExpr>(LastA) &&
8374 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008375 // Warn on this floating-point to bool conversion
8376 DiagnoseImpCast(S, E, T, CC,
8377 diag::warn_impcast_floating_point_to_bool);
8378 }
8379 }
8380 }
John McCall263a48b2010-01-04 23:31:57 +00008381 return;
8382 }
8383
Richard Trieu5b993502014-10-15 03:42:06 +00008384 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00008385
David Blaikie9366d2b2012-06-19 21:19:06 +00008386 if (!Source->isIntegerType() || !Target->isIntegerType())
8387 return;
8388
David Blaikie7555b6a2012-05-15 16:56:36 +00008389 // TODO: remove this early return once the false positives for constant->bool
8390 // in templates, macros, etc, are reduced or removed.
8391 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
8392 return;
8393
John McCallcc7e5bf2010-05-06 08:58:33 +00008394 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00008395 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00008396
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008397 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00008398 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008399 // TODO: this should happen for bitfield stores, too.
8400 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +00008401 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008402 if (S.SourceMgr.isInSystemMacro(CC))
8403 return;
8404
John McCall18a2c2c2010-11-09 22:22:12 +00008405 std::string PrettySourceValue = Value.toString(10);
8406 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008407
Ted Kremenek33ba9952011-10-22 02:37:33 +00008408 S.DiagRuntimeBehavior(E->getExprLoc(), E,
8409 S.PDiag(diag::warn_impcast_integer_precision_constant)
8410 << PrettySourceValue << PrettyTargetValue
8411 << E->getType() << T << E->getSourceRange()
8412 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00008413 return;
8414 }
8415
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008416 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
8417 if (S.SourceMgr.isInSystemMacro(CC))
8418 return;
8419
David Blaikie9455da02012-04-12 22:40:54 +00008420 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00008421 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
8422 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00008423 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00008424 }
8425
Richard Trieudcb55572016-01-29 23:51:16 +00008426 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
8427 SourceRange.NonNegative && Source->isSignedIntegerType()) {
8428 // Warn when doing a signed to signed conversion, warn if the positive
8429 // source value is exactly the width of the target type, which will
8430 // cause a negative value to be stored.
8431
8432 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +00008433 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
8434 !S.SourceMgr.isInSystemMacro(CC)) {
8435 if (isSameWidthConstantConversion(S, E, T, CC)) {
8436 std::string PrettySourceValue = Value.toString(10);
8437 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +00008438
Richard Trieufc404c72016-02-05 23:02:38 +00008439 S.DiagRuntimeBehavior(
8440 E->getExprLoc(), E,
8441 S.PDiag(diag::warn_impcast_integer_precision_constant)
8442 << PrettySourceValue << PrettyTargetValue << E->getType() << T
8443 << E->getSourceRange() << clang::SourceRange(CC));
8444 return;
Richard Trieudcb55572016-01-29 23:51:16 +00008445 }
8446 }
Richard Trieufc404c72016-02-05 23:02:38 +00008447
Richard Trieudcb55572016-01-29 23:51:16 +00008448 // Fall through for non-constants to give a sign conversion warning.
8449 }
8450
John McCallcc7e5bf2010-05-06 08:58:33 +00008451 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
8452 (!TargetRange.NonNegative && SourceRange.NonNegative &&
8453 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008454 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008455 return;
8456
John McCallcc7e5bf2010-05-06 08:58:33 +00008457 unsigned DiagID = diag::warn_impcast_integer_sign;
8458
8459 // Traditionally, gcc has warned about this under -Wsign-compare.
8460 // We also want to warn about it in -Wconversion.
8461 // So if -Wconversion is off, use a completely identical diagnostic
8462 // in the sign-compare group.
8463 // The conditional-checking code will
8464 if (ICContext) {
8465 DiagID = diag::warn_impcast_integer_sign_conditional;
8466 *ICContext = true;
8467 }
8468
John McCallacf0ee52010-10-08 02:01:28 +00008469 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00008470 }
8471
Douglas Gregora78f1932011-02-22 02:45:07 +00008472 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00008473 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
8474 // type, to give us better diagnostics.
8475 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00008476 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00008477 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8478 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
8479 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
8480 SourceType = S.Context.getTypeDeclType(Enum);
8481 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
8482 }
8483 }
8484
Douglas Gregora78f1932011-02-22 02:45:07 +00008485 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
8486 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00008487 if (SourceEnum->getDecl()->hasNameForLinkage() &&
8488 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008489 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008490 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008491 return;
8492
Douglas Gregor364f7db2011-03-12 00:14:31 +00008493 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00008494 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008495 }
John McCall263a48b2010-01-04 23:31:57 +00008496}
8497
David Blaikie18e9ac72012-05-15 21:57:38 +00008498void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
8499 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00008500
8501void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00008502 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008503 E = E->IgnoreParenImpCasts();
8504
8505 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00008506 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00008507
John McCallacf0ee52010-10-08 02:01:28 +00008508 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008509 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00008510 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00008511}
8512
David Blaikie18e9ac72012-05-15 21:57:38 +00008513void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
8514 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00008515 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00008516
8517 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00008518 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
8519 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00008520
8521 // If -Wconversion would have warned about either of the candidates
8522 // for a signedness conversion to the context type...
8523 if (!Suspicious) return;
8524
8525 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008526 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00008527 return;
8528
John McCallcc7e5bf2010-05-06 08:58:33 +00008529 // ...then check whether it would have warned about either of the
8530 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00008531 if (E->getType() == T) return;
8532
8533 Suspicious = false;
8534 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
8535 E->getType(), CC, &Suspicious);
8536 if (!Suspicious)
8537 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00008538 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00008539}
8540
Richard Trieu65724892014-11-15 06:37:39 +00008541/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
8542/// Input argument E is a logical expression.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008543void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +00008544 if (S.getLangOpts().Bool)
8545 return;
8546 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
8547}
8548
John McCallcc7e5bf2010-05-06 08:58:33 +00008549/// AnalyzeImplicitConversions - Find and report any interesting
8550/// implicit conversions in the given expression. There are a couple
8551/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00008552void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00008553 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00008554 Expr *E = OrigE->IgnoreParenImpCasts();
8555
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00008556 if (E->isTypeDependent() || E->isValueDependent())
8557 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00008558
John McCallcc7e5bf2010-05-06 08:58:33 +00008559 // For conditional operators, we analyze the arguments as if they
8560 // were being fed directly into the output.
8561 if (isa<ConditionalOperator>(E)) {
8562 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00008563 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00008564 return;
8565 }
8566
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008567 // Check implicit argument conversions for function calls.
8568 if (CallExpr *Call = dyn_cast<CallExpr>(E))
8569 CheckImplicitArgumentConversions(S, Call, CC);
8570
John McCallcc7e5bf2010-05-06 08:58:33 +00008571 // Go ahead and check any implicit conversions we might have skipped.
8572 // The non-canonical typecheck is just an optimization;
8573 // CheckImplicitConversion will filter out dead implicit conversions.
8574 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00008575 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008576
8577 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +00008578
8579 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
8580 // The bound subexpressions in a PseudoObjectExpr are not reachable
8581 // as transitive children.
8582 // FIXME: Use a more uniform representation for this.
8583 for (auto *SE : POE->semantics())
8584 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
8585 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00008586 }
Richard Smithd7bed4d2015-11-22 02:57:17 +00008587
John McCallcc7e5bf2010-05-06 08:58:33 +00008588 // Skip past explicit casts.
8589 if (isa<ExplicitCastExpr>(E)) {
8590 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00008591 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008592 }
8593
John McCalld2a53122010-11-09 23:24:47 +00008594 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8595 // Do a somewhat different check with comparison operators.
8596 if (BO->isComparisonOp())
8597 return AnalyzeComparison(S, BO);
8598
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008599 // And with simple assignments.
8600 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00008601 return AnalyzeAssignment(S, BO);
8602 }
John McCallcc7e5bf2010-05-06 08:58:33 +00008603
8604 // These break the otherwise-useful invariant below. Fortunately,
8605 // we don't really need to recurse into them, because any internal
8606 // expressions should have been analyzed already when they were
8607 // built into statements.
8608 if (isa<StmtExpr>(E)) return;
8609
8610 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00008611 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00008612
8613 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00008614 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00008615 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00008616 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +00008617 for (Stmt *SubStmt : E->children()) {
8618 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00008619 if (!ChildExpr)
8620 continue;
8621
Richard Trieu955231d2014-01-25 01:10:35 +00008622 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00008623 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00008624 // Ignore checking string literals that are in logical and operators.
8625 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00008626 continue;
8627 AnalyzeImplicitConversions(S, ChildExpr, CC);
8628 }
Richard Trieu791b86e2014-11-19 06:08:18 +00008629
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00008630 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00008631 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
8632 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00008633 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00008634
8635 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
8636 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00008637 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00008638 }
Richard Trieu791b86e2014-11-19 06:08:18 +00008639
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00008640 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
8641 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00008642 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008643}
8644
8645} // end anonymous namespace
8646
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00008647static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
8648 unsigned Start, unsigned End) {
8649 bool IllegalParams = false;
8650 for (unsigned I = Start; I <= End; ++I) {
8651 QualType Ty = TheCall->getArg(I)->getType();
8652 // Taking into account implicit conversions,
8653 // allow any integer within 32 bits range
8654 if (!Ty->isIntegerType() ||
8655 S.Context.getTypeSizeInChars(Ty).getQuantity() > 4) {
8656 S.Diag(TheCall->getArg(I)->getLocStart(),
8657 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
8658 IllegalParams = true;
8659 }
8660 // Potentially emit standard warnings for implicit conversions if enabled
8661 // using -Wconversion.
8662 CheckImplicitConversion(S, TheCall->getArg(I), S.Context.UnsignedIntTy,
8663 TheCall->getArg(I)->getLocStart());
8664 }
8665 return IllegalParams;
8666}
8667
Richard Trieuc1888e02014-06-28 23:25:37 +00008668// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
8669// Returns true when emitting a warning about taking the address of a reference.
8670static bool CheckForReference(Sema &SemaRef, const Expr *E,
Benjamin Kramer7320b992016-06-15 14:20:56 +00008671 const PartialDiagnostic &PD) {
Richard Trieuc1888e02014-06-28 23:25:37 +00008672 E = E->IgnoreParenImpCasts();
8673
8674 const FunctionDecl *FD = nullptr;
8675
8676 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8677 if (!DRE->getDecl()->getType()->isReferenceType())
8678 return false;
8679 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
8680 if (!M->getMemberDecl()->getType()->isReferenceType())
8681 return false;
8682 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00008683 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00008684 return false;
8685 FD = Call->getDirectCallee();
8686 } else {
8687 return false;
8688 }
8689
8690 SemaRef.Diag(E->getExprLoc(), PD);
8691
8692 // If possible, point to location of function.
8693 if (FD) {
8694 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
8695 }
8696
8697 return true;
8698}
8699
Richard Trieu4cbff5c2014-08-08 22:41:43 +00008700// Returns true if the SourceLocation is expanded from any macro body.
8701// Returns false if the SourceLocation is invalid, is from not in a macro
8702// expansion, or is from expanded from a top-level macro argument.
8703static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
8704 if (Loc.isInvalid())
8705 return false;
8706
8707 while (Loc.isMacroID()) {
8708 if (SM.isMacroBodyExpansion(Loc))
8709 return true;
8710 Loc = SM.getImmediateMacroCallerLoc(Loc);
8711 }
8712
8713 return false;
8714}
8715
Richard Trieu3bb8b562014-02-26 02:36:06 +00008716/// \brief Diagnose pointers that are always non-null.
8717/// \param E the expression containing the pointer
8718/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
8719/// compared to a null pointer
8720/// \param IsEqual True when the comparison is equal to a null pointer
8721/// \param Range Extra SourceRange to highlight in the diagnostic
8722void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
8723 Expr::NullPointerConstantKind NullKind,
8724 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00008725 if (!E)
8726 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008727
8728 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00008729 if (E->getExprLoc().isMacroID()) {
8730 const SourceManager &SM = getSourceManager();
8731 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
8732 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00008733 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00008734 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00008735 E = E->IgnoreImpCasts();
8736
8737 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
8738
Richard Trieuf7432752014-06-06 21:39:26 +00008739 if (isa<CXXThisExpr>(E)) {
8740 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
8741 : diag::warn_this_bool_conversion;
8742 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
8743 return;
8744 }
8745
Richard Trieu3bb8b562014-02-26 02:36:06 +00008746 bool IsAddressOf = false;
8747
8748 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
8749 if (UO->getOpcode() != UO_AddrOf)
8750 return;
8751 IsAddressOf = true;
8752 E = UO->getSubExpr();
8753 }
8754
Richard Trieuc1888e02014-06-28 23:25:37 +00008755 if (IsAddressOf) {
8756 unsigned DiagID = IsCompare
8757 ? diag::warn_address_of_reference_null_compare
8758 : diag::warn_address_of_reference_bool_conversion;
8759 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
8760 << IsEqual;
8761 if (CheckForReference(*this, E, PD)) {
8762 return;
8763 }
8764 }
8765
Nick Lewyckybc85ec82016-06-15 05:18:39 +00008766 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
8767 bool IsParam = isa<NonNullAttr>(NonnullAttr);
George Burgess IV850269a2015-12-08 22:02:00 +00008768 std::string Str;
8769 llvm::raw_string_ostream S(Str);
8770 E->printPretty(S, nullptr, getPrintingPolicy());
8771 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
8772 : diag::warn_cast_nonnull_to_bool;
8773 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
8774 << E->getSourceRange() << Range << IsEqual;
Nick Lewyckybc85ec82016-06-15 05:18:39 +00008775 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
George Burgess IV850269a2015-12-08 22:02:00 +00008776 };
8777
8778 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
8779 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
8780 if (auto *Callee = Call->getDirectCallee()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00008781 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
8782 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00008783 return;
8784 }
8785 }
8786 }
8787
Richard Trieu3bb8b562014-02-26 02:36:06 +00008788 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00008789 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008790 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
8791 D = R->getDecl();
8792 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
8793 D = M->getMemberDecl();
8794 }
8795
8796 // Weak Decls can be null.
8797 if (!D || D->isWeak())
8798 return;
George Burgess IV850269a2015-12-08 22:02:00 +00008799
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008800 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +00008801 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
8802 if (getCurFunction() &&
8803 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00008804 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
8805 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00008806 return;
8807 }
8808
8809 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
David Majnemera3debed2016-06-24 05:33:44 +00008810 auto ParamIter = llvm::find(FD->parameters(), PV);
George Burgess IV850269a2015-12-08 22:02:00 +00008811 assert(ParamIter != FD->param_end());
8812 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
8813
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008814 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
8815 if (!NonNull->args_size()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00008816 ComplainAboutNonnullParamOrCall(NonNull);
George Burgess IV850269a2015-12-08 22:02:00 +00008817 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008818 }
George Burgess IV850269a2015-12-08 22:02:00 +00008819
8820 for (unsigned ArgNo : NonNull->args()) {
8821 if (ArgNo == ParamNo) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00008822 ComplainAboutNonnullParamOrCall(NonNull);
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008823 return;
8824 }
George Burgess IV850269a2015-12-08 22:02:00 +00008825 }
8826 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008827 }
8828 }
George Burgess IV850269a2015-12-08 22:02:00 +00008829 }
8830
Richard Trieu3bb8b562014-02-26 02:36:06 +00008831 QualType T = D->getType();
8832 const bool IsArray = T->isArrayType();
8833 const bool IsFunction = T->isFunctionType();
8834
Richard Trieuc1888e02014-06-28 23:25:37 +00008835 // Address of function is used to silence the function warning.
8836 if (IsAddressOf && IsFunction) {
8837 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008838 }
8839
8840 // Found nothing.
8841 if (!IsAddressOf && !IsFunction && !IsArray)
8842 return;
8843
8844 // Pretty print the expression for the diagnostic.
8845 std::string Str;
8846 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00008847 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00008848
8849 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
8850 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +00008851 enum {
8852 AddressOf,
8853 FunctionPointer,
8854 ArrayPointer
8855 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008856 if (IsAddressOf)
8857 DiagType = AddressOf;
8858 else if (IsFunction)
8859 DiagType = FunctionPointer;
8860 else if (IsArray)
8861 DiagType = ArrayPointer;
8862 else
8863 llvm_unreachable("Could not determine diagnostic.");
8864 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
8865 << Range << IsEqual;
8866
8867 if (!IsFunction)
8868 return;
8869
8870 // Suggest '&' to silence the function warning.
8871 Diag(E->getExprLoc(), diag::note_function_warning_silence)
8872 << FixItHint::CreateInsertion(E->getLocStart(), "&");
8873
8874 // Check to see if '()' fixit should be emitted.
8875 QualType ReturnType;
8876 UnresolvedSet<4> NonTemplateOverloads;
8877 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
8878 if (ReturnType.isNull())
8879 return;
8880
8881 if (IsCompare) {
8882 // There are two cases here. If there is null constant, the only suggest
8883 // for a pointer return type. If the null is 0, then suggest if the return
8884 // type is a pointer or an integer type.
8885 if (!ReturnType->isPointerType()) {
8886 if (NullKind == Expr::NPCK_ZeroExpression ||
8887 NullKind == Expr::NPCK_ZeroLiteral) {
8888 if (!ReturnType->isIntegerType())
8889 return;
8890 } else {
8891 return;
8892 }
8893 }
8894 } else { // !IsCompare
8895 // For function to bool, only suggest if the function pointer has bool
8896 // return type.
8897 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
8898 return;
8899 }
8900 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00008901 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00008902}
8903
John McCallcc7e5bf2010-05-06 08:58:33 +00008904/// Diagnoses "dangerous" implicit conversions within the given
8905/// expression (which is a full expression). Implements -Wconversion
8906/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00008907///
8908/// \param CC the "context" location of the implicit conversion, i.e.
8909/// the most location of the syntactic entity requiring the implicit
8910/// conversion
8911void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008912 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00008913 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00008914 return;
8915
8916 // Don't diagnose for value- or type-dependent expressions.
8917 if (E->isTypeDependent() || E->isValueDependent())
8918 return;
8919
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008920 // Check for array bounds violations in cases where the check isn't triggered
8921 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
8922 // ArraySubscriptExpr is on the RHS of a variable initialization.
8923 CheckArrayAccess(E);
8924
John McCallacf0ee52010-10-08 02:01:28 +00008925 // This is not the right CC for (e.g.) a variable initialization.
8926 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008927}
8928
Richard Trieu65724892014-11-15 06:37:39 +00008929/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
8930/// Input argument E is a logical expression.
8931void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
8932 ::CheckBoolLikeConversion(*this, E, CC);
8933}
8934
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008935/// Diagnose when expression is an integer constant expression and its evaluation
8936/// results in integer overflow
8937void Sema::CheckForIntOverflow (Expr *E) {
Akira Hatanakadfe2156f2016-02-10 06:06:06 +00008938 // Use a work list to deal with nested struct initializers.
8939 SmallVector<Expr *, 2> Exprs(1, E);
8940
8941 do {
8942 Expr *E = Exprs.pop_back_val();
8943
8944 if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
8945 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
8946 continue;
8947 }
8948
8949 if (auto InitList = dyn_cast<InitListExpr>(E))
8950 Exprs.append(InitList->inits().begin(), InitList->inits().end());
8951 } while (!Exprs.empty());
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008952}
8953
Richard Smithc406cb72013-01-17 01:17:56 +00008954namespace {
8955/// \brief Visitor for expressions which looks for unsequenced operations on the
8956/// same object.
8957class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00008958 typedef EvaluatedExprVisitor<SequenceChecker> Base;
8959
Richard Smithc406cb72013-01-17 01:17:56 +00008960 /// \brief A tree of sequenced regions within an expression. Two regions are
8961 /// unsequenced if one is an ancestor or a descendent of the other. When we
8962 /// finish processing an expression with sequencing, such as a comma
8963 /// expression, we fold its tree nodes into its parent, since they are
8964 /// unsequenced with respect to nodes we will visit later.
8965 class SequenceTree {
8966 struct Value {
8967 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
8968 unsigned Parent : 31;
Aaron Ballmanaffa1c32016-07-06 18:33:01 +00008969 unsigned Merged : 1;
Richard Smithc406cb72013-01-17 01:17:56 +00008970 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008971 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00008972
8973 public:
8974 /// \brief A region within an expression which may be sequenced with respect
8975 /// to some other region.
8976 class Seq {
8977 explicit Seq(unsigned N) : Index(N) {}
8978 unsigned Index;
8979 friend class SequenceTree;
8980 public:
8981 Seq() : Index(0) {}
8982 };
8983
8984 SequenceTree() { Values.push_back(Value(0)); }
8985 Seq root() const { return Seq(0); }
8986
8987 /// \brief Create a new sequence of operations, which is an unsequenced
8988 /// subset of \p Parent. This sequence of operations is sequenced with
8989 /// respect to other children of \p Parent.
8990 Seq allocate(Seq Parent) {
8991 Values.push_back(Value(Parent.Index));
8992 return Seq(Values.size() - 1);
8993 }
8994
8995 /// \brief Merge a sequence of operations into its parent.
8996 void merge(Seq S) {
8997 Values[S.Index].Merged = true;
8998 }
8999
9000 /// \brief Determine whether two operations are unsequenced. This operation
9001 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
9002 /// should have been merged into its parent as appropriate.
9003 bool isUnsequenced(Seq Cur, Seq Old) {
9004 unsigned C = representative(Cur.Index);
9005 unsigned Target = representative(Old.Index);
9006 while (C >= Target) {
9007 if (C == Target)
9008 return true;
9009 C = Values[C].Parent;
9010 }
9011 return false;
9012 }
9013
9014 private:
9015 /// \brief Pick a representative for a sequence.
9016 unsigned representative(unsigned K) {
9017 if (Values[K].Merged)
9018 // Perform path compression as we go.
9019 return Values[K].Parent = representative(Values[K].Parent);
9020 return K;
9021 }
9022 };
9023
9024 /// An object for which we can track unsequenced uses.
9025 typedef NamedDecl *Object;
9026
9027 /// Different flavors of object usage which we track. We only track the
9028 /// least-sequenced usage of each kind.
9029 enum UsageKind {
9030 /// A read of an object. Multiple unsequenced reads are OK.
9031 UK_Use,
9032 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00009033 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00009034 UK_ModAsValue,
9035 /// A modification of an object which is not sequenced before the value
9036 /// computation of the expression, such as n++.
9037 UK_ModAsSideEffect,
9038
9039 UK_Count = UK_ModAsSideEffect + 1
9040 };
9041
9042 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00009043 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00009044 Expr *Use;
9045 SequenceTree::Seq Seq;
9046 };
9047
9048 struct UsageInfo {
9049 UsageInfo() : Diagnosed(false) {}
9050 Usage Uses[UK_Count];
9051 /// Have we issued a diagnostic for this variable already?
9052 bool Diagnosed;
9053 };
9054 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
9055
9056 Sema &SemaRef;
9057 /// Sequenced regions within the expression.
9058 SequenceTree Tree;
9059 /// Declaration modifications and references which we have seen.
9060 UsageInfoMap UsageMap;
9061 /// The region we are currently within.
9062 SequenceTree::Seq Region;
9063 /// Filled in with declarations which were modified as a side-effect
9064 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009065 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00009066 /// Expressions to check later. We defer checking these to reduce
9067 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009068 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00009069
9070 /// RAII object wrapping the visitation of a sequenced subexpression of an
9071 /// expression. At the end of this process, the side-effects of the evaluation
9072 /// become sequenced with respect to the value computation of the result, so
9073 /// we downgrade any UK_ModAsSideEffect within the evaluation to
9074 /// UK_ModAsValue.
9075 struct SequencedSubexpression {
9076 SequencedSubexpression(SequenceChecker &Self)
9077 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
9078 Self.ModAsSideEffect = &ModAsSideEffect;
9079 }
9080 ~SequencedSubexpression() {
David Majnemerf7e36092016-06-23 00:15:04 +00009081 for (auto &M : llvm::reverse(ModAsSideEffect)) {
9082 UsageInfo &U = Self.UsageMap[M.first];
Richard Smithe8efd992014-12-03 01:05:50 +00009083 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
David Majnemerf7e36092016-06-23 00:15:04 +00009084 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
9085 SideEffectUsage = M.second;
Richard Smithc406cb72013-01-17 01:17:56 +00009086 }
9087 Self.ModAsSideEffect = OldModAsSideEffect;
9088 }
9089
9090 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009091 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
9092 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00009093 };
9094
Richard Smith40238f02013-06-20 22:21:56 +00009095 /// RAII object wrapping the visitation of a subexpression which we might
9096 /// choose to evaluate as a constant. If any subexpression is evaluated and
9097 /// found to be non-constant, this allows us to suppress the evaluation of
9098 /// the outer expression.
9099 class EvaluationTracker {
9100 public:
9101 EvaluationTracker(SequenceChecker &Self)
9102 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
9103 Self.EvalTracker = this;
9104 }
9105 ~EvaluationTracker() {
9106 Self.EvalTracker = Prev;
9107 if (Prev)
9108 Prev->EvalOK &= EvalOK;
9109 }
9110
9111 bool evaluate(const Expr *E, bool &Result) {
9112 if (!EvalOK || E->isValueDependent())
9113 return false;
9114 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
9115 return EvalOK;
9116 }
9117
9118 private:
9119 SequenceChecker &Self;
9120 EvaluationTracker *Prev;
9121 bool EvalOK;
9122 } *EvalTracker;
9123
Richard Smithc406cb72013-01-17 01:17:56 +00009124 /// \brief Find the object which is produced by the specified expression,
9125 /// if any.
9126 Object getObject(Expr *E, bool Mod) const {
9127 E = E->IgnoreParenCasts();
9128 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9129 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
9130 return getObject(UO->getSubExpr(), Mod);
9131 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9132 if (BO->getOpcode() == BO_Comma)
9133 return getObject(BO->getRHS(), Mod);
9134 if (Mod && BO->isAssignmentOp())
9135 return getObject(BO->getLHS(), Mod);
9136 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9137 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
9138 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
9139 return ME->getMemberDecl();
9140 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9141 // FIXME: If this is a reference, map through to its value.
9142 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00009143 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00009144 }
9145
9146 /// \brief Note that an object was modified or used by an expression.
9147 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
9148 Usage &U = UI.Uses[UK];
9149 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
9150 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
9151 ModAsSideEffect->push_back(std::make_pair(O, U));
9152 U.Use = Ref;
9153 U.Seq = Region;
9154 }
9155 }
9156 /// \brief Check whether a modification or use conflicts with a prior usage.
9157 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
9158 bool IsModMod) {
9159 if (UI.Diagnosed)
9160 return;
9161
9162 const Usage &U = UI.Uses[OtherKind];
9163 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
9164 return;
9165
9166 Expr *Mod = U.Use;
9167 Expr *ModOrUse = Ref;
9168 if (OtherKind == UK_Use)
9169 std::swap(Mod, ModOrUse);
9170
9171 SemaRef.Diag(Mod->getExprLoc(),
9172 IsModMod ? diag::warn_unsequenced_mod_mod
9173 : diag::warn_unsequenced_mod_use)
9174 << O << SourceRange(ModOrUse->getExprLoc());
9175 UI.Diagnosed = true;
9176 }
9177
9178 void notePreUse(Object O, Expr *Use) {
9179 UsageInfo &U = UsageMap[O];
9180 // Uses conflict with other modifications.
9181 checkUsage(O, U, Use, UK_ModAsValue, false);
9182 }
9183 void notePostUse(Object O, Expr *Use) {
9184 UsageInfo &U = UsageMap[O];
9185 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
9186 addUsage(U, O, Use, UK_Use);
9187 }
9188
9189 void notePreMod(Object O, Expr *Mod) {
9190 UsageInfo &U = UsageMap[O];
9191 // Modifications conflict with other modifications and with uses.
9192 checkUsage(O, U, Mod, UK_ModAsValue, true);
9193 checkUsage(O, U, Mod, UK_Use, false);
9194 }
9195 void notePostMod(Object O, Expr *Use, UsageKind UK) {
9196 UsageInfo &U = UsageMap[O];
9197 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
9198 addUsage(U, O, Use, UK);
9199 }
9200
9201public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009202 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00009203 : Base(S.Context), SemaRef(S), Region(Tree.root()),
9204 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00009205 Visit(E);
9206 }
9207
9208 void VisitStmt(Stmt *S) {
9209 // Skip all statements which aren't expressions for now.
9210 }
9211
9212 void VisitExpr(Expr *E) {
9213 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00009214 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00009215 }
9216
9217 void VisitCastExpr(CastExpr *E) {
9218 Object O = Object();
9219 if (E->getCastKind() == CK_LValueToRValue)
9220 O = getObject(E->getSubExpr(), false);
9221
9222 if (O)
9223 notePreUse(O, E);
9224 VisitExpr(E);
9225 if (O)
9226 notePostUse(O, E);
9227 }
9228
9229 void VisitBinComma(BinaryOperator *BO) {
9230 // C++11 [expr.comma]p1:
9231 // Every value computation and side effect associated with the left
9232 // expression is sequenced before every value computation and side
9233 // effect associated with the right expression.
9234 SequenceTree::Seq LHS = Tree.allocate(Region);
9235 SequenceTree::Seq RHS = Tree.allocate(Region);
9236 SequenceTree::Seq OldRegion = Region;
9237
9238 {
9239 SequencedSubexpression SeqLHS(*this);
9240 Region = LHS;
9241 Visit(BO->getLHS());
9242 }
9243
9244 Region = RHS;
9245 Visit(BO->getRHS());
9246
9247 Region = OldRegion;
9248
9249 // Forget that LHS and RHS are sequenced. They are both unsequenced
9250 // with respect to other stuff.
9251 Tree.merge(LHS);
9252 Tree.merge(RHS);
9253 }
9254
9255 void VisitBinAssign(BinaryOperator *BO) {
9256 // The modification is sequenced after the value computation of the LHS
9257 // and RHS, so check it before inspecting the operands and update the
9258 // map afterwards.
9259 Object O = getObject(BO->getLHS(), true);
9260 if (!O)
9261 return VisitExpr(BO);
9262
9263 notePreMod(O, BO);
9264
9265 // C++11 [expr.ass]p7:
9266 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
9267 // only once.
9268 //
9269 // Therefore, for a compound assignment operator, O is considered used
9270 // everywhere except within the evaluation of E1 itself.
9271 if (isa<CompoundAssignOperator>(BO))
9272 notePreUse(O, BO);
9273
9274 Visit(BO->getLHS());
9275
9276 if (isa<CompoundAssignOperator>(BO))
9277 notePostUse(O, BO);
9278
9279 Visit(BO->getRHS());
9280
Richard Smith83e37bee2013-06-26 23:16:51 +00009281 // C++11 [expr.ass]p1:
9282 // the assignment is sequenced [...] before the value computation of the
9283 // assignment expression.
9284 // C11 6.5.16/3 has no such rule.
9285 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
9286 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00009287 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009288
Richard Smithc406cb72013-01-17 01:17:56 +00009289 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
9290 VisitBinAssign(CAO);
9291 }
9292
9293 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
9294 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
9295 void VisitUnaryPreIncDec(UnaryOperator *UO) {
9296 Object O = getObject(UO->getSubExpr(), true);
9297 if (!O)
9298 return VisitExpr(UO);
9299
9300 notePreMod(O, UO);
9301 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00009302 // C++11 [expr.pre.incr]p1:
9303 // the expression ++x is equivalent to x+=1
9304 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
9305 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00009306 }
9307
9308 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
9309 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
9310 void VisitUnaryPostIncDec(UnaryOperator *UO) {
9311 Object O = getObject(UO->getSubExpr(), true);
9312 if (!O)
9313 return VisitExpr(UO);
9314
9315 notePreMod(O, UO);
9316 Visit(UO->getSubExpr());
9317 notePostMod(O, UO, UK_ModAsSideEffect);
9318 }
9319
9320 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
9321 void VisitBinLOr(BinaryOperator *BO) {
9322 // The side-effects of the LHS of an '&&' are sequenced before the
9323 // value computation of the RHS, and hence before the value computation
9324 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
9325 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00009326 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00009327 {
9328 SequencedSubexpression Sequenced(*this);
9329 Visit(BO->getLHS());
9330 }
9331
9332 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00009333 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00009334 if (!Result)
9335 Visit(BO->getRHS());
9336 } else {
9337 // Check for unsequenced operations in the RHS, treating it as an
9338 // entirely separate evaluation.
9339 //
9340 // FIXME: If there are operations in the RHS which are unsequenced
9341 // with respect to operations outside the RHS, and those operations
9342 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00009343 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00009344 }
Richard Smithc406cb72013-01-17 01:17:56 +00009345 }
9346 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00009347 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00009348 {
9349 SequencedSubexpression Sequenced(*this);
9350 Visit(BO->getLHS());
9351 }
9352
9353 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00009354 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00009355 if (Result)
9356 Visit(BO->getRHS());
9357 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00009358 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00009359 }
Richard Smithc406cb72013-01-17 01:17:56 +00009360 }
9361
9362 // Only visit the condition, unless we can be sure which subexpression will
9363 // be chosen.
9364 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00009365 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00009366 {
9367 SequencedSubexpression Sequenced(*this);
9368 Visit(CO->getCond());
9369 }
Richard Smithc406cb72013-01-17 01:17:56 +00009370
9371 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00009372 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00009373 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00009374 else {
Richard Smithd33f5202013-01-17 23:18:09 +00009375 WorkList.push_back(CO->getTrueExpr());
9376 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00009377 }
Richard Smithc406cb72013-01-17 01:17:56 +00009378 }
9379
Richard Smithe3dbfe02013-06-30 10:40:20 +00009380 void VisitCallExpr(CallExpr *CE) {
9381 // C++11 [intro.execution]p15:
9382 // When calling a function [...], every value computation and side effect
9383 // associated with any argument expression, or with the postfix expression
9384 // designating the called function, is sequenced before execution of every
9385 // expression or statement in the body of the function [and thus before
9386 // the value computation of its result].
9387 SequencedSubexpression Sequenced(*this);
9388 Base::VisitCallExpr(CE);
9389
9390 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
9391 }
9392
Richard Smithc406cb72013-01-17 01:17:56 +00009393 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00009394 // This is a call, so all subexpressions are sequenced before the result.
9395 SequencedSubexpression Sequenced(*this);
9396
Richard Smithc406cb72013-01-17 01:17:56 +00009397 if (!CCE->isListInitialization())
9398 return VisitExpr(CCE);
9399
9400 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009401 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00009402 SequenceTree::Seq Parent = Region;
9403 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
9404 E = CCE->arg_end();
9405 I != E; ++I) {
9406 Region = Tree.allocate(Parent);
9407 Elts.push_back(Region);
9408 Visit(*I);
9409 }
9410
9411 // Forget that the initializers are sequenced.
9412 Region = Parent;
9413 for (unsigned I = 0; I < Elts.size(); ++I)
9414 Tree.merge(Elts[I]);
9415 }
9416
9417 void VisitInitListExpr(InitListExpr *ILE) {
9418 if (!SemaRef.getLangOpts().CPlusPlus11)
9419 return VisitExpr(ILE);
9420
9421 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009422 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00009423 SequenceTree::Seq Parent = Region;
9424 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
9425 Expr *E = ILE->getInit(I);
9426 if (!E) continue;
9427 Region = Tree.allocate(Parent);
9428 Elts.push_back(Region);
9429 Visit(E);
9430 }
9431
9432 // Forget that the initializers are sequenced.
9433 Region = Parent;
9434 for (unsigned I = 0; I < Elts.size(); ++I)
9435 Tree.merge(Elts[I]);
9436 }
9437};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009438} // end anonymous namespace
Richard Smithc406cb72013-01-17 01:17:56 +00009439
9440void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009441 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00009442 WorkList.push_back(E);
9443 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00009444 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00009445 SequenceChecker(*this, Item, WorkList);
9446 }
Richard Smithc406cb72013-01-17 01:17:56 +00009447}
9448
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009449void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
9450 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00009451 CheckImplicitConversions(E, CheckLoc);
Richard Trieu71d74d42016-08-05 21:02:34 +00009452 if (!E->isInstantiationDependent())
9453 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009454 if (!IsConstexpr && !E->isValueDependent())
9455 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00009456}
9457
John McCall1f425642010-11-11 03:21:53 +00009458void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
9459 FieldDecl *BitField,
9460 Expr *Init) {
9461 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
9462}
9463
David Majnemer61a5bbf2015-04-07 22:08:51 +00009464static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
9465 SourceLocation Loc) {
9466 if (!PType->isVariablyModifiedType())
9467 return;
9468 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
9469 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
9470 return;
9471 }
David Majnemerdf8f73f2015-04-09 19:53:25 +00009472 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
9473 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
9474 return;
9475 }
David Majnemer61a5bbf2015-04-07 22:08:51 +00009476 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
9477 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
9478 return;
9479 }
9480
9481 const ArrayType *AT = S.Context.getAsArrayType(PType);
9482 if (!AT)
9483 return;
9484
9485 if (AT->getSizeModifier() != ArrayType::Star) {
9486 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
9487 return;
9488 }
9489
9490 S.Diag(Loc, diag::err_array_star_in_function_definition);
9491}
9492
Mike Stump0c2ec772010-01-21 03:59:47 +00009493/// CheckParmsForFunctionDef - Check that the parameters of the given
9494/// function are appropriate for the definition of a function. This
9495/// takes care of any checks that cannot be performed on the
9496/// declaration itself, e.g., that the types of each of the function
9497/// parameters are complete.
David Majnemer59f77922016-06-24 04:05:48 +00009498bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
Douglas Gregorb524d902010-11-01 18:37:59 +00009499 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00009500 bool HasInvalidParm = false;
David Majnemer59f77922016-06-24 04:05:48 +00009501 for (ParmVarDecl *Param : Parameters) {
Mike Stump0c2ec772010-01-21 03:59:47 +00009502 // C99 6.7.5.3p4: the parameters in a parameter type list in a
9503 // function declarator that is part of a function definition of
9504 // that function shall not have incomplete type.
9505 //
9506 // This is also C++ [dcl.fct]p6.
9507 if (!Param->isInvalidDecl() &&
9508 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00009509 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00009510 Param->setInvalidDecl();
9511 HasInvalidParm = true;
9512 }
9513
9514 // C99 6.9.1p5: If the declarator includes a parameter type list, the
9515 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00009516 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00009517 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00009518 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00009519 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00009520 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00009521
9522 // C99 6.7.5.3p12:
9523 // If the function declarator is not part of a definition of that
9524 // function, parameters may have incomplete type and may use the [*]
9525 // notation in their sequences of declarator specifiers to specify
9526 // variable length array types.
9527 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +00009528 // FIXME: This diagnostic should point the '[*]' if source-location
9529 // information is added for it.
9530 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00009531
9532 // MSVC destroys objects passed by value in the callee. Therefore a
9533 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00009534 // object's destructor. However, we don't perform any direct access check
9535 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00009536 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
9537 .getCXXABI()
9538 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00009539 if (!Param->isInvalidDecl()) {
9540 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
9541 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
9542 if (!ClassDecl->isInvalidDecl() &&
9543 !ClassDecl->hasIrrelevantDestructor() &&
9544 !ClassDecl->isDependentContext()) {
9545 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
9546 MarkFunctionReferenced(Param->getLocation(), Destructor);
9547 DiagnoseUseOfDecl(Destructor, Param->getLocation());
9548 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00009549 }
9550 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00009551 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009552
9553 // Parameters with the pass_object_size attribute only need to be marked
9554 // constant at function definitions. Because we lack information about
9555 // whether we're on a declaration or definition when we're instantiating the
9556 // attribute, we need to check for constness here.
9557 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
9558 if (!Param->getType().isConstQualified())
9559 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
9560 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +00009561 }
9562
9563 return HasInvalidParm;
9564}
John McCall2b5c1b22010-08-12 21:44:57 +00009565
9566/// CheckCastAlign - Implements -Wcast-align, which warns when a
9567/// pointer cast increases the alignment requirements.
9568void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
9569 // This is actually a lot of work to potentially be doing on every
9570 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009571 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00009572 return;
9573
9574 // Ignore dependent types.
9575 if (T->isDependentType() || Op->getType()->isDependentType())
9576 return;
9577
9578 // Require that the destination be a pointer type.
9579 const PointerType *DestPtr = T->getAs<PointerType>();
9580 if (!DestPtr) return;
9581
9582 // If the destination has alignment 1, we're done.
9583 QualType DestPointee = DestPtr->getPointeeType();
9584 if (DestPointee->isIncompleteType()) return;
9585 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
9586 if (DestAlign.isOne()) return;
9587
9588 // Require that the source be a pointer type.
9589 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
9590 if (!SrcPtr) return;
9591 QualType SrcPointee = SrcPtr->getPointeeType();
9592
9593 // Whitelist casts from cv void*. We already implicitly
9594 // whitelisted casts to cv void*, since they have alignment 1.
9595 // Also whitelist casts involving incomplete types, which implicitly
9596 // includes 'void'.
9597 if (SrcPointee->isIncompleteType()) return;
9598
9599 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
9600 if (SrcAlign >= DestAlign) return;
9601
9602 Diag(TRange.getBegin(), diag::warn_cast_align)
9603 << Op->getType() << T
9604 << static_cast<unsigned>(SrcAlign.getQuantity())
9605 << static_cast<unsigned>(DestAlign.getQuantity())
9606 << TRange << Op->getSourceRange();
9607}
9608
Chandler Carruth28389f02011-08-05 09:10:50 +00009609/// \brief Check whether this array fits the idiom of a size-one tail padded
9610/// array member of a struct.
9611///
9612/// We avoid emitting out-of-bounds access warnings for such arrays as they are
9613/// commonly used to emulate flexible arrays in C89 code.
Benjamin Kramer7320b992016-06-15 14:20:56 +00009614static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
Chandler Carruth28389f02011-08-05 09:10:50 +00009615 const NamedDecl *ND) {
9616 if (Size != 1 || !ND) return false;
9617
9618 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
9619 if (!FD) return false;
9620
9621 // Don't consider sizes resulting from macro expansions or template argument
9622 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00009623
9624 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00009625 while (TInfo) {
9626 TypeLoc TL = TInfo->getTypeLoc();
9627 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00009628 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
9629 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00009630 TInfo = TDL->getTypeSourceInfo();
9631 continue;
9632 }
David Blaikie6adc78e2013-02-18 22:06:02 +00009633 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
9634 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00009635 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
9636 return false;
9637 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00009638 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00009639 }
Chandler Carruth28389f02011-08-05 09:10:50 +00009640
9641 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00009642 if (!RD) return false;
9643 if (RD->isUnion()) return false;
9644 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
9645 if (!CRD->isStandardLayout()) return false;
9646 }
Chandler Carruth28389f02011-08-05 09:10:50 +00009647
Benjamin Kramer8c543672011-08-06 03:04:42 +00009648 // See if this is the last field decl in the record.
9649 const Decl *D = FD;
9650 while ((D = D->getNextDeclInContext()))
9651 if (isa<FieldDecl>(D))
9652 return false;
9653 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00009654}
9655
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009656void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009657 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00009658 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009659 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009660 if (IndexExpr->isValueDependent())
9661 return;
9662
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009663 const Type *EffectiveType =
9664 BaseExpr->getType()->getPointeeOrArrayElementType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009665 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009666 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009667 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009668 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00009669 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00009670
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009671 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +00009672 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +00009673 return;
Richard Smith13f67182011-12-16 19:31:14 +00009674 if (IndexNegated)
9675 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00009676
Craig Topperc3ec1492014-05-26 06:22:03 +00009677 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00009678 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
9679 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00009680 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00009681 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00009682
Ted Kremeneke4b316c2011-02-23 23:06:04 +00009683 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00009684 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00009685 if (!size.isStrictlyPositive())
9686 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009687
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009688 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
Nico Weber7c299802011-09-17 22:59:41 +00009689 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009690 // Make sure we're comparing apples to apples when comparing index to size
9691 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
9692 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00009693 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00009694 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009695 if (ptrarith_typesize != array_typesize) {
9696 // There's a cast to a different size type involved
9697 uint64_t ratio = array_typesize / ptrarith_typesize;
9698 // TODO: Be smarter about handling cases where array_typesize is not a
9699 // multiple of ptrarith_typesize
9700 if (ptrarith_typesize * ratio == array_typesize)
9701 size *= llvm::APInt(size.getBitWidth(), ratio);
9702 }
9703 }
9704
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009705 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009706 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00009707 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009708 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00009709
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009710 // For array subscripting the index must be less than size, but for pointer
9711 // arithmetic also allow the index (offset) to be equal to size since
9712 // computing the next address after the end of the array is legal and
9713 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009714 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00009715 return;
9716
9717 // Also don't warn for arrays of size 1 which are members of some
9718 // structure. These are often used to approximate flexible arrays in C89
9719 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009720 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00009721 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009722
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009723 // Suppress the warning if the subscript expression (as identified by the
9724 // ']' location) and the index expression are both from macro expansions
9725 // within a system header.
9726 if (ASE) {
9727 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
9728 ASE->getRBracketLoc());
9729 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
9730 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
9731 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00009732 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009733 return;
9734 }
9735 }
9736
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009737 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009738 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009739 DiagID = diag::warn_array_index_exceeds_bounds;
9740
9741 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
9742 PDiag(DiagID) << index.toString(10, true)
9743 << size.toString(10, true)
9744 << (unsigned)size.getLimitedValue(~0U)
9745 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009746 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009747 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009748 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009749 DiagID = diag::warn_ptr_arith_precedes_bounds;
9750 if (index.isNegative()) index = -index;
9751 }
9752
9753 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
9754 PDiag(DiagID) << index.toString(10, true)
9755 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00009756 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00009757
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00009758 if (!ND) {
9759 // Try harder to find a NamedDecl to point at in the note.
9760 while (const ArraySubscriptExpr *ASE =
9761 dyn_cast<ArraySubscriptExpr>(BaseExpr))
9762 BaseExpr = ASE->getBase()->IgnoreParenCasts();
9763 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
9764 ND = dyn_cast<NamedDecl>(DRE->getDecl());
9765 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
9766 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
9767 }
9768
Chandler Carruth1af88f12011-02-17 21:10:52 +00009769 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009770 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
9771 PDiag(diag::note_array_index_out_of_bounds)
9772 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00009773}
9774
Ted Kremenekdf26df72011-03-01 18:41:00 +00009775void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009776 int AllowOnePastEnd = 0;
9777 while (expr) {
9778 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00009779 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009780 case Stmt::ArraySubscriptExprClass: {
9781 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009782 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009783 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00009784 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009785 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +00009786 case Stmt::OMPArraySectionExprClass: {
9787 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
9788 if (ASE->getLowerBound())
9789 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
9790 /*ASE=*/nullptr, AllowOnePastEnd > 0);
9791 return;
9792 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009793 case Stmt::UnaryOperatorClass: {
9794 // Only unwrap the * and & unary operators
9795 const UnaryOperator *UO = cast<UnaryOperator>(expr);
9796 expr = UO->getSubExpr();
9797 switch (UO->getOpcode()) {
9798 case UO_AddrOf:
9799 AllowOnePastEnd++;
9800 break;
9801 case UO_Deref:
9802 AllowOnePastEnd--;
9803 break;
9804 default:
9805 return;
9806 }
9807 break;
9808 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00009809 case Stmt::ConditionalOperatorClass: {
9810 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
9811 if (const Expr *lhs = cond->getLHS())
9812 CheckArrayAccess(lhs);
9813 if (const Expr *rhs = cond->getRHS())
9814 CheckArrayAccess(rhs);
9815 return;
9816 }
9817 default:
9818 return;
9819 }
Peter Collingbourne91147592011-04-15 00:35:48 +00009820 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00009821}
John McCall31168b02011-06-15 23:02:42 +00009822
9823//===--- CHECK: Objective-C retain cycles ----------------------------------//
9824
9825namespace {
9826 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00009827 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00009828 VarDecl *Variable;
9829 SourceRange Range;
9830 SourceLocation Loc;
9831 bool Indirect;
9832
9833 void setLocsFrom(Expr *e) {
9834 Loc = e->getExprLoc();
9835 Range = e->getSourceRange();
9836 }
9837 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009838} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +00009839
9840/// Consider whether capturing the given variable can possibly lead to
9841/// a retain cycle.
9842static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00009843 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00009844 // lifetime. In MRR, it's captured strongly if the variable is
9845 // __block and has an appropriate type.
9846 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
9847 return false;
9848
9849 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009850 if (ref)
9851 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00009852 return true;
9853}
9854
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009855static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00009856 while (true) {
9857 e = e->IgnoreParens();
9858 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
9859 switch (cast->getCastKind()) {
9860 case CK_BitCast:
9861 case CK_LValueBitCast:
9862 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00009863 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00009864 e = cast->getSubExpr();
9865 continue;
9866
John McCall31168b02011-06-15 23:02:42 +00009867 default:
9868 return false;
9869 }
9870 }
9871
9872 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
9873 ObjCIvarDecl *ivar = ref->getDecl();
9874 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
9875 return false;
9876
9877 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009878 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00009879 return false;
9880
9881 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
9882 owner.Indirect = true;
9883 return true;
9884 }
9885
9886 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
9887 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
9888 if (!var) return false;
9889 return considerVariable(var, ref, owner);
9890 }
9891
John McCall31168b02011-06-15 23:02:42 +00009892 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
9893 if (member->isArrow()) return false;
9894
9895 // Don't count this as an indirect ownership.
9896 e = member->getBase();
9897 continue;
9898 }
9899
John McCallfe96e0b2011-11-06 09:01:30 +00009900 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
9901 // Only pay attention to pseudo-objects on property references.
9902 ObjCPropertyRefExpr *pre
9903 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
9904 ->IgnoreParens());
9905 if (!pre) return false;
9906 if (pre->isImplicitProperty()) return false;
9907 ObjCPropertyDecl *property = pre->getExplicitProperty();
9908 if (!property->isRetaining() &&
9909 !(property->getPropertyIvarDecl() &&
9910 property->getPropertyIvarDecl()->getType()
9911 .getObjCLifetime() == Qualifiers::OCL_Strong))
9912 return false;
9913
9914 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009915 if (pre->isSuperReceiver()) {
9916 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
9917 if (!owner.Variable)
9918 return false;
9919 owner.Loc = pre->getLocation();
9920 owner.Range = pre->getSourceRange();
9921 return true;
9922 }
John McCallfe96e0b2011-11-06 09:01:30 +00009923 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
9924 ->getSourceExpr());
9925 continue;
9926 }
9927
John McCall31168b02011-06-15 23:02:42 +00009928 // Array ivars?
9929
9930 return false;
9931 }
9932}
9933
9934namespace {
9935 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
9936 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
9937 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009938 Context(Context), Variable(variable), Capturer(nullptr),
9939 VarWillBeReased(false) {}
9940 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +00009941 VarDecl *Variable;
9942 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009943 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +00009944
9945 void VisitDeclRefExpr(DeclRefExpr *ref) {
9946 if (ref->getDecl() == Variable && !Capturer)
9947 Capturer = ref;
9948 }
9949
John McCall31168b02011-06-15 23:02:42 +00009950 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
9951 if (Capturer) return;
9952 Visit(ref->getBase());
9953 if (Capturer && ref->isFreeIvar())
9954 Capturer = ref;
9955 }
9956
9957 void VisitBlockExpr(BlockExpr *block) {
9958 // Look inside nested blocks
9959 if (block->getBlockDecl()->capturesVariable(Variable))
9960 Visit(block->getBlockDecl()->getBody());
9961 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00009962
9963 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
9964 if (Capturer) return;
9965 if (OVE->getSourceExpr())
9966 Visit(OVE->getSourceExpr());
9967 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009968 void VisitBinaryOperator(BinaryOperator *BinOp) {
9969 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
9970 return;
9971 Expr *LHS = BinOp->getLHS();
9972 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
9973 if (DRE->getDecl() != Variable)
9974 return;
9975 if (Expr *RHS = BinOp->getRHS()) {
9976 RHS = RHS->IgnoreParenCasts();
9977 llvm::APSInt Value;
9978 VarWillBeReased =
9979 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
9980 }
9981 }
9982 }
John McCall31168b02011-06-15 23:02:42 +00009983 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009984} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +00009985
9986/// Check whether the given argument is a block which captures a
9987/// variable.
9988static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
9989 assert(owner.Variable && owner.Loc.isValid());
9990
9991 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00009992
9993 // Look through [^{...} copy] and Block_copy(^{...}).
9994 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
9995 Selector Cmd = ME->getSelector();
9996 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
9997 e = ME->getInstanceReceiver();
9998 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +00009999 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +000010000 e = e->IgnoreParenCasts();
10001 }
10002 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
10003 if (CE->getNumArgs() == 1) {
10004 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +000010005 if (Fn) {
10006 const IdentifierInfo *FnI = Fn->getIdentifier();
10007 if (FnI && FnI->isStr("_Block_copy")) {
10008 e = CE->getArg(0)->IgnoreParenCasts();
10009 }
10010 }
Jordan Rose67e887c2012-09-17 17:54:30 +000010011 }
10012 }
10013
John McCall31168b02011-06-15 23:02:42 +000010014 BlockExpr *block = dyn_cast<BlockExpr>(e);
10015 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +000010016 return nullptr;
John McCall31168b02011-06-15 23:02:42 +000010017
10018 FindCaptureVisitor visitor(S.Context, owner.Variable);
10019 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010020 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +000010021}
10022
10023static void diagnoseRetainCycle(Sema &S, Expr *capturer,
10024 RetainCycleOwner &owner) {
10025 assert(capturer);
10026 assert(owner.Variable && owner.Loc.isValid());
10027
10028 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
10029 << owner.Variable << capturer->getSourceRange();
10030 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
10031 << owner.Indirect << owner.Range;
10032}
10033
10034/// Check for a keyword selector that starts with the word 'add' or
10035/// 'set'.
10036static bool isSetterLikeSelector(Selector sel) {
10037 if (sel.isUnarySelector()) return false;
10038
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010039 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +000010040 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +000010041 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +000010042 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +000010043 else if (str.startswith("add")) {
10044 // Specially whitelist 'addOperationWithBlock:'.
10045 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
10046 return false;
10047 str = str.substr(3);
10048 }
John McCall31168b02011-06-15 23:02:42 +000010049 else
10050 return false;
10051
10052 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +000010053 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +000010054}
10055
Benjamin Kramer3a743452015-03-09 15:03:32 +000010056static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
10057 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010058 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
10059 Message->getReceiverInterface(),
10060 NSAPI::ClassId_NSMutableArray);
10061 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010062 return None;
10063 }
10064
10065 Selector Sel = Message->getSelector();
10066
10067 Optional<NSAPI::NSArrayMethodKind> MKOpt =
10068 S.NSAPIObj->getNSArrayMethodKind(Sel);
10069 if (!MKOpt) {
10070 return None;
10071 }
10072
10073 NSAPI::NSArrayMethodKind MK = *MKOpt;
10074
10075 switch (MK) {
10076 case NSAPI::NSMutableArr_addObject:
10077 case NSAPI::NSMutableArr_insertObjectAtIndex:
10078 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
10079 return 0;
10080 case NSAPI::NSMutableArr_replaceObjectAtIndex:
10081 return 1;
10082
10083 default:
10084 return None;
10085 }
10086
10087 return None;
10088}
10089
10090static
10091Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
10092 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010093 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
10094 Message->getReceiverInterface(),
10095 NSAPI::ClassId_NSMutableDictionary);
10096 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010097 return None;
10098 }
10099
10100 Selector Sel = Message->getSelector();
10101
10102 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
10103 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
10104 if (!MKOpt) {
10105 return None;
10106 }
10107
10108 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
10109
10110 switch (MK) {
10111 case NSAPI::NSMutableDict_setObjectForKey:
10112 case NSAPI::NSMutableDict_setValueForKey:
10113 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
10114 return 0;
10115
10116 default:
10117 return None;
10118 }
10119
10120 return None;
10121}
10122
10123static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010124 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
10125 Message->getReceiverInterface(),
10126 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +000010127
Alex Denisov5dfac812015-08-06 04:51:14 +000010128 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
10129 Message->getReceiverInterface(),
10130 NSAPI::ClassId_NSMutableOrderedSet);
10131 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010132 return None;
10133 }
10134
10135 Selector Sel = Message->getSelector();
10136
10137 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
10138 if (!MKOpt) {
10139 return None;
10140 }
10141
10142 NSAPI::NSSetMethodKind MK = *MKOpt;
10143
10144 switch (MK) {
10145 case NSAPI::NSMutableSet_addObject:
10146 case NSAPI::NSOrderedSet_setObjectAtIndex:
10147 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
10148 case NSAPI::NSOrderedSet_insertObjectAtIndex:
10149 return 0;
10150 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
10151 return 1;
10152 }
10153
10154 return None;
10155}
10156
10157void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
10158 if (!Message->isInstanceMessage()) {
10159 return;
10160 }
10161
10162 Optional<int> ArgOpt;
10163
10164 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
10165 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
10166 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
10167 return;
10168 }
10169
10170 int ArgIndex = *ArgOpt;
10171
Alex Denisove1d882c2015-03-04 17:55:52 +000010172 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
10173 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
10174 Arg = OE->getSourceExpr()->IgnoreImpCasts();
10175 }
10176
Alex Denisov5dfac812015-08-06 04:51:14 +000010177 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010178 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010179 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010180 Diag(Message->getSourceRange().getBegin(),
10181 diag::warn_objc_circular_container)
Alex Denisov5dfac812015-08-06 04:51:14 +000010182 << ArgRE->getDecl()->getName() << StringRef("super");
Alex Denisove1d882c2015-03-04 17:55:52 +000010183 }
10184 }
Alex Denisov5dfac812015-08-06 04:51:14 +000010185 } else {
10186 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
10187
10188 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
10189 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
10190 }
10191
10192 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
10193 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
10194 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
10195 ValueDecl *Decl = ReceiverRE->getDecl();
10196 Diag(Message->getSourceRange().getBegin(),
10197 diag::warn_objc_circular_container)
10198 << Decl->getName() << Decl->getName();
10199 if (!ArgRE->isObjCSelfExpr()) {
10200 Diag(Decl->getLocation(),
10201 diag::note_objc_circular_container_declared_here)
10202 << Decl->getName();
10203 }
10204 }
10205 }
10206 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
10207 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
10208 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
10209 ObjCIvarDecl *Decl = IvarRE->getDecl();
10210 Diag(Message->getSourceRange().getBegin(),
10211 diag::warn_objc_circular_container)
10212 << Decl->getName() << Decl->getName();
10213 Diag(Decl->getLocation(),
10214 diag::note_objc_circular_container_declared_here)
10215 << Decl->getName();
10216 }
Alex Denisove1d882c2015-03-04 17:55:52 +000010217 }
10218 }
10219 }
Alex Denisove1d882c2015-03-04 17:55:52 +000010220}
10221
John McCall31168b02011-06-15 23:02:42 +000010222/// Check a message send to see if it's likely to cause a retain cycle.
10223void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
10224 // Only check instance methods whose selector looks like a setter.
10225 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
10226 return;
10227
10228 // Try to find a variable that the receiver is strongly owned by.
10229 RetainCycleOwner owner;
10230 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010231 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +000010232 return;
10233 } else {
10234 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
10235 owner.Variable = getCurMethodDecl()->getSelfDecl();
10236 owner.Loc = msg->getSuperLoc();
10237 owner.Range = msg->getSuperLoc();
10238 }
10239
10240 // Check whether the receiver is captured by any of the arguments.
10241 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
10242 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
10243 return diagnoseRetainCycle(*this, capturer, owner);
10244}
10245
10246/// Check a property assign to see if it's likely to cause a retain cycle.
10247void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
10248 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010249 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +000010250 return;
10251
10252 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
10253 diagnoseRetainCycle(*this, capturer, owner);
10254}
10255
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000010256void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
10257 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +000010258 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000010259 return;
10260
10261 // Because we don't have an expression for the variable, we have to set the
10262 // location explicitly here.
10263 Owner.Loc = Var->getLocation();
10264 Owner.Range = Var->getSourceRange();
10265
10266 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
10267 diagnoseRetainCycle(*this, Capturer, Owner);
10268}
10269
Ted Kremenek9304da92012-12-21 08:04:28 +000010270static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
10271 Expr *RHS, bool isProperty) {
10272 // Check if RHS is an Objective-C object literal, which also can get
10273 // immediately zapped in a weak reference. Note that we explicitly
10274 // allow ObjCStringLiterals, since those are designed to never really die.
10275 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000010276
Ted Kremenek64873352012-12-21 22:46:35 +000010277 // This enum needs to match with the 'select' in
10278 // warn_objc_arc_literal_assign (off-by-1).
10279 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
10280 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
10281 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000010282
10283 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +000010284 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +000010285 << (isProperty ? 0 : 1)
10286 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000010287
10288 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +000010289}
10290
Ted Kremenekc1f014a2012-12-21 19:45:30 +000010291static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
10292 Qualifiers::ObjCLifetime LT,
10293 Expr *RHS, bool isProperty) {
10294 // Strip off any implicit cast added to get to the one ARC-specific.
10295 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
10296 if (cast->getCastKind() == CK_ARCConsumeObject) {
10297 S.Diag(Loc, diag::warn_arc_retained_assign)
10298 << (LT == Qualifiers::OCL_ExplicitNone)
10299 << (isProperty ? 0 : 1)
10300 << RHS->getSourceRange();
10301 return true;
10302 }
10303 RHS = cast->getSubExpr();
10304 }
10305
10306 if (LT == Qualifiers::OCL_Weak &&
10307 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
10308 return true;
10309
10310 return false;
10311}
10312
Ted Kremenekb36234d2012-12-21 08:04:20 +000010313bool Sema::checkUnsafeAssigns(SourceLocation Loc,
10314 QualType LHS, Expr *RHS) {
10315 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
10316
10317 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
10318 return false;
10319
10320 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
10321 return true;
10322
10323 return false;
10324}
10325
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010326void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
10327 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010328 QualType LHSType;
10329 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +000010330 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010331 ObjCPropertyRefExpr *PRE
10332 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
10333 if (PRE && !PRE->isImplicitProperty()) {
10334 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
10335 if (PD)
10336 LHSType = PD->getType();
10337 }
10338
10339 if (LHSType.isNull())
10340 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +000010341
10342 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
10343
10344 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010345 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +000010346 getCurFunction()->markSafeWeakUse(LHS);
10347 }
10348
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010349 if (checkUnsafeAssigns(Loc, LHSType, RHS))
10350 return;
Jordan Rose657b5f42012-09-28 22:21:35 +000010351
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010352 // FIXME. Check for other life times.
10353 if (LT != Qualifiers::OCL_None)
10354 return;
10355
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010356 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010357 if (PRE->isImplicitProperty())
10358 return;
10359 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
10360 if (!PD)
10361 return;
10362
Bill Wendling44426052012-12-20 19:22:21 +000010363 unsigned Attributes = PD->getPropertyAttributes();
10364 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010365 // when 'assign' attribute was not explicitly specified
10366 // by user, ignore it and rely on property type itself
10367 // for lifetime info.
10368 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
10369 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
10370 LHSType->isObjCRetainableType())
10371 return;
10372
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010373 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +000010374 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010375 Diag(Loc, diag::warn_arc_retained_property_assign)
10376 << RHS->getSourceRange();
10377 return;
10378 }
10379 RHS = cast->getSubExpr();
10380 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010381 }
Bill Wendling44426052012-12-20 19:22:21 +000010382 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +000010383 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
10384 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +000010385 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010386 }
10387}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010388
10389//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
10390
10391namespace {
10392bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
10393 SourceLocation StmtLoc,
10394 const NullStmt *Body) {
10395 // Do not warn if the body is a macro that expands to nothing, e.g:
10396 //
10397 // #define CALL(x)
10398 // if (condition)
10399 // CALL(0);
10400 //
10401 if (Body->hasLeadingEmptyMacro())
10402 return false;
10403
10404 // Get line numbers of statement and body.
10405 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +000010406 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010407 &StmtLineInvalid);
10408 if (StmtLineInvalid)
10409 return false;
10410
10411 bool BodyLineInvalid;
10412 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
10413 &BodyLineInvalid);
10414 if (BodyLineInvalid)
10415 return false;
10416
10417 // Warn if null statement and body are on the same line.
10418 if (StmtLine != BodyLine)
10419 return false;
10420
10421 return true;
10422}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010423} // end anonymous namespace
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010424
10425void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
10426 const Stmt *Body,
10427 unsigned DiagID) {
10428 // Since this is a syntactic check, don't emit diagnostic for template
10429 // instantiations, this just adds noise.
10430 if (CurrentInstantiationScope)
10431 return;
10432
10433 // The body should be a null statement.
10434 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
10435 if (!NBody)
10436 return;
10437
10438 // Do the usual checks.
10439 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
10440 return;
10441
10442 Diag(NBody->getSemiLoc(), DiagID);
10443 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
10444}
10445
10446void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
10447 const Stmt *PossibleBody) {
10448 assert(!CurrentInstantiationScope); // Ensured by caller
10449
10450 SourceLocation StmtLoc;
10451 const Stmt *Body;
10452 unsigned DiagID;
10453 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
10454 StmtLoc = FS->getRParenLoc();
10455 Body = FS->getBody();
10456 DiagID = diag::warn_empty_for_body;
10457 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
10458 StmtLoc = WS->getCond()->getSourceRange().getEnd();
10459 Body = WS->getBody();
10460 DiagID = diag::warn_empty_while_body;
10461 } else
10462 return; // Neither `for' nor `while'.
10463
10464 // The body should be a null statement.
10465 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
10466 if (!NBody)
10467 return;
10468
10469 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010470 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010471 return;
10472
10473 // Do the usual checks.
10474 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
10475 return;
10476
10477 // `for(...);' and `while(...);' are popular idioms, so in order to keep
10478 // noise level low, emit diagnostics only if for/while is followed by a
10479 // CompoundStmt, e.g.:
10480 // for (int i = 0; i < n; i++);
10481 // {
10482 // a(i);
10483 // }
10484 // or if for/while is followed by a statement with more indentation
10485 // than for/while itself:
10486 // for (int i = 0; i < n; i++);
10487 // a(i);
10488 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
10489 if (!ProbableTypo) {
10490 bool BodyColInvalid;
10491 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
10492 PossibleBody->getLocStart(),
10493 &BodyColInvalid);
10494 if (BodyColInvalid)
10495 return;
10496
10497 bool StmtColInvalid;
10498 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
10499 S->getLocStart(),
10500 &StmtColInvalid);
10501 if (StmtColInvalid)
10502 return;
10503
10504 if (BodyCol > StmtCol)
10505 ProbableTypo = true;
10506 }
10507
10508 if (ProbableTypo) {
10509 Diag(NBody->getSemiLoc(), DiagID);
10510 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
10511 }
10512}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010513
Richard Trieu36d0b2b2015-01-13 02:32:02 +000010514//===--- CHECK: Warn on self move with std::move. -------------------------===//
10515
10516/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
10517void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
10518 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +000010519 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
10520 return;
10521
10522 if (!ActiveTemplateInstantiations.empty())
10523 return;
10524
10525 // Strip parens and casts away.
10526 LHSExpr = LHSExpr->IgnoreParenImpCasts();
10527 RHSExpr = RHSExpr->IgnoreParenImpCasts();
10528
10529 // Check for a call expression
10530 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
10531 if (!CE || CE->getNumArgs() != 1)
10532 return;
10533
10534 // Check for a call to std::move
10535 const FunctionDecl *FD = CE->getDirectCallee();
10536 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
10537 !FD->getIdentifier()->isStr("move"))
10538 return;
10539
10540 // Get argument from std::move
10541 RHSExpr = CE->getArg(0);
10542
10543 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
10544 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
10545
10546 // Two DeclRefExpr's, check that the decls are the same.
10547 if (LHSDeclRef && RHSDeclRef) {
10548 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
10549 return;
10550 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
10551 RHSDeclRef->getDecl()->getCanonicalDecl())
10552 return;
10553
10554 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10555 << LHSExpr->getSourceRange()
10556 << RHSExpr->getSourceRange();
10557 return;
10558 }
10559
10560 // Member variables require a different approach to check for self moves.
10561 // MemberExpr's are the same if every nested MemberExpr refers to the same
10562 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
10563 // the base Expr's are CXXThisExpr's.
10564 const Expr *LHSBase = LHSExpr;
10565 const Expr *RHSBase = RHSExpr;
10566 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
10567 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
10568 if (!LHSME || !RHSME)
10569 return;
10570
10571 while (LHSME && RHSME) {
10572 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
10573 RHSME->getMemberDecl()->getCanonicalDecl())
10574 return;
10575
10576 LHSBase = LHSME->getBase();
10577 RHSBase = RHSME->getBase();
10578 LHSME = dyn_cast<MemberExpr>(LHSBase);
10579 RHSME = dyn_cast<MemberExpr>(RHSBase);
10580 }
10581
10582 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
10583 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
10584 if (LHSDeclRef && RHSDeclRef) {
10585 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
10586 return;
10587 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
10588 RHSDeclRef->getDecl()->getCanonicalDecl())
10589 return;
10590
10591 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10592 << LHSExpr->getSourceRange()
10593 << RHSExpr->getSourceRange();
10594 return;
10595 }
10596
10597 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
10598 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10599 << LHSExpr->getSourceRange()
10600 << RHSExpr->getSourceRange();
10601}
10602
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010603//===--- Layout compatibility ----------------------------------------------//
10604
10605namespace {
10606
10607bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
10608
10609/// \brief Check if two enumeration types are layout-compatible.
10610bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
10611 // C++11 [dcl.enum] p8:
10612 // Two enumeration types are layout-compatible if they have the same
10613 // underlying type.
10614 return ED1->isComplete() && ED2->isComplete() &&
10615 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
10616}
10617
10618/// \brief Check if two fields are layout-compatible.
10619bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
10620 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
10621 return false;
10622
10623 if (Field1->isBitField() != Field2->isBitField())
10624 return false;
10625
10626 if (Field1->isBitField()) {
10627 // Make sure that the bit-fields are the same length.
10628 unsigned Bits1 = Field1->getBitWidthValue(C);
10629 unsigned Bits2 = Field2->getBitWidthValue(C);
10630
10631 if (Bits1 != Bits2)
10632 return false;
10633 }
10634
10635 return true;
10636}
10637
10638/// \brief Check if two standard-layout structs are layout-compatible.
10639/// (C++11 [class.mem] p17)
10640bool isLayoutCompatibleStruct(ASTContext &C,
10641 RecordDecl *RD1,
10642 RecordDecl *RD2) {
10643 // If both records are C++ classes, check that base classes match.
10644 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
10645 // If one of records is a CXXRecordDecl we are in C++ mode,
10646 // thus the other one is a CXXRecordDecl, too.
10647 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
10648 // Check number of base classes.
10649 if (D1CXX->getNumBases() != D2CXX->getNumBases())
10650 return false;
10651
10652 // Check the base classes.
10653 for (CXXRecordDecl::base_class_const_iterator
10654 Base1 = D1CXX->bases_begin(),
10655 BaseEnd1 = D1CXX->bases_end(),
10656 Base2 = D2CXX->bases_begin();
10657 Base1 != BaseEnd1;
10658 ++Base1, ++Base2) {
10659 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
10660 return false;
10661 }
10662 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
10663 // If only RD2 is a C++ class, it should have zero base classes.
10664 if (D2CXX->getNumBases() > 0)
10665 return false;
10666 }
10667
10668 // Check the fields.
10669 RecordDecl::field_iterator Field2 = RD2->field_begin(),
10670 Field2End = RD2->field_end(),
10671 Field1 = RD1->field_begin(),
10672 Field1End = RD1->field_end();
10673 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
10674 if (!isLayoutCompatible(C, *Field1, *Field2))
10675 return false;
10676 }
10677 if (Field1 != Field1End || Field2 != Field2End)
10678 return false;
10679
10680 return true;
10681}
10682
10683/// \brief Check if two standard-layout unions are layout-compatible.
10684/// (C++11 [class.mem] p18)
10685bool isLayoutCompatibleUnion(ASTContext &C,
10686 RecordDecl *RD1,
10687 RecordDecl *RD2) {
10688 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010689 for (auto *Field2 : RD2->fields())
10690 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010691
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010692 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010693 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
10694 I = UnmatchedFields.begin(),
10695 E = UnmatchedFields.end();
10696
10697 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010698 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010699 bool Result = UnmatchedFields.erase(*I);
10700 (void) Result;
10701 assert(Result);
10702 break;
10703 }
10704 }
10705 if (I == E)
10706 return false;
10707 }
10708
10709 return UnmatchedFields.empty();
10710}
10711
10712bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
10713 if (RD1->isUnion() != RD2->isUnion())
10714 return false;
10715
10716 if (RD1->isUnion())
10717 return isLayoutCompatibleUnion(C, RD1, RD2);
10718 else
10719 return isLayoutCompatibleStruct(C, RD1, RD2);
10720}
10721
10722/// \brief Check if two types are layout-compatible in C++11 sense.
10723bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
10724 if (T1.isNull() || T2.isNull())
10725 return false;
10726
10727 // C++11 [basic.types] p11:
10728 // If two types T1 and T2 are the same type, then T1 and T2 are
10729 // layout-compatible types.
10730 if (C.hasSameType(T1, T2))
10731 return true;
10732
10733 T1 = T1.getCanonicalType().getUnqualifiedType();
10734 T2 = T2.getCanonicalType().getUnqualifiedType();
10735
10736 const Type::TypeClass TC1 = T1->getTypeClass();
10737 const Type::TypeClass TC2 = T2->getTypeClass();
10738
10739 if (TC1 != TC2)
10740 return false;
10741
10742 if (TC1 == Type::Enum) {
10743 return isLayoutCompatible(C,
10744 cast<EnumType>(T1)->getDecl(),
10745 cast<EnumType>(T2)->getDecl());
10746 } else if (TC1 == Type::Record) {
10747 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
10748 return false;
10749
10750 return isLayoutCompatible(C,
10751 cast<RecordType>(T1)->getDecl(),
10752 cast<RecordType>(T2)->getDecl());
10753 }
10754
10755 return false;
10756}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010757} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010758
10759//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
10760
10761namespace {
10762/// \brief Given a type tag expression find the type tag itself.
10763///
10764/// \param TypeExpr Type tag expression, as it appears in user's code.
10765///
10766/// \param VD Declaration of an identifier that appears in a type tag.
10767///
10768/// \param MagicValue Type tag magic value.
10769bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
10770 const ValueDecl **VD, uint64_t *MagicValue) {
10771 while(true) {
10772 if (!TypeExpr)
10773 return false;
10774
10775 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
10776
10777 switch (TypeExpr->getStmtClass()) {
10778 case Stmt::UnaryOperatorClass: {
10779 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
10780 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
10781 TypeExpr = UO->getSubExpr();
10782 continue;
10783 }
10784 return false;
10785 }
10786
10787 case Stmt::DeclRefExprClass: {
10788 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
10789 *VD = DRE->getDecl();
10790 return true;
10791 }
10792
10793 case Stmt::IntegerLiteralClass: {
10794 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
10795 llvm::APInt MagicValueAPInt = IL->getValue();
10796 if (MagicValueAPInt.getActiveBits() <= 64) {
10797 *MagicValue = MagicValueAPInt.getZExtValue();
10798 return true;
10799 } else
10800 return false;
10801 }
10802
10803 case Stmt::BinaryConditionalOperatorClass:
10804 case Stmt::ConditionalOperatorClass: {
10805 const AbstractConditionalOperator *ACO =
10806 cast<AbstractConditionalOperator>(TypeExpr);
10807 bool Result;
10808 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
10809 if (Result)
10810 TypeExpr = ACO->getTrueExpr();
10811 else
10812 TypeExpr = ACO->getFalseExpr();
10813 continue;
10814 }
10815 return false;
10816 }
10817
10818 case Stmt::BinaryOperatorClass: {
10819 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
10820 if (BO->getOpcode() == BO_Comma) {
10821 TypeExpr = BO->getRHS();
10822 continue;
10823 }
10824 return false;
10825 }
10826
10827 default:
10828 return false;
10829 }
10830 }
10831}
10832
10833/// \brief Retrieve the C type corresponding to type tag TypeExpr.
10834///
10835/// \param TypeExpr Expression that specifies a type tag.
10836///
10837/// \param MagicValues Registered magic values.
10838///
10839/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
10840/// kind.
10841///
10842/// \param TypeInfo Information about the corresponding C type.
10843///
10844/// \returns true if the corresponding C type was found.
10845bool GetMatchingCType(
10846 const IdentifierInfo *ArgumentKind,
10847 const Expr *TypeExpr, const ASTContext &Ctx,
10848 const llvm::DenseMap<Sema::TypeTagMagicValue,
10849 Sema::TypeTagData> *MagicValues,
10850 bool &FoundWrongKind,
10851 Sema::TypeTagData &TypeInfo) {
10852 FoundWrongKind = false;
10853
10854 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000010855 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010856
10857 uint64_t MagicValue;
10858
10859 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
10860 return false;
10861
10862 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000010863 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010864 if (I->getArgumentKind() != ArgumentKind) {
10865 FoundWrongKind = true;
10866 return false;
10867 }
10868 TypeInfo.Type = I->getMatchingCType();
10869 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
10870 TypeInfo.MustBeNull = I->getMustBeNull();
10871 return true;
10872 }
10873 return false;
10874 }
10875
10876 if (!MagicValues)
10877 return false;
10878
10879 llvm::DenseMap<Sema::TypeTagMagicValue,
10880 Sema::TypeTagData>::const_iterator I =
10881 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
10882 if (I == MagicValues->end())
10883 return false;
10884
10885 TypeInfo = I->second;
10886 return true;
10887}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010888} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010889
10890void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
10891 uint64_t MagicValue, QualType Type,
10892 bool LayoutCompatible,
10893 bool MustBeNull) {
10894 if (!TypeTagForDatatypeMagicValues)
10895 TypeTagForDatatypeMagicValues.reset(
10896 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
10897
10898 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
10899 (*TypeTagForDatatypeMagicValues)[Magic] =
10900 TypeTagData(Type, LayoutCompatible, MustBeNull);
10901}
10902
10903namespace {
10904bool IsSameCharType(QualType T1, QualType T2) {
10905 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
10906 if (!BT1)
10907 return false;
10908
10909 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
10910 if (!BT2)
10911 return false;
10912
10913 BuiltinType::Kind T1Kind = BT1->getKind();
10914 BuiltinType::Kind T2Kind = BT2->getKind();
10915
10916 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
10917 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
10918 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
10919 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
10920}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010921} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010922
10923void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
10924 const Expr * const *ExprArgs) {
10925 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
10926 bool IsPointerAttr = Attr->getIsPointer();
10927
10928 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
10929 bool FoundWrongKind;
10930 TypeTagData TypeInfo;
10931 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
10932 TypeTagForDatatypeMagicValues.get(),
10933 FoundWrongKind, TypeInfo)) {
10934 if (FoundWrongKind)
10935 Diag(TypeTagExpr->getExprLoc(),
10936 diag::warn_type_tag_for_datatype_wrong_kind)
10937 << TypeTagExpr->getSourceRange();
10938 return;
10939 }
10940
10941 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
10942 if (IsPointerAttr) {
10943 // Skip implicit cast of pointer to `void *' (as a function argument).
10944 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000010945 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000010946 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010947 ArgumentExpr = ICE->getSubExpr();
10948 }
10949 QualType ArgumentType = ArgumentExpr->getType();
10950
10951 // Passing a `void*' pointer shouldn't trigger a warning.
10952 if (IsPointerAttr && ArgumentType->isVoidPointerType())
10953 return;
10954
10955 if (TypeInfo.MustBeNull) {
10956 // Type tag with matching void type requires a null pointer.
10957 if (!ArgumentExpr->isNullPointerConstant(Context,
10958 Expr::NPC_ValueDependentIsNotNull)) {
10959 Diag(ArgumentExpr->getExprLoc(),
10960 diag::warn_type_safety_null_pointer_required)
10961 << ArgumentKind->getName()
10962 << ArgumentExpr->getSourceRange()
10963 << TypeTagExpr->getSourceRange();
10964 }
10965 return;
10966 }
10967
10968 QualType RequiredType = TypeInfo.Type;
10969 if (IsPointerAttr)
10970 RequiredType = Context.getPointerType(RequiredType);
10971
10972 bool mismatch = false;
10973 if (!TypeInfo.LayoutCompatible) {
10974 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
10975
10976 // C++11 [basic.fundamental] p1:
10977 // Plain char, signed char, and unsigned char are three distinct types.
10978 //
10979 // But we treat plain `char' as equivalent to `signed char' or `unsigned
10980 // char' depending on the current char signedness mode.
10981 if (mismatch)
10982 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
10983 RequiredType->getPointeeType())) ||
10984 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
10985 mismatch = false;
10986 } else
10987 if (IsPointerAttr)
10988 mismatch = !isLayoutCompatible(Context,
10989 ArgumentType->getPointeeType(),
10990 RequiredType->getPointeeType());
10991 else
10992 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
10993
10994 if (mismatch)
10995 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000010996 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010997 << TypeInfo.LayoutCompatible << RequiredType
10998 << ArgumentExpr->getSourceRange()
10999 << TypeTagExpr->getSourceRange();
11000}