blob: 7a99fc8383021e427315d7e0c152fe4e3540f6a6 [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 Topper39c87102016-05-18 03:18:12 +00001600 case X86::BI__builtin_ia32_extractf64x4_mask:
1601 case X86::BI__builtin_ia32_extracti64x4_mask:
1602 case X86::BI__builtin_ia32_extractf32x8_mask:
1603 case X86::BI__builtin_ia32_extracti32x8_mask:
1604 case X86::BI__builtin_ia32_extractf64x2_256_mask:
1605 case X86::BI__builtin_ia32_extracti64x2_256_mask:
1606 case X86::BI__builtin_ia32_extractf32x4_256_mask:
1607 case X86::BI__builtin_ia32_extracti32x4_256_mask:
1608 i = 1; l = 0; u = 1;
1609 break;
Richard Trieucc3949d2016-02-18 22:34:54 +00001610 case X86::BI_mm_prefetch:
Craig Topper39c87102016-05-18 03:18:12 +00001611 case X86::BI__builtin_ia32_extractf32x4_mask:
1612 case X86::BI__builtin_ia32_extracti32x4_mask:
Craig Topper39c87102016-05-18 03:18:12 +00001613 case X86::BI__builtin_ia32_extractf64x2_512_mask:
1614 case X86::BI__builtin_ia32_extracti64x2_512_mask:
1615 i = 1; l = 0; u = 3;
1616 break;
1617 case X86::BI__builtin_ia32_insertf32x8_mask:
1618 case X86::BI__builtin_ia32_inserti32x8_mask:
1619 case X86::BI__builtin_ia32_insertf64x4_mask:
1620 case X86::BI__builtin_ia32_inserti64x4_mask:
1621 case X86::BI__builtin_ia32_insertf64x2_256_mask:
1622 case X86::BI__builtin_ia32_inserti64x2_256_mask:
1623 case X86::BI__builtin_ia32_insertf32x4_256_mask:
1624 case X86::BI__builtin_ia32_inserti32x4_256_mask:
1625 i = 2; l = 0; u = 1;
Richard Trieucc3949d2016-02-18 22:34:54 +00001626 break;
1627 case X86::BI__builtin_ia32_sha1rnds4:
Craig Topper39c87102016-05-18 03:18:12 +00001628 case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
1629 case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
1630 case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
1631 case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00001632 case X86::BI__builtin_ia32_insertf64x2_512_mask:
1633 case X86::BI__builtin_ia32_inserti64x2_512_mask:
1634 case X86::BI__builtin_ia32_insertf32x4_mask:
1635 case X86::BI__builtin_ia32_inserti32x4_mask:
1636 i = 2; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00001637 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00001638 case X86::BI__builtin_ia32_vpermil2pd:
1639 case X86::BI__builtin_ia32_vpermil2pd256:
1640 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00001641 case X86::BI__builtin_ia32_vpermil2ps256:
Craig Topper39c87102016-05-18 03:18:12 +00001642 i = 3; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00001643 break;
Craig Topper95b0d732015-01-25 23:30:05 +00001644 case X86::BI__builtin_ia32_cmpb128_mask:
1645 case X86::BI__builtin_ia32_cmpw128_mask:
1646 case X86::BI__builtin_ia32_cmpd128_mask:
1647 case X86::BI__builtin_ia32_cmpq128_mask:
1648 case X86::BI__builtin_ia32_cmpb256_mask:
1649 case X86::BI__builtin_ia32_cmpw256_mask:
1650 case X86::BI__builtin_ia32_cmpd256_mask:
1651 case X86::BI__builtin_ia32_cmpq256_mask:
1652 case X86::BI__builtin_ia32_cmpb512_mask:
1653 case X86::BI__builtin_ia32_cmpw512_mask:
1654 case X86::BI__builtin_ia32_cmpd512_mask:
1655 case X86::BI__builtin_ia32_cmpq512_mask:
1656 case X86::BI__builtin_ia32_ucmpb128_mask:
1657 case X86::BI__builtin_ia32_ucmpw128_mask:
1658 case X86::BI__builtin_ia32_ucmpd128_mask:
1659 case X86::BI__builtin_ia32_ucmpq128_mask:
1660 case X86::BI__builtin_ia32_ucmpb256_mask:
1661 case X86::BI__builtin_ia32_ucmpw256_mask:
1662 case X86::BI__builtin_ia32_ucmpd256_mask:
1663 case X86::BI__builtin_ia32_ucmpq256_mask:
1664 case X86::BI__builtin_ia32_ucmpb512_mask:
1665 case X86::BI__builtin_ia32_ucmpw512_mask:
1666 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00001667 case X86::BI__builtin_ia32_ucmpq512_mask:
Craig Topper8dd7d0d2015-02-13 06:04:48 +00001668 case X86::BI__builtin_ia32_vpcomub:
1669 case X86::BI__builtin_ia32_vpcomuw:
1670 case X86::BI__builtin_ia32_vpcomud:
1671 case X86::BI__builtin_ia32_vpcomuq:
1672 case X86::BI__builtin_ia32_vpcomb:
1673 case X86::BI__builtin_ia32_vpcomw:
1674 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00001675 case X86::BI__builtin_ia32_vpcomq:
Craig Topper39c87102016-05-18 03:18:12 +00001676 i = 2; l = 0; u = 7;
1677 break;
1678 case X86::BI__builtin_ia32_roundps:
1679 case X86::BI__builtin_ia32_roundpd:
1680 case X86::BI__builtin_ia32_roundps256:
1681 case X86::BI__builtin_ia32_roundpd256:
Craig Topper39c87102016-05-18 03:18:12 +00001682 i = 1; l = 0; u = 15;
1683 break;
1684 case X86::BI__builtin_ia32_roundss:
1685 case X86::BI__builtin_ia32_roundsd:
1686 case X86::BI__builtin_ia32_rangepd128_mask:
1687 case X86::BI__builtin_ia32_rangepd256_mask:
1688 case X86::BI__builtin_ia32_rangepd512_mask:
1689 case X86::BI__builtin_ia32_rangeps128_mask:
1690 case X86::BI__builtin_ia32_rangeps256_mask:
1691 case X86::BI__builtin_ia32_rangeps512_mask:
1692 case X86::BI__builtin_ia32_getmantsd_round_mask:
1693 case X86::BI__builtin_ia32_getmantss_round_mask:
Craig Topper39c87102016-05-18 03:18:12 +00001694 i = 2; l = 0; u = 15;
1695 break;
1696 case X86::BI__builtin_ia32_cmpps:
1697 case X86::BI__builtin_ia32_cmpss:
1698 case X86::BI__builtin_ia32_cmppd:
1699 case X86::BI__builtin_ia32_cmpsd:
1700 case X86::BI__builtin_ia32_cmpps256:
1701 case X86::BI__builtin_ia32_cmppd256:
1702 case X86::BI__builtin_ia32_cmpps128_mask:
1703 case X86::BI__builtin_ia32_cmppd128_mask:
1704 case X86::BI__builtin_ia32_cmpps256_mask:
1705 case X86::BI__builtin_ia32_cmppd256_mask:
1706 case X86::BI__builtin_ia32_cmpps512_mask:
1707 case X86::BI__builtin_ia32_cmppd512_mask:
1708 case X86::BI__builtin_ia32_cmpsd_mask:
1709 case X86::BI__builtin_ia32_cmpss_mask:
1710 i = 2; l = 0; u = 31;
1711 break;
1712 case X86::BI__builtin_ia32_xabort:
1713 i = 0; l = -128; u = 255;
1714 break;
1715 case X86::BI__builtin_ia32_pshufw:
1716 case X86::BI__builtin_ia32_aeskeygenassist128:
1717 i = 1; l = -128; u = 255;
1718 break;
1719 case X86::BI__builtin_ia32_vcvtps2ph:
1720 case X86::BI__builtin_ia32_vcvtps2ph256:
Craig Topper39c87102016-05-18 03:18:12 +00001721 case X86::BI__builtin_ia32_rndscaleps_128_mask:
1722 case X86::BI__builtin_ia32_rndscalepd_128_mask:
1723 case X86::BI__builtin_ia32_rndscaleps_256_mask:
1724 case X86::BI__builtin_ia32_rndscalepd_256_mask:
1725 case X86::BI__builtin_ia32_rndscaleps_mask:
1726 case X86::BI__builtin_ia32_rndscalepd_mask:
1727 case X86::BI__builtin_ia32_reducepd128_mask:
1728 case X86::BI__builtin_ia32_reducepd256_mask:
1729 case X86::BI__builtin_ia32_reducepd512_mask:
1730 case X86::BI__builtin_ia32_reduceps128_mask:
1731 case X86::BI__builtin_ia32_reduceps256_mask:
1732 case X86::BI__builtin_ia32_reduceps512_mask:
1733 case X86::BI__builtin_ia32_prold512_mask:
1734 case X86::BI__builtin_ia32_prolq512_mask:
1735 case X86::BI__builtin_ia32_prold128_mask:
1736 case X86::BI__builtin_ia32_prold256_mask:
1737 case X86::BI__builtin_ia32_prolq128_mask:
1738 case X86::BI__builtin_ia32_prolq256_mask:
1739 case X86::BI__builtin_ia32_prord128_mask:
1740 case X86::BI__builtin_ia32_prord256_mask:
1741 case X86::BI__builtin_ia32_prorq128_mask:
1742 case X86::BI__builtin_ia32_prorq256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00001743 case X86::BI__builtin_ia32_psllwi512_mask:
1744 case X86::BI__builtin_ia32_psllwi128_mask:
1745 case X86::BI__builtin_ia32_psllwi256_mask:
1746 case X86::BI__builtin_ia32_psrldi128_mask:
1747 case X86::BI__builtin_ia32_psrldi256_mask:
1748 case X86::BI__builtin_ia32_psrldi512_mask:
1749 case X86::BI__builtin_ia32_psrlqi128_mask:
1750 case X86::BI__builtin_ia32_psrlqi256_mask:
1751 case X86::BI__builtin_ia32_psrlqi512_mask:
1752 case X86::BI__builtin_ia32_psrawi512_mask:
1753 case X86::BI__builtin_ia32_psrawi128_mask:
1754 case X86::BI__builtin_ia32_psrawi256_mask:
1755 case X86::BI__builtin_ia32_psrlwi512_mask:
1756 case X86::BI__builtin_ia32_psrlwi128_mask:
1757 case X86::BI__builtin_ia32_psrlwi256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00001758 case X86::BI__builtin_ia32_psradi128_mask:
1759 case X86::BI__builtin_ia32_psradi256_mask:
1760 case X86::BI__builtin_ia32_psradi512_mask:
1761 case X86::BI__builtin_ia32_psraqi128_mask:
1762 case X86::BI__builtin_ia32_psraqi256_mask:
1763 case X86::BI__builtin_ia32_psraqi512_mask:
1764 case X86::BI__builtin_ia32_pslldi128_mask:
1765 case X86::BI__builtin_ia32_pslldi256_mask:
1766 case X86::BI__builtin_ia32_pslldi512_mask:
1767 case X86::BI__builtin_ia32_psllqi128_mask:
1768 case X86::BI__builtin_ia32_psllqi256_mask:
1769 case X86::BI__builtin_ia32_psllqi512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00001770 case X86::BI__builtin_ia32_fpclasspd128_mask:
1771 case X86::BI__builtin_ia32_fpclasspd256_mask:
1772 case X86::BI__builtin_ia32_fpclassps128_mask:
1773 case X86::BI__builtin_ia32_fpclassps256_mask:
1774 case X86::BI__builtin_ia32_fpclassps512_mask:
1775 case X86::BI__builtin_ia32_fpclasspd512_mask:
1776 case X86::BI__builtin_ia32_fpclasssd_mask:
1777 case X86::BI__builtin_ia32_fpclassss_mask:
Craig Topper39c87102016-05-18 03:18:12 +00001778 i = 1; l = 0; u = 255;
1779 break;
1780 case X86::BI__builtin_ia32_palignr:
1781 case X86::BI__builtin_ia32_insertps128:
1782 case X86::BI__builtin_ia32_dpps:
1783 case X86::BI__builtin_ia32_dppd:
1784 case X86::BI__builtin_ia32_dpps256:
1785 case X86::BI__builtin_ia32_mpsadbw128:
1786 case X86::BI__builtin_ia32_mpsadbw256:
1787 case X86::BI__builtin_ia32_pcmpistrm128:
1788 case X86::BI__builtin_ia32_pcmpistri128:
1789 case X86::BI__builtin_ia32_pcmpistria128:
1790 case X86::BI__builtin_ia32_pcmpistric128:
1791 case X86::BI__builtin_ia32_pcmpistrio128:
1792 case X86::BI__builtin_ia32_pcmpistris128:
1793 case X86::BI__builtin_ia32_pcmpistriz128:
1794 case X86::BI__builtin_ia32_pclmulqdq128:
1795 case X86::BI__builtin_ia32_vperm2f128_pd256:
1796 case X86::BI__builtin_ia32_vperm2f128_ps256:
1797 case X86::BI__builtin_ia32_vperm2f128_si256:
1798 case X86::BI__builtin_ia32_permti256:
1799 i = 2; l = -128; u = 255;
1800 break;
1801 case X86::BI__builtin_ia32_palignr128:
1802 case X86::BI__builtin_ia32_palignr256:
1803 case X86::BI__builtin_ia32_palignr128_mask:
1804 case X86::BI__builtin_ia32_palignr256_mask:
1805 case X86::BI__builtin_ia32_palignr512_mask:
1806 case X86::BI__builtin_ia32_alignq512_mask:
1807 case X86::BI__builtin_ia32_alignd512_mask:
1808 case X86::BI__builtin_ia32_alignd128_mask:
1809 case X86::BI__builtin_ia32_alignd256_mask:
1810 case X86::BI__builtin_ia32_alignq128_mask:
1811 case X86::BI__builtin_ia32_alignq256_mask:
1812 case X86::BI__builtin_ia32_vcomisd:
1813 case X86::BI__builtin_ia32_vcomiss:
1814 case X86::BI__builtin_ia32_shuf_f32x4_mask:
1815 case X86::BI__builtin_ia32_shuf_f64x2_mask:
1816 case X86::BI__builtin_ia32_shuf_i32x4_mask:
1817 case X86::BI__builtin_ia32_shuf_i64x2_mask:
Craig Topper39c87102016-05-18 03:18:12 +00001818 case X86::BI__builtin_ia32_dbpsadbw128_mask:
1819 case X86::BI__builtin_ia32_dbpsadbw256_mask:
1820 case X86::BI__builtin_ia32_dbpsadbw512_mask:
1821 i = 2; l = 0; u = 255;
1822 break;
1823 case X86::BI__builtin_ia32_fixupimmpd512_mask:
1824 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
1825 case X86::BI__builtin_ia32_fixupimmps512_mask:
1826 case X86::BI__builtin_ia32_fixupimmps512_maskz:
1827 case X86::BI__builtin_ia32_fixupimmsd_mask:
1828 case X86::BI__builtin_ia32_fixupimmsd_maskz:
1829 case X86::BI__builtin_ia32_fixupimmss_mask:
1830 case X86::BI__builtin_ia32_fixupimmss_maskz:
1831 case X86::BI__builtin_ia32_fixupimmpd128_mask:
1832 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
1833 case X86::BI__builtin_ia32_fixupimmpd256_mask:
1834 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
1835 case X86::BI__builtin_ia32_fixupimmps128_mask:
1836 case X86::BI__builtin_ia32_fixupimmps128_maskz:
1837 case X86::BI__builtin_ia32_fixupimmps256_mask:
1838 case X86::BI__builtin_ia32_fixupimmps256_maskz:
1839 case X86::BI__builtin_ia32_pternlogd512_mask:
1840 case X86::BI__builtin_ia32_pternlogd512_maskz:
1841 case X86::BI__builtin_ia32_pternlogq512_mask:
1842 case X86::BI__builtin_ia32_pternlogq512_maskz:
1843 case X86::BI__builtin_ia32_pternlogd128_mask:
1844 case X86::BI__builtin_ia32_pternlogd128_maskz:
1845 case X86::BI__builtin_ia32_pternlogd256_mask:
1846 case X86::BI__builtin_ia32_pternlogd256_maskz:
1847 case X86::BI__builtin_ia32_pternlogq128_mask:
1848 case X86::BI__builtin_ia32_pternlogq128_maskz:
1849 case X86::BI__builtin_ia32_pternlogq256_mask:
1850 case X86::BI__builtin_ia32_pternlogq256_maskz:
1851 i = 3; l = 0; u = 255;
1852 break;
1853 case X86::BI__builtin_ia32_pcmpestrm128:
1854 case X86::BI__builtin_ia32_pcmpestri128:
1855 case X86::BI__builtin_ia32_pcmpestria128:
1856 case X86::BI__builtin_ia32_pcmpestric128:
1857 case X86::BI__builtin_ia32_pcmpestrio128:
1858 case X86::BI__builtin_ia32_pcmpestris128:
1859 case X86::BI__builtin_ia32_pcmpestriz128:
1860 i = 4; l = -128; u = 255;
1861 break;
1862 case X86::BI__builtin_ia32_rndscalesd_round_mask:
1863 case X86::BI__builtin_ia32_rndscaless_round_mask:
1864 i = 4; l = 0; u = 255;
Richard Trieucc3949d2016-02-18 22:34:54 +00001865 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001866 }
Craig Topperdd84ec52014-12-27 07:00:08 +00001867 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001868}
1869
Richard Smith55ce3522012-06-25 20:30:08 +00001870/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
1871/// parameter with the FormatAttr's correct format_idx and firstDataArg.
1872/// Returns true when the format fits the function and the FormatStringInfo has
1873/// been populated.
1874bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
1875 FormatStringInfo *FSI) {
1876 FSI->HasVAListArg = Format->getFirstArg() == 0;
1877 FSI->FormatIdx = Format->getFormatIdx() - 1;
1878 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001879
Richard Smith55ce3522012-06-25 20:30:08 +00001880 // The way the format attribute works in GCC, the implicit this argument
1881 // of member functions is counted. However, it doesn't appear in our own
1882 // lists, so decrement format_idx in that case.
1883 if (IsCXXMember) {
1884 if(FSI->FormatIdx == 0)
1885 return false;
1886 --FSI->FormatIdx;
1887 if (FSI->FirstDataArg != 0)
1888 --FSI->FirstDataArg;
1889 }
1890 return true;
1891}
Mike Stump11289f42009-09-09 15:08:12 +00001892
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001893/// Checks if a the given expression evaluates to null.
1894///
1895/// \brief Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00001896static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001897 // If the expression has non-null type, it doesn't evaluate to null.
1898 if (auto nullability
1899 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
1900 if (*nullability == NullabilityKind::NonNull)
1901 return false;
1902 }
1903
Ted Kremeneka146db32014-01-17 06:24:47 +00001904 // As a special case, transparent unions initialized with zero are
1905 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001906 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00001907 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
1908 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001909 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00001910 if (const InitListExpr *ILE =
1911 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001912 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00001913 }
1914
1915 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00001916 return (!Expr->isValueDependent() &&
1917 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
1918 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001919}
1920
1921static void CheckNonNullArgument(Sema &S,
1922 const Expr *ArgExpr,
1923 SourceLocation CallSiteLoc) {
1924 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00001925 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
1926 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00001927}
1928
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001929bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
1930 FormatStringInfo FSI;
1931 if ((GetFormatStringType(Format) == FST_NSString) &&
1932 getFormatStringInfo(Format, false, &FSI)) {
1933 Idx = FSI.FormatIdx;
1934 return true;
1935 }
1936 return false;
1937}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001938/// \brief Diagnose use of %s directive in an NSString which is being passed
1939/// as formatting string to formatting method.
1940static void
1941DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
1942 const NamedDecl *FDecl,
1943 Expr **Args,
1944 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001945 unsigned Idx = 0;
1946 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001947 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
1948 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001949 Idx = 2;
1950 Format = true;
1951 }
1952 else
1953 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
1954 if (S.GetFormatNSStringIdx(I, Idx)) {
1955 Format = true;
1956 break;
1957 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001958 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001959 if (!Format || NumArgs <= Idx)
1960 return;
1961 const Expr *FormatExpr = Args[Idx];
1962 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
1963 FormatExpr = CSCE->getSubExpr();
1964 const StringLiteral *FormatString;
1965 if (const ObjCStringLiteral *OSL =
1966 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
1967 FormatString = OSL->getString();
1968 else
1969 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
1970 if (!FormatString)
1971 return;
1972 if (S.FormatStringHasSArg(FormatString)) {
1973 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
1974 << "%s" << 1 << 1;
1975 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
1976 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001977 }
1978}
1979
Douglas Gregorb4866e82015-06-19 18:13:19 +00001980/// Determine whether the given type has a non-null nullability annotation.
1981static bool isNonNullType(ASTContext &ctx, QualType type) {
1982 if (auto nullability = type->getNullability(ctx))
1983 return *nullability == NullabilityKind::NonNull;
1984
1985 return false;
1986}
1987
Ted Kremenek2bc73332014-01-17 06:24:43 +00001988static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00001989 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00001990 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00001991 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00001992 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001993 assert((FDecl || Proto) && "Need a function declaration or prototype");
1994
Ted Kremenek9aedc152014-01-17 06:24:56 +00001995 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00001996 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00001997 if (FDecl) {
1998 // Handle the nonnull attribute on the function/method declaration itself.
1999 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2000 if (!NonNull->args_size()) {
2001 // Easy case: all pointer arguments are nonnull.
2002 for (const auto *Arg : Args)
2003 if (S.isValidPointerAttrType(Arg->getType()))
2004 CheckNonNullArgument(S, Arg, CallSiteLoc);
2005 return;
2006 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002007
Douglas Gregorb4866e82015-06-19 18:13:19 +00002008 for (unsigned Val : NonNull->args()) {
2009 if (Val >= Args.size())
2010 continue;
2011 if (NonNullArgs.empty())
2012 NonNullArgs.resize(Args.size());
2013 NonNullArgs.set(Val);
2014 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002015 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002016 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002017
Douglas Gregorb4866e82015-06-19 18:13:19 +00002018 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2019 // Handle the nonnull attribute on the parameters of the
2020 // function/method.
2021 ArrayRef<ParmVarDecl*> parms;
2022 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2023 parms = FD->parameters();
2024 else
2025 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2026
2027 unsigned ParamIndex = 0;
2028 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2029 I != E; ++I, ++ParamIndex) {
2030 const ParmVarDecl *PVD = *I;
2031 if (PVD->hasAttr<NonNullAttr>() ||
2032 isNonNullType(S.Context, PVD->getType())) {
2033 if (NonNullArgs.empty())
2034 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00002035
Douglas Gregorb4866e82015-06-19 18:13:19 +00002036 NonNullArgs.set(ParamIndex);
2037 }
2038 }
2039 } else {
2040 // If we have a non-function, non-method declaration but no
2041 // function prototype, try to dig out the function prototype.
2042 if (!Proto) {
2043 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2044 QualType type = VD->getType().getNonReferenceType();
2045 if (auto pointerType = type->getAs<PointerType>())
2046 type = pointerType->getPointeeType();
2047 else if (auto blockType = type->getAs<BlockPointerType>())
2048 type = blockType->getPointeeType();
2049 // FIXME: data member pointers?
2050
2051 // Dig out the function prototype, if there is one.
2052 Proto = type->getAs<FunctionProtoType>();
2053 }
2054 }
2055
2056 // Fill in non-null argument information from the nullability
2057 // information on the parameter types (if we have them).
2058 if (Proto) {
2059 unsigned Index = 0;
2060 for (auto paramType : Proto->getParamTypes()) {
2061 if (isNonNullType(S.Context, paramType)) {
2062 if (NonNullArgs.empty())
2063 NonNullArgs.resize(Args.size());
2064
2065 NonNullArgs.set(Index);
2066 }
2067
2068 ++Index;
2069 }
2070 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002071 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002072
Douglas Gregorb4866e82015-06-19 18:13:19 +00002073 // Check for non-null arguments.
2074 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2075 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00002076 if (NonNullArgs[ArgIndex])
2077 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00002078 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002079}
2080
Richard Smith55ce3522012-06-25 20:30:08 +00002081/// Handles the checks for format strings, non-POD arguments to vararg
2082/// functions, and NULL arguments passed to non-NULL parameters.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002083void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2084 ArrayRef<const Expr *> Args, bool IsMemberFunction,
Alp Toker9cacbab2014-01-20 20:26:09 +00002085 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +00002086 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00002087 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00002088 if (CurContext->isDependentContext())
2089 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00002090
Ted Kremenekb8176da2010-09-09 04:33:05 +00002091 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00002092 llvm::SmallBitVector CheckedVarArgs;
2093 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002094 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002095 // Only create vector if there are format attributes.
2096 CheckedVarArgs.resize(Args.size());
2097
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002098 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00002099 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002100 }
Richard Smithd7293d72013-08-05 18:49:43 +00002101 }
Richard Smith55ce3522012-06-25 20:30:08 +00002102
2103 // Refuse POD arguments that weren't caught by the format string
2104 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +00002105 if (CallType != VariadicDoesNotApply) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002106 unsigned NumParams = Proto ? Proto->getNumParams()
2107 : FDecl && isa<FunctionDecl>(FDecl)
2108 ? cast<FunctionDecl>(FDecl)->getNumParams()
2109 : FDecl && isa<ObjCMethodDecl>(FDecl)
2110 ? cast<ObjCMethodDecl>(FDecl)->param_size()
2111 : 0;
2112
Alp Toker9cacbab2014-01-20 20:26:09 +00002113 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002114 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00002115 if (const Expr *Arg = Args[ArgIdx]) {
2116 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2117 checkVariadicArgument(Arg, CallType);
2118 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002119 }
Richard Smithd7293d72013-08-05 18:49:43 +00002120 }
Mike Stump11289f42009-09-09 15:08:12 +00002121
Douglas Gregorb4866e82015-06-19 18:13:19 +00002122 if (FDecl || Proto) {
2123 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002124
Richard Trieu41bc0992013-06-22 00:20:41 +00002125 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002126 if (FDecl) {
2127 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
2128 CheckArgumentWithTypeTag(I, Args.data());
2129 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002130 }
Richard Smith55ce3522012-06-25 20:30:08 +00002131}
2132
2133/// CheckConstructorCall - Check a constructor call for correctness and safety
2134/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002135void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2136 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002137 const FunctionProtoType *Proto,
2138 SourceLocation Loc) {
2139 VariadicCallType CallType =
2140 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Douglas Gregorb4866e82015-06-19 18:13:19 +00002141 checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(),
2142 CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00002143}
2144
2145/// CheckFunctionCall - Check a direct function call for various correctness
2146/// and safety properties not strictly enforced by the C type system.
2147bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2148 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002149 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2150 isa<CXXMethodDecl>(FDecl);
2151 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2152 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00002153 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2154 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00002155 Expr** Args = TheCall->getArgs();
2156 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +00002157 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002158 // If this is a call to a member operator, hide the first argument
2159 // from checkCall.
2160 // FIXME: Our choice of AST representation here is less than ideal.
2161 ++Args;
2162 --NumArgs;
2163 }
Douglas Gregorb4866e82015-06-19 18:13:19 +00002164 checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00002165 IsMemberFunction, TheCall->getRParenLoc(),
2166 TheCall->getCallee()->getSourceRange(), CallType);
2167
2168 IdentifierInfo *FnInfo = FDecl->getIdentifier();
2169 // None of the checks below are needed for functions that don't have
2170 // simple names (e.g., C++ conversion functions).
2171 if (!FnInfo)
2172 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002173
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00002174 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002175 if (getLangOpts().ObjC1)
2176 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00002177
Anna Zaks22122702012-01-17 00:37:07 +00002178 unsigned CMId = FDecl->getMemoryFunctionKind();
2179 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00002180 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00002181
Anna Zaks201d4892012-01-13 21:52:01 +00002182 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00002183 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00002184 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00002185 else if (CMId == Builtin::BIstrncat)
2186 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00002187 else
Anna Zaks22122702012-01-17 00:37:07 +00002188 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00002189
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002190 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00002191}
2192
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002193bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00002194 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00002195 VariadicCallType CallType =
2196 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002197
Douglas Gregorb4866e82015-06-19 18:13:19 +00002198 checkCall(Method, nullptr, Args,
2199 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
2200 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002201
2202 return false;
2203}
2204
Richard Trieu664c4c62013-06-20 21:03:13 +00002205bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2206 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00002207 QualType Ty;
2208 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002209 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002210 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002211 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002212 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002213 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002214
Douglas Gregorb4866e82015-06-19 18:13:19 +00002215 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2216 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002217 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002218
Richard Trieu664c4c62013-06-20 21:03:13 +00002219 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00002220 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00002221 CallType = VariadicDoesNotApply;
2222 } else if (Ty->isBlockPointerType()) {
2223 CallType = VariadicBlock;
2224 } else { // Ty->isFunctionPointerType()
2225 CallType = VariadicFunction;
2226 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002227
Douglas Gregorb4866e82015-06-19 18:13:19 +00002228 checkCall(NDecl, Proto,
2229 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2230 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00002231 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00002232
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002233 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00002234}
2235
Richard Trieu41bc0992013-06-22 00:20:41 +00002236/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2237/// such as function pointers returned from functions.
2238bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002239 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00002240 TheCall->getCallee());
Douglas Gregorb4866e82015-06-19 18:13:19 +00002241 checkCall(/*FDecl=*/nullptr, Proto,
Craig Topper8c2a2a02014-08-30 16:55:39 +00002242 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00002243 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00002244 TheCall->getCallee()->getSourceRange(), CallType);
2245
2246 return false;
2247}
2248
Tim Northovere94a34c2014-03-11 10:49:14 +00002249static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
JF Bastiendda2cb12016-04-18 18:01:49 +00002250 if (!llvm::isValidAtomicOrderingCABI(Ordering))
Tim Northovere94a34c2014-03-11 10:49:14 +00002251 return false;
2252
JF Bastiendda2cb12016-04-18 18:01:49 +00002253 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
Tim Northovere94a34c2014-03-11 10:49:14 +00002254 switch (Op) {
2255 case AtomicExpr::AO__c11_atomic_init:
2256 llvm_unreachable("There is no ordering argument for an init");
2257
2258 case AtomicExpr::AO__c11_atomic_load:
2259 case AtomicExpr::AO__atomic_load_n:
2260 case AtomicExpr::AO__atomic_load:
JF Bastiendda2cb12016-04-18 18:01:49 +00002261 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2262 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002263
2264 case AtomicExpr::AO__c11_atomic_store:
2265 case AtomicExpr::AO__atomic_store:
2266 case AtomicExpr::AO__atomic_store_n:
JF Bastiendda2cb12016-04-18 18:01:49 +00002267 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2268 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2269 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002270
2271 default:
2272 return true;
2273 }
2274}
2275
Richard Smithfeea8832012-04-12 05:08:17 +00002276ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2277 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002278 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2279 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002280
Richard Smithfeea8832012-04-12 05:08:17 +00002281 // All these operations take one of the following forms:
2282 enum {
2283 // C __c11_atomic_init(A *, C)
2284 Init,
2285 // C __c11_atomic_load(A *, int)
2286 Load,
2287 // void __atomic_load(A *, CP, int)
Eric Fiselier8d662442016-03-30 23:39:56 +00002288 LoadCopy,
2289 // void __atomic_store(A *, CP, int)
Richard Smithfeea8832012-04-12 05:08:17 +00002290 Copy,
2291 // C __c11_atomic_add(A *, M, int)
2292 Arithmetic,
2293 // C __atomic_exchange_n(A *, CP, int)
2294 Xchg,
2295 // void __atomic_exchange(A *, C *, CP, int)
2296 GNUXchg,
2297 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2298 C11CmpXchg,
2299 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2300 GNUCmpXchg
2301 } Form = Init;
Eric Fiselier8d662442016-03-30 23:39:56 +00002302 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2303 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
Richard Smithfeea8832012-04-12 05:08:17 +00002304 // where:
2305 // C is an appropriate type,
2306 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2307 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2308 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2309 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002310
Gabor Horvath98bd0982015-03-16 09:59:54 +00002311 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2312 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2313 AtomicExpr::AO__atomic_load,
2314 "need to update code for modified C11 atomics");
Richard Smithfeea8832012-04-12 05:08:17 +00002315 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
2316 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
2317 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2318 Op == AtomicExpr::AO__atomic_store_n ||
2319 Op == AtomicExpr::AO__atomic_exchange_n ||
2320 Op == AtomicExpr::AO__atomic_compare_exchange_n;
2321 bool IsAddSub = false;
2322
2323 switch (Op) {
2324 case AtomicExpr::AO__c11_atomic_init:
2325 Form = Init;
2326 break;
2327
2328 case AtomicExpr::AO__c11_atomic_load:
2329 case AtomicExpr::AO__atomic_load_n:
2330 Form = Load;
2331 break;
2332
Richard Smithfeea8832012-04-12 05:08:17 +00002333 case AtomicExpr::AO__atomic_load:
Eric Fiselier8d662442016-03-30 23:39:56 +00002334 Form = LoadCopy;
2335 break;
2336
2337 case AtomicExpr::AO__c11_atomic_store:
Richard Smithfeea8832012-04-12 05:08:17 +00002338 case AtomicExpr::AO__atomic_store:
2339 case AtomicExpr::AO__atomic_store_n:
2340 Form = Copy;
2341 break;
2342
2343 case AtomicExpr::AO__c11_atomic_fetch_add:
2344 case AtomicExpr::AO__c11_atomic_fetch_sub:
2345 case AtomicExpr::AO__atomic_fetch_add:
2346 case AtomicExpr::AO__atomic_fetch_sub:
2347 case AtomicExpr::AO__atomic_add_fetch:
2348 case AtomicExpr::AO__atomic_sub_fetch:
2349 IsAddSub = true;
2350 // Fall through.
2351 case AtomicExpr::AO__c11_atomic_fetch_and:
2352 case AtomicExpr::AO__c11_atomic_fetch_or:
2353 case AtomicExpr::AO__c11_atomic_fetch_xor:
2354 case AtomicExpr::AO__atomic_fetch_and:
2355 case AtomicExpr::AO__atomic_fetch_or:
2356 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00002357 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00002358 case AtomicExpr::AO__atomic_and_fetch:
2359 case AtomicExpr::AO__atomic_or_fetch:
2360 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00002361 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00002362 Form = Arithmetic;
2363 break;
2364
2365 case AtomicExpr::AO__c11_atomic_exchange:
2366 case AtomicExpr::AO__atomic_exchange_n:
2367 Form = Xchg;
2368 break;
2369
2370 case AtomicExpr::AO__atomic_exchange:
2371 Form = GNUXchg;
2372 break;
2373
2374 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
2375 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
2376 Form = C11CmpXchg;
2377 break;
2378
2379 case AtomicExpr::AO__atomic_compare_exchange:
2380 case AtomicExpr::AO__atomic_compare_exchange_n:
2381 Form = GNUCmpXchg;
2382 break;
2383 }
2384
2385 // Check we have the right number of arguments.
2386 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002387 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00002388 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002389 << TheCall->getCallee()->getSourceRange();
2390 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00002391 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
2392 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002393 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00002394 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002395 << TheCall->getCallee()->getSourceRange();
2396 return ExprError();
2397 }
2398
Richard Smithfeea8832012-04-12 05:08:17 +00002399 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002400 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002401 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
2402 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
2403 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00002404 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002405 << Ptr->getType() << Ptr->getSourceRange();
2406 return ExprError();
2407 }
2408
Richard Smithfeea8832012-04-12 05:08:17 +00002409 // For a __c11 builtin, this should be a pointer to an _Atomic type.
2410 QualType AtomTy = pointerType->getPointeeType(); // 'A'
2411 QualType ValType = AtomTy; // 'C'
2412 if (IsC11) {
2413 if (!AtomTy->isAtomicType()) {
2414 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
2415 << Ptr->getType() << Ptr->getSourceRange();
2416 return ExprError();
2417 }
Richard Smithe00921a2012-09-15 06:09:58 +00002418 if (AtomTy.isConstQualified()) {
2419 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
2420 << Ptr->getType() << Ptr->getSourceRange();
2421 return ExprError();
2422 }
Richard Smithfeea8832012-04-12 05:08:17 +00002423 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiselier8d662442016-03-30 23:39:56 +00002424 } else if (Form != Load && Form != LoadCopy) {
Eric Fiseliera3a7c562015-10-04 00:11:02 +00002425 if (ValType.isConstQualified()) {
2426 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
2427 << Ptr->getType() << Ptr->getSourceRange();
2428 return ExprError();
2429 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002430 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002431
Richard Smithfeea8832012-04-12 05:08:17 +00002432 // For an arithmetic operation, the implied arithmetic must be well-formed.
2433 if (Form == Arithmetic) {
2434 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
2435 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
2436 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2437 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2438 return ExprError();
2439 }
2440 if (!IsAddSub && !ValType->isIntegerType()) {
2441 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
2442 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2443 return ExprError();
2444 }
David Majnemere85cff82015-01-28 05:48:06 +00002445 if (IsC11 && ValType->isPointerType() &&
2446 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
2447 diag::err_incomplete_type)) {
2448 return ExprError();
2449 }
Richard Smithfeea8832012-04-12 05:08:17 +00002450 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
2451 // For __atomic_*_n operations, the value type must be a scalar integral or
2452 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002453 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00002454 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2455 return ExprError();
2456 }
2457
Eli Friedmanaa769812013-09-11 03:49:34 +00002458 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
2459 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00002460 // For GNU atomics, require a trivially-copyable type. This is not part of
2461 // the GNU atomics specification, but we enforce it for sanity.
2462 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002463 << Ptr->getType() << Ptr->getSourceRange();
2464 return ExprError();
2465 }
2466
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002467 switch (ValType.getObjCLifetime()) {
2468 case Qualifiers::OCL_None:
2469 case Qualifiers::OCL_ExplicitNone:
2470 // okay
2471 break;
2472
2473 case Qualifiers::OCL_Weak:
2474 case Qualifiers::OCL_Strong:
2475 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00002476 // FIXME: Can this happen? By this point, ValType should be known
2477 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002478 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
2479 << ValType << Ptr->getSourceRange();
2480 return ExprError();
2481 }
2482
David Majnemerc6eb6502015-06-03 00:26:35 +00002483 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
2484 // volatile-ness of the pointee-type inject itself into the result or the
Eric Fiselier8d662442016-03-30 23:39:56 +00002485 // other operands. Similarly atomic_load can take a pointer to a const 'A'.
David Majnemerc6eb6502015-06-03 00:26:35 +00002486 ValType.removeLocalVolatile();
Eric Fiselier8d662442016-03-30 23:39:56 +00002487 ValType.removeLocalConst();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002488 QualType ResultType = ValType;
Eric Fiselier8d662442016-03-30 23:39:56 +00002489 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002490 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00002491 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002492 ResultType = Context.BoolTy;
2493
Richard Smithfeea8832012-04-12 05:08:17 +00002494 // The type of a parameter passed 'by value'. In the GNU atomics, such
2495 // arguments are actually passed as pointers.
2496 QualType ByValType = ValType; // 'CP'
2497 if (!IsC11 && !IsN)
2498 ByValType = Ptr->getType();
2499
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002500 // The first argument --- the pointer --- has a fixed type; we
2501 // deduce the types of the rest of the arguments accordingly. Walk
2502 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00002503 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002504 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00002505 if (i < NumVals[Form] + 1) {
2506 switch (i) {
2507 case 1:
2508 // The second argument is the non-atomic operand. For arithmetic, this
2509 // is always passed by value, and for a compare_exchange it is always
2510 // passed by address. For the rest, GNU uses by-address and C11 uses
2511 // by-value.
2512 assert(Form != Load);
2513 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
2514 Ty = ValType;
2515 else if (Form == Copy || Form == Xchg)
2516 Ty = ByValType;
2517 else if (Form == Arithmetic)
2518 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00002519 else {
2520 Expr *ValArg = TheCall->getArg(i);
2521 unsigned AS = 0;
2522 // Keep address space of non-atomic pointer type.
2523 if (const PointerType *PtrTy =
2524 ValArg->getType()->getAs<PointerType>()) {
2525 AS = PtrTy->getPointeeType().getAddressSpace();
2526 }
2527 Ty = Context.getPointerType(
2528 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
2529 }
Richard Smithfeea8832012-04-12 05:08:17 +00002530 break;
2531 case 2:
2532 // The third argument to compare_exchange / GNU exchange is a
2533 // (pointer to a) desired value.
2534 Ty = ByValType;
2535 break;
2536 case 3:
2537 // The fourth argument to GNU compare_exchange is a 'weak' flag.
2538 Ty = Context.BoolTy;
2539 break;
2540 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002541 } else {
2542 // The order(s) are always converted to int.
2543 Ty = Context.IntTy;
2544 }
Richard Smithfeea8832012-04-12 05:08:17 +00002545
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002546 InitializedEntity Entity =
2547 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00002548 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002549 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2550 if (Arg.isInvalid())
2551 return true;
2552 TheCall->setArg(i, Arg.get());
2553 }
2554
Richard Smithfeea8832012-04-12 05:08:17 +00002555 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002556 SmallVector<Expr*, 5> SubExprs;
2557 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00002558 switch (Form) {
2559 case Init:
2560 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00002561 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00002562 break;
2563 case Load:
2564 SubExprs.push_back(TheCall->getArg(1)); // Order
2565 break;
Eric Fiselier8d662442016-03-30 23:39:56 +00002566 case LoadCopy:
Richard Smithfeea8832012-04-12 05:08:17 +00002567 case Copy:
2568 case Arithmetic:
2569 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002570 SubExprs.push_back(TheCall->getArg(2)); // Order
2571 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00002572 break;
2573 case GNUXchg:
2574 // Note, AtomicExpr::getVal2() has a special case for this atomic.
2575 SubExprs.push_back(TheCall->getArg(3)); // Order
2576 SubExprs.push_back(TheCall->getArg(1)); // Val1
2577 SubExprs.push_back(TheCall->getArg(2)); // Val2
2578 break;
2579 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002580 SubExprs.push_back(TheCall->getArg(3)); // Order
2581 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002582 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00002583 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00002584 break;
2585 case GNUCmpXchg:
2586 SubExprs.push_back(TheCall->getArg(4)); // Order
2587 SubExprs.push_back(TheCall->getArg(1)); // Val1
2588 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
2589 SubExprs.push_back(TheCall->getArg(2)); // Val2
2590 SubExprs.push_back(TheCall->getArg(3)); // Weak
2591 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002592 }
Tim Northovere94a34c2014-03-11 10:49:14 +00002593
2594 if (SubExprs.size() >= 2 && Form != Init) {
2595 llvm::APSInt Result(32);
2596 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
2597 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00002598 Diag(SubExprs[1]->getLocStart(),
2599 diag::warn_atomic_op_has_invalid_memory_order)
2600 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00002601 }
2602
Fariborz Jahanian615de762013-05-28 17:37:39 +00002603 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
2604 SubExprs, ResultType, Op,
2605 TheCall->getRParenLoc());
2606
2607 if ((Op == AtomicExpr::AO__c11_atomic_load ||
2608 (Op == AtomicExpr::AO__c11_atomic_store)) &&
2609 Context.AtomicUsesUnsupportedLibcall(AE))
2610 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
2611 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002612
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002613 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002614}
2615
John McCall29ad95b2011-08-27 01:09:30 +00002616/// checkBuiltinArgument - Given a call to a builtin function, perform
2617/// normal type-checking on the given argument, updating the call in
2618/// place. This is useful when a builtin function requires custom
2619/// type-checking for some of its arguments but not necessarily all of
2620/// them.
2621///
2622/// Returns true on error.
2623static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
2624 FunctionDecl *Fn = E->getDirectCallee();
2625 assert(Fn && "builtin call without direct callee!");
2626
2627 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
2628 InitializedEntity Entity =
2629 InitializedEntity::InitializeParameter(S.Context, Param);
2630
2631 ExprResult Arg = E->getArg(0);
2632 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
2633 if (Arg.isInvalid())
2634 return true;
2635
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002636 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00002637 return false;
2638}
2639
Chris Lattnerdc046542009-05-08 06:58:22 +00002640/// SemaBuiltinAtomicOverloaded - We have a call to a function like
2641/// __sync_fetch_and_add, which is an overloaded function based on the pointer
2642/// type of its first argument. The main ActOnCallExpr routines have already
2643/// promoted the types of arguments because all of these calls are prototyped as
2644/// void(...).
2645///
2646/// This function goes through and does final semantic checking for these
2647/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00002648ExprResult
2649Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002650 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00002651 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2652 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2653
2654 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002655 if (TheCall->getNumArgs() < 1) {
2656 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2657 << 0 << 1 << TheCall->getNumArgs()
2658 << TheCall->getCallee()->getSourceRange();
2659 return ExprError();
2660 }
Mike Stump11289f42009-09-09 15:08:12 +00002661
Chris Lattnerdc046542009-05-08 06:58:22 +00002662 // Inspect the first argument of the atomic builtin. This should always be
2663 // a pointer type, whose element is an integral scalar or pointer type.
2664 // Because it is a pointer type, we don't have to worry about any implicit
2665 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002666 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00002667 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00002668 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
2669 if (FirstArgResult.isInvalid())
2670 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002671 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00002672 TheCall->setArg(0, FirstArg);
2673
John McCall31168b02011-06-15 23:02:42 +00002674 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
2675 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002676 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
2677 << FirstArg->getType() << FirstArg->getSourceRange();
2678 return ExprError();
2679 }
Mike Stump11289f42009-09-09 15:08:12 +00002680
John McCall31168b02011-06-15 23:02:42 +00002681 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00002682 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002683 !ValType->isBlockPointerType()) {
2684 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
2685 << FirstArg->getType() << FirstArg->getSourceRange();
2686 return ExprError();
2687 }
Chris Lattnerdc046542009-05-08 06:58:22 +00002688
John McCall31168b02011-06-15 23:02:42 +00002689 switch (ValType.getObjCLifetime()) {
2690 case Qualifiers::OCL_None:
2691 case Qualifiers::OCL_ExplicitNone:
2692 // okay
2693 break;
2694
2695 case Qualifiers::OCL_Weak:
2696 case Qualifiers::OCL_Strong:
2697 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00002698 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00002699 << ValType << FirstArg->getSourceRange();
2700 return ExprError();
2701 }
2702
John McCallb50451a2011-10-05 07:41:44 +00002703 // Strip any qualifiers off ValType.
2704 ValType = ValType.getUnqualifiedType();
2705
Chandler Carruth3973af72010-07-18 20:54:12 +00002706 // The majority of builtins return a value, but a few have special return
2707 // types, so allow them to override appropriately below.
2708 QualType ResultType = ValType;
2709
Chris Lattnerdc046542009-05-08 06:58:22 +00002710 // We need to figure out which concrete builtin this maps onto. For example,
2711 // __sync_fetch_and_add with a 2 byte object turns into
2712 // __sync_fetch_and_add_2.
2713#define BUILTIN_ROW(x) \
2714 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
2715 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00002716
Chris Lattnerdc046542009-05-08 06:58:22 +00002717 static const unsigned BuiltinIndices[][5] = {
2718 BUILTIN_ROW(__sync_fetch_and_add),
2719 BUILTIN_ROW(__sync_fetch_and_sub),
2720 BUILTIN_ROW(__sync_fetch_and_or),
2721 BUILTIN_ROW(__sync_fetch_and_and),
2722 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00002723 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00002724
Chris Lattnerdc046542009-05-08 06:58:22 +00002725 BUILTIN_ROW(__sync_add_and_fetch),
2726 BUILTIN_ROW(__sync_sub_and_fetch),
2727 BUILTIN_ROW(__sync_and_and_fetch),
2728 BUILTIN_ROW(__sync_or_and_fetch),
2729 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00002730 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00002731
Chris Lattnerdc046542009-05-08 06:58:22 +00002732 BUILTIN_ROW(__sync_val_compare_and_swap),
2733 BUILTIN_ROW(__sync_bool_compare_and_swap),
2734 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00002735 BUILTIN_ROW(__sync_lock_release),
2736 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00002737 };
Mike Stump11289f42009-09-09 15:08:12 +00002738#undef BUILTIN_ROW
2739
Chris Lattnerdc046542009-05-08 06:58:22 +00002740 // Determine the index of the size.
2741 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00002742 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00002743 case 1: SizeIndex = 0; break;
2744 case 2: SizeIndex = 1; break;
2745 case 4: SizeIndex = 2; break;
2746 case 8: SizeIndex = 3; break;
2747 case 16: SizeIndex = 4; break;
2748 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002749 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
2750 << FirstArg->getType() << FirstArg->getSourceRange();
2751 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00002752 }
Mike Stump11289f42009-09-09 15:08:12 +00002753
Chris Lattnerdc046542009-05-08 06:58:22 +00002754 // Each of these builtins has one pointer argument, followed by some number of
2755 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
2756 // that we ignore. Find out which row of BuiltinIndices to read from as well
2757 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00002758 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00002759 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00002760 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00002761 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00002762 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00002763 case Builtin::BI__sync_fetch_and_add:
2764 case Builtin::BI__sync_fetch_and_add_1:
2765 case Builtin::BI__sync_fetch_and_add_2:
2766 case Builtin::BI__sync_fetch_and_add_4:
2767 case Builtin::BI__sync_fetch_and_add_8:
2768 case Builtin::BI__sync_fetch_and_add_16:
2769 BuiltinIndex = 0;
2770 break;
2771
2772 case Builtin::BI__sync_fetch_and_sub:
2773 case Builtin::BI__sync_fetch_and_sub_1:
2774 case Builtin::BI__sync_fetch_and_sub_2:
2775 case Builtin::BI__sync_fetch_and_sub_4:
2776 case Builtin::BI__sync_fetch_and_sub_8:
2777 case Builtin::BI__sync_fetch_and_sub_16:
2778 BuiltinIndex = 1;
2779 break;
2780
2781 case Builtin::BI__sync_fetch_and_or:
2782 case Builtin::BI__sync_fetch_and_or_1:
2783 case Builtin::BI__sync_fetch_and_or_2:
2784 case Builtin::BI__sync_fetch_and_or_4:
2785 case Builtin::BI__sync_fetch_and_or_8:
2786 case Builtin::BI__sync_fetch_and_or_16:
2787 BuiltinIndex = 2;
2788 break;
2789
2790 case Builtin::BI__sync_fetch_and_and:
2791 case Builtin::BI__sync_fetch_and_and_1:
2792 case Builtin::BI__sync_fetch_and_and_2:
2793 case Builtin::BI__sync_fetch_and_and_4:
2794 case Builtin::BI__sync_fetch_and_and_8:
2795 case Builtin::BI__sync_fetch_and_and_16:
2796 BuiltinIndex = 3;
2797 break;
Mike Stump11289f42009-09-09 15:08:12 +00002798
Douglas Gregor73722482011-11-28 16:30:08 +00002799 case Builtin::BI__sync_fetch_and_xor:
2800 case Builtin::BI__sync_fetch_and_xor_1:
2801 case Builtin::BI__sync_fetch_and_xor_2:
2802 case Builtin::BI__sync_fetch_and_xor_4:
2803 case Builtin::BI__sync_fetch_and_xor_8:
2804 case Builtin::BI__sync_fetch_and_xor_16:
2805 BuiltinIndex = 4;
2806 break;
2807
Hal Finkeld2208b52014-10-02 20:53:50 +00002808 case Builtin::BI__sync_fetch_and_nand:
2809 case Builtin::BI__sync_fetch_and_nand_1:
2810 case Builtin::BI__sync_fetch_and_nand_2:
2811 case Builtin::BI__sync_fetch_and_nand_4:
2812 case Builtin::BI__sync_fetch_and_nand_8:
2813 case Builtin::BI__sync_fetch_and_nand_16:
2814 BuiltinIndex = 5;
2815 WarnAboutSemanticsChange = true;
2816 break;
2817
Douglas Gregor73722482011-11-28 16:30:08 +00002818 case Builtin::BI__sync_add_and_fetch:
2819 case Builtin::BI__sync_add_and_fetch_1:
2820 case Builtin::BI__sync_add_and_fetch_2:
2821 case Builtin::BI__sync_add_and_fetch_4:
2822 case Builtin::BI__sync_add_and_fetch_8:
2823 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002824 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00002825 break;
2826
2827 case Builtin::BI__sync_sub_and_fetch:
2828 case Builtin::BI__sync_sub_and_fetch_1:
2829 case Builtin::BI__sync_sub_and_fetch_2:
2830 case Builtin::BI__sync_sub_and_fetch_4:
2831 case Builtin::BI__sync_sub_and_fetch_8:
2832 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002833 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00002834 break;
2835
2836 case Builtin::BI__sync_and_and_fetch:
2837 case Builtin::BI__sync_and_and_fetch_1:
2838 case Builtin::BI__sync_and_and_fetch_2:
2839 case Builtin::BI__sync_and_and_fetch_4:
2840 case Builtin::BI__sync_and_and_fetch_8:
2841 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002842 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00002843 break;
2844
2845 case Builtin::BI__sync_or_and_fetch:
2846 case Builtin::BI__sync_or_and_fetch_1:
2847 case Builtin::BI__sync_or_and_fetch_2:
2848 case Builtin::BI__sync_or_and_fetch_4:
2849 case Builtin::BI__sync_or_and_fetch_8:
2850 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002851 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00002852 break;
2853
2854 case Builtin::BI__sync_xor_and_fetch:
2855 case Builtin::BI__sync_xor_and_fetch_1:
2856 case Builtin::BI__sync_xor_and_fetch_2:
2857 case Builtin::BI__sync_xor_and_fetch_4:
2858 case Builtin::BI__sync_xor_and_fetch_8:
2859 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002860 BuiltinIndex = 10;
2861 break;
2862
2863 case Builtin::BI__sync_nand_and_fetch:
2864 case Builtin::BI__sync_nand_and_fetch_1:
2865 case Builtin::BI__sync_nand_and_fetch_2:
2866 case Builtin::BI__sync_nand_and_fetch_4:
2867 case Builtin::BI__sync_nand_and_fetch_8:
2868 case Builtin::BI__sync_nand_and_fetch_16:
2869 BuiltinIndex = 11;
2870 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00002871 break;
Mike Stump11289f42009-09-09 15:08:12 +00002872
Chris Lattnerdc046542009-05-08 06:58:22 +00002873 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00002874 case Builtin::BI__sync_val_compare_and_swap_1:
2875 case Builtin::BI__sync_val_compare_and_swap_2:
2876 case Builtin::BI__sync_val_compare_and_swap_4:
2877 case Builtin::BI__sync_val_compare_and_swap_8:
2878 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002879 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00002880 NumFixed = 2;
2881 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002882
Chris Lattnerdc046542009-05-08 06:58:22 +00002883 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00002884 case Builtin::BI__sync_bool_compare_and_swap_1:
2885 case Builtin::BI__sync_bool_compare_and_swap_2:
2886 case Builtin::BI__sync_bool_compare_and_swap_4:
2887 case Builtin::BI__sync_bool_compare_and_swap_8:
2888 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002889 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00002890 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00002891 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00002892 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002893
2894 case Builtin::BI__sync_lock_test_and_set:
2895 case Builtin::BI__sync_lock_test_and_set_1:
2896 case Builtin::BI__sync_lock_test_and_set_2:
2897 case Builtin::BI__sync_lock_test_and_set_4:
2898 case Builtin::BI__sync_lock_test_and_set_8:
2899 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002900 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00002901 break;
2902
Chris Lattnerdc046542009-05-08 06:58:22 +00002903 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00002904 case Builtin::BI__sync_lock_release_1:
2905 case Builtin::BI__sync_lock_release_2:
2906 case Builtin::BI__sync_lock_release_4:
2907 case Builtin::BI__sync_lock_release_8:
2908 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002909 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00002910 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00002911 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00002912 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002913
2914 case Builtin::BI__sync_swap:
2915 case Builtin::BI__sync_swap_1:
2916 case Builtin::BI__sync_swap_2:
2917 case Builtin::BI__sync_swap_4:
2918 case Builtin::BI__sync_swap_8:
2919 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002920 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00002921 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00002922 }
Mike Stump11289f42009-09-09 15:08:12 +00002923
Chris Lattnerdc046542009-05-08 06:58:22 +00002924 // Now that we know how many fixed arguments we expect, first check that we
2925 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002926 if (TheCall->getNumArgs() < 1+NumFixed) {
2927 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2928 << 0 << 1+NumFixed << TheCall->getNumArgs()
2929 << TheCall->getCallee()->getSourceRange();
2930 return ExprError();
2931 }
Mike Stump11289f42009-09-09 15:08:12 +00002932
Hal Finkeld2208b52014-10-02 20:53:50 +00002933 if (WarnAboutSemanticsChange) {
2934 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
2935 << TheCall->getCallee()->getSourceRange();
2936 }
2937
Chris Lattner5b9241b2009-05-08 15:36:58 +00002938 // Get the decl for the concrete builtin from this, we can tell what the
2939 // concrete integer type we should convert to is.
2940 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Eric Christopher02d5d862015-08-06 01:01:12 +00002941 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00002942 FunctionDecl *NewBuiltinDecl;
2943 if (NewBuiltinID == BuiltinID)
2944 NewBuiltinDecl = FDecl;
2945 else {
2946 // Perform builtin lookup to avoid redeclaring it.
2947 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
2948 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
2949 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
2950 assert(Res.getFoundDecl());
2951 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00002952 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00002953 return ExprError();
2954 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002955
John McCallcf142162010-08-07 06:22:56 +00002956 // The first argument --- the pointer --- has a fixed type; we
2957 // deduce the types of the rest of the arguments accordingly. Walk
2958 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00002959 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00002960 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00002961
Chris Lattnerdc046542009-05-08 06:58:22 +00002962 // GCC does an implicit conversion to the pointer or integer ValType. This
2963 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00002964 // Initialize the argument.
2965 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2966 ValType, /*consume*/ false);
2967 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00002968 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002969 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002970
Chris Lattnerdc046542009-05-08 06:58:22 +00002971 // Okay, we have something that *can* be converted to the right type. Check
2972 // to see if there is a potentially weird extension going on here. This can
2973 // happen when you do an atomic operation on something like an char* and
2974 // pass in 42. The 42 gets converted to char. This is even more strange
2975 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00002976 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002977 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00002978 }
Mike Stump11289f42009-09-09 15:08:12 +00002979
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002980 ASTContext& Context = this->getASTContext();
2981
2982 // Create a new DeclRefExpr to refer to the new decl.
2983 DeclRefExpr* NewDRE = DeclRefExpr::Create(
2984 Context,
2985 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00002986 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002987 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00002988 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002989 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00002990 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002991 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00002992
Chris Lattnerdc046542009-05-08 06:58:22 +00002993 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00002994 // FIXME: This loses syntactic information.
2995 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
2996 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
2997 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002998 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00002999
Chandler Carruthbc8cab12010-07-18 07:23:17 +00003000 // Change the result type of the call to match the original value type. This
3001 // is arbitrary, but the codegen for these builtins ins design to handle it
3002 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00003003 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003004
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003005 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00003006}
3007
Michael Zolotukhin84df1232015-09-08 23:52:33 +00003008/// SemaBuiltinNontemporalOverloaded - We have a call to
3009/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3010/// overloaded function based on the pointer type of its last argument.
3011///
3012/// This function goes through and does final semantic checking for these
3013/// builtins.
3014ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3015 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3016 DeclRefExpr *DRE =
3017 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3018 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3019 unsigned BuiltinID = FDecl->getBuiltinID();
3020 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3021 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3022 "Unexpected nontemporal load/store builtin!");
3023 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3024 unsigned numArgs = isStore ? 2 : 1;
3025
3026 // Ensure that we have the proper number of arguments.
3027 if (checkArgCount(*this, TheCall, numArgs))
3028 return ExprError();
3029
3030 // Inspect the last argument of the nontemporal builtin. This should always
3031 // be a pointer type, from which we imply the type of the memory access.
3032 // Because it is a pointer type, we don't have to worry about any implicit
3033 // casts here.
3034 Expr *PointerArg = TheCall->getArg(numArgs - 1);
3035 ExprResult PointerArgResult =
3036 DefaultFunctionArrayLvalueConversion(PointerArg);
3037
3038 if (PointerArgResult.isInvalid())
3039 return ExprError();
3040 PointerArg = PointerArgResult.get();
3041 TheCall->setArg(numArgs - 1, PointerArg);
3042
3043 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3044 if (!pointerType) {
3045 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3046 << PointerArg->getType() << PointerArg->getSourceRange();
3047 return ExprError();
3048 }
3049
3050 QualType ValType = pointerType->getPointeeType();
3051
3052 // Strip any qualifiers off ValType.
3053 ValType = ValType.getUnqualifiedType();
3054 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3055 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3056 !ValType->isVectorType()) {
3057 Diag(DRE->getLocStart(),
3058 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3059 << PointerArg->getType() << PointerArg->getSourceRange();
3060 return ExprError();
3061 }
3062
3063 if (!isStore) {
3064 TheCall->setType(ValType);
3065 return TheCallResult;
3066 }
3067
3068 ExprResult ValArg = TheCall->getArg(0);
3069 InitializedEntity Entity = InitializedEntity::InitializeParameter(
3070 Context, ValType, /*consume*/ false);
3071 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3072 if (ValArg.isInvalid())
3073 return ExprError();
3074
3075 TheCall->setArg(0, ValArg.get());
3076 TheCall->setType(Context.VoidTy);
3077 return TheCallResult;
3078}
3079
Chris Lattner6436fb62009-02-18 06:01:06 +00003080/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00003081/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00003082/// Note: It might also make sense to do the UTF-16 conversion here (would
3083/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00003084bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00003085 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00003086 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3087
Douglas Gregorfb65e592011-07-27 05:40:30 +00003088 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003089 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3090 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00003091 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00003092 }
Mike Stump11289f42009-09-09 15:08:12 +00003093
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003094 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003095 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003096 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003097 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00003098 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003099 UTF16 *ToPtr = &ToBuf[0];
3100
3101 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
3102 &ToPtr, ToPtr + NumBytes,
3103 strictConversion);
3104 // Check for conversion failure.
3105 if (Result != conversionOK)
3106 Diag(Arg->getLocStart(),
3107 diag::warn_cfstring_truncated) << Arg->getSourceRange();
3108 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00003109 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003110}
3111
Charles Davisc7d5c942015-09-17 20:55:33 +00003112/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3113/// for validity. Emit an error and return true on failure; return false
3114/// on success.
3115bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00003116 Expr *Fn = TheCall->getCallee();
3117 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00003118 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003119 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003120 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3121 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00003122 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003123 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00003124 return true;
3125 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003126
3127 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00003128 return Diag(TheCall->getLocEnd(),
3129 diag::err_typecheck_call_too_few_args_at_least)
3130 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003131 }
3132
John McCall29ad95b2011-08-27 01:09:30 +00003133 // Type-check the first argument normally.
3134 if (checkBuiltinArgument(*this, TheCall, 0))
3135 return true;
3136
Chris Lattnere202e6a2007-12-20 00:05:45 +00003137 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00003138 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00003139 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00003140 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00003141 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00003142 else if (FunctionDecl *FD = getCurFunctionDecl())
3143 isVariadic = FD->isVariadic();
3144 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00003145 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00003146
Chris Lattnere202e6a2007-12-20 00:05:45 +00003147 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00003148 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3149 return true;
3150 }
Mike Stump11289f42009-09-09 15:08:12 +00003151
Chris Lattner43be2e62007-12-19 23:59:04 +00003152 // Verify that the second argument to the builtin is the last argument of the
3153 // current function or method.
3154 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00003155 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00003156
Nico Weber9eea7642013-05-24 23:31:57 +00003157 // These are valid if SecondArgIsLastNamedArgument is false after the next
3158 // block.
3159 QualType Type;
3160 SourceLocation ParamLoc;
Aaron Ballman1de59c52016-04-24 13:30:21 +00003161 bool IsCRegister = false;
Nico Weber9eea7642013-05-24 23:31:57 +00003162
Anders Carlsson6a8350b2008-02-11 04:20:54 +00003163 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3164 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00003165 // FIXME: This isn't correct for methods (results in bogus warning).
3166 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00003167 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00003168 if (CurBlock)
David Majnemera3debed2016-06-24 05:33:44 +00003169 LastArg = CurBlock->TheDecl->parameters().back();
Steve Naroff439a3e42009-04-15 19:33:47 +00003170 else if (FunctionDecl *FD = getCurFunctionDecl())
David Majnemera3debed2016-06-24 05:33:44 +00003171 LastArg = FD->parameters().back();
Chris Lattner43be2e62007-12-19 23:59:04 +00003172 else
David Majnemera3debed2016-06-24 05:33:44 +00003173 LastArg = getCurMethodDecl()->parameters().back();
Chris Lattner43be2e62007-12-19 23:59:04 +00003174 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00003175
3176 Type = PV->getType();
3177 ParamLoc = PV->getLocation();
Aaron Ballman1de59c52016-04-24 13:30:21 +00003178 IsCRegister =
3179 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
Chris Lattner43be2e62007-12-19 23:59:04 +00003180 }
3181 }
Mike Stump11289f42009-09-09 15:08:12 +00003182
Chris Lattner43be2e62007-12-19 23:59:04 +00003183 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00003184 Diag(TheCall->getArg(1)->getLocStart(),
Aaron Ballman05164812016-04-18 18:10:53 +00003185 diag::warn_second_arg_of_va_start_not_last_named_param);
Aaron Ballman1de59c52016-04-24 13:30:21 +00003186 else if (IsCRegister || Type->isReferenceType() ||
3187 Type->isPromotableIntegerType() ||
3188 Type->isSpecificBuiltinType(BuiltinType::Float)) {
3189 unsigned Reason = 0;
3190 if (Type->isReferenceType()) Reason = 1;
3191 else if (IsCRegister) Reason = 2;
3192 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
Nico Weber9eea7642013-05-24 23:31:57 +00003193 Diag(ParamLoc, diag::note_parameter_type) << Type;
3194 }
3195
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00003196 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00003197 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00003198}
Chris Lattner43be2e62007-12-19 23:59:04 +00003199
Charles Davisc7d5c942015-09-17 20:55:33 +00003200/// Check the arguments to '__builtin_va_start' for validity, and that
3201/// it was called from a function of the native ABI.
3202/// Emit an error and return true on failure; return false on success.
3203bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
3204 // On x86-64 Unix, don't allow this in Win64 ABI functions.
3205 // On x64 Windows, don't allow this in System V ABI functions.
3206 // (Yes, that means there's no corresponding way to support variadic
3207 // System V ABI functions on Windows.)
3208 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) {
3209 unsigned OS = Context.getTargetInfo().getTriple().getOS();
3210 clang::CallingConv CC = CC_C;
3211 if (const FunctionDecl *FD = getCurFunctionDecl())
3212 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3213 if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) ||
3214 (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64))
3215 return Diag(TheCall->getCallee()->getLocStart(),
3216 diag::err_va_start_used_in_wrong_abi_function)
3217 << (OS != llvm::Triple::Win32);
3218 }
3219 return SemaBuiltinVAStartImpl(TheCall);
3220}
3221
3222/// Check the arguments to '__builtin_ms_va_start' for validity, and that
3223/// it was called from a Win64 ABI function.
3224/// Emit an error and return true on failure; return false on success.
3225bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) {
3226 // This only makes sense for x86-64.
3227 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3228 Expr *Callee = TheCall->getCallee();
3229 if (TT.getArch() != llvm::Triple::x86_64)
3230 return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt);
3231 // Don't allow this in System V ABI functions.
3232 clang::CallingConv CC = CC_C;
3233 if (const FunctionDecl *FD = getCurFunctionDecl())
3234 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3235 if (CC == CC_X86_64SysV ||
3236 (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64))
3237 return Diag(Callee->getLocStart(),
3238 diag::err_ms_va_start_used_in_sysv_function);
3239 return SemaBuiltinVAStartImpl(TheCall);
3240}
3241
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003242bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
3243 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
3244 // const char *named_addr);
3245
3246 Expr *Func = Call->getCallee();
3247
3248 if (Call->getNumArgs() < 3)
3249 return Diag(Call->getLocEnd(),
3250 diag::err_typecheck_call_too_few_args_at_least)
3251 << 0 /*function call*/ << 3 << Call->getNumArgs();
3252
3253 // Determine whether the current function is variadic or not.
3254 bool IsVariadic;
3255 if (BlockScopeInfo *CurBlock = getCurBlock())
3256 IsVariadic = CurBlock->TheDecl->isVariadic();
3257 else if (FunctionDecl *FD = getCurFunctionDecl())
3258 IsVariadic = FD->isVariadic();
3259 else if (ObjCMethodDecl *MD = getCurMethodDecl())
3260 IsVariadic = MD->isVariadic();
3261 else
3262 llvm_unreachable("unexpected statement type");
3263
3264 if (!IsVariadic) {
3265 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3266 return true;
3267 }
3268
3269 // Type-check the first argument normally.
3270 if (checkBuiltinArgument(*this, Call, 0))
3271 return true;
3272
Benjamin Kramere0ca6e12015-03-01 18:09:50 +00003273 const struct {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003274 unsigned ArgNo;
3275 QualType Type;
3276 } ArgumentTypes[] = {
3277 { 1, Context.getPointerType(Context.CharTy.withConst()) },
3278 { 2, Context.getSizeType() },
3279 };
3280
3281 for (const auto &AT : ArgumentTypes) {
3282 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
3283 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
3284 continue;
3285 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
3286 << Arg->getType() << AT.Type << 1 /* different class */
3287 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
3288 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
3289 }
3290
3291 return false;
3292}
3293
Chris Lattner2da14fb2007-12-20 00:26:33 +00003294/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
3295/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00003296bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
3297 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00003298 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00003299 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00003300 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00003301 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003302 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003303 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00003304 << SourceRange(TheCall->getArg(2)->getLocStart(),
3305 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003306
John Wiegley01296292011-04-08 18:41:53 +00003307 ExprResult OrigArg0 = TheCall->getArg(0);
3308 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00003309
Chris Lattner2da14fb2007-12-20 00:26:33 +00003310 // Do standard promotions between the two arguments, returning their common
3311 // type.
Chris Lattner08464942007-12-28 05:29:59 +00003312 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00003313 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
3314 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00003315
3316 // Make sure any conversions are pushed back into the call; this is
3317 // type safe since unordered compare builtins are declared as "_Bool
3318 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00003319 TheCall->setArg(0, OrigArg0.get());
3320 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00003321
John Wiegley01296292011-04-08 18:41:53 +00003322 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00003323 return false;
3324
Chris Lattner2da14fb2007-12-20 00:26:33 +00003325 // If the common type isn't a real floating type, then the arguments were
3326 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00003327 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00003328 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003329 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00003330 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
3331 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003332
Chris Lattner2da14fb2007-12-20 00:26:33 +00003333 return false;
3334}
3335
Benjamin Kramer634fc102010-02-15 22:42:31 +00003336/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
3337/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00003338/// to check everything. We expect the last argument to be a floating point
3339/// value.
3340bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
3341 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00003342 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00003343 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00003344 if (TheCall->getNumArgs() > NumArgs)
3345 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003346 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003347 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00003348 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003349 (*(TheCall->arg_end()-1))->getLocEnd());
3350
Benjamin Kramer64aae502010-02-16 10:07:31 +00003351 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00003352
Eli Friedman7e4faac2009-08-31 20:06:00 +00003353 if (OrigArg->isTypeDependent())
3354 return false;
3355
Chris Lattner68784ef2010-05-06 05:50:07 +00003356 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00003357 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00003358 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003359 diag::err_typecheck_call_invalid_unary_fp)
3360 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003361
Chris Lattner68784ef2010-05-06 05:50:07 +00003362 // If this is an implicit conversion from float -> double, remove it.
3363 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
3364 Expr *CastArg = Cast->getSubExpr();
3365 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
3366 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
3367 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00003368 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00003369 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00003370 }
3371 }
3372
Eli Friedman7e4faac2009-08-31 20:06:00 +00003373 return false;
3374}
3375
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003376/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
3377// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00003378ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00003379 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003380 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00003381 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00003382 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3383 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003384
Nate Begemana0110022010-06-08 00:16:34 +00003385 // Determine which of the following types of shufflevector we're checking:
3386 // 1) unary, vector mask: (lhs, mask)
Craig Topperb3174a82016-05-18 04:11:25 +00003387 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
Nate Begemana0110022010-06-08 00:16:34 +00003388 QualType resType = TheCall->getArg(0)->getType();
3389 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00003390
Douglas Gregorc25f7662009-05-19 22:10:17 +00003391 if (!TheCall->getArg(0)->isTypeDependent() &&
3392 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00003393 QualType LHSType = TheCall->getArg(0)->getType();
3394 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00003395
Craig Topperbaca3892013-07-29 06:47:04 +00003396 if (!LHSType->isVectorType() || !RHSType->isVectorType())
3397 return ExprError(Diag(TheCall->getLocStart(),
3398 diag::err_shufflevector_non_vector)
3399 << SourceRange(TheCall->getArg(0)->getLocStart(),
3400 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00003401
Nate Begemana0110022010-06-08 00:16:34 +00003402 numElements = LHSType->getAs<VectorType>()->getNumElements();
3403 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00003404
Nate Begemana0110022010-06-08 00:16:34 +00003405 // Check to see if we have a call with 2 vector arguments, the unary shuffle
3406 // with mask. If so, verify that RHS is an integer vector type with the
3407 // same number of elts as lhs.
3408 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00003409 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00003410 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00003411 return ExprError(Diag(TheCall->getLocStart(),
3412 diag::err_shufflevector_incompatible_vector)
3413 << SourceRange(TheCall->getArg(1)->getLocStart(),
3414 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00003415 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00003416 return ExprError(Diag(TheCall->getLocStart(),
3417 diag::err_shufflevector_incompatible_vector)
3418 << SourceRange(TheCall->getArg(0)->getLocStart(),
3419 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00003420 } else if (numElements != numResElements) {
3421 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00003422 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00003423 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00003424 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003425 }
3426
3427 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00003428 if (TheCall->getArg(i)->isTypeDependent() ||
3429 TheCall->getArg(i)->isValueDependent())
3430 continue;
3431
Nate Begemana0110022010-06-08 00:16:34 +00003432 llvm::APSInt Result(32);
3433 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
3434 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00003435 diag::err_shufflevector_nonconstant_argument)
3436 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003437
Craig Topper50ad5b72013-08-03 17:40:38 +00003438 // Allow -1 which will be translated to undef in the IR.
3439 if (Result.isSigned() && Result.isAllOnesValue())
3440 continue;
3441
Chris Lattner7ab824e2008-08-10 02:05:13 +00003442 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003443 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00003444 diag::err_shufflevector_argument_too_large)
3445 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003446 }
3447
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003448 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003449
Chris Lattner7ab824e2008-08-10 02:05:13 +00003450 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003451 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00003452 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003453 }
3454
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003455 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
3456 TheCall->getCallee()->getLocStart(),
3457 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003458}
Chris Lattner43be2e62007-12-19 23:59:04 +00003459
Hal Finkelc4d7c822013-09-18 03:29:45 +00003460/// SemaConvertVectorExpr - Handle __builtin_convertvector
3461ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
3462 SourceLocation BuiltinLoc,
3463 SourceLocation RParenLoc) {
3464 ExprValueKind VK = VK_RValue;
3465 ExprObjectKind OK = OK_Ordinary;
3466 QualType DstTy = TInfo->getType();
3467 QualType SrcTy = E->getType();
3468
3469 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
3470 return ExprError(Diag(BuiltinLoc,
3471 diag::err_convertvector_non_vector)
3472 << E->getSourceRange());
3473 if (!DstTy->isVectorType() && !DstTy->isDependentType())
3474 return ExprError(Diag(BuiltinLoc,
3475 diag::err_convertvector_non_vector_type));
3476
3477 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
3478 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
3479 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
3480 if (SrcElts != DstElts)
3481 return ExprError(Diag(BuiltinLoc,
3482 diag::err_convertvector_incompatible_vector)
3483 << E->getSourceRange());
3484 }
3485
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003486 return new (Context)
3487 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00003488}
3489
Daniel Dunbarb7257262008-07-21 22:59:13 +00003490/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
3491// This is declared to take (const void*, ...) and can take two
3492// optional constant int args.
3493bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00003494 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003495
Chris Lattner3b054132008-11-19 05:08:23 +00003496 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003497 return Diag(TheCall->getLocEnd(),
3498 diag::err_typecheck_call_too_many_args_at_most)
3499 << 0 /*function call*/ << 3 << NumArgs
3500 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003501
3502 // Argument 0 is checked for us and the remaining arguments must be
3503 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00003504 for (unsigned i = 1; i != NumArgs; ++i)
3505 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00003506 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003507
Warren Hunt20e4a5d2014-02-21 23:08:53 +00003508 return false;
3509}
3510
Hal Finkelf0417332014-07-17 14:25:55 +00003511/// SemaBuiltinAssume - Handle __assume (MS Extension).
3512// __assume does not evaluate its arguments, and should warn if its argument
3513// has side effects.
3514bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
3515 Expr *Arg = TheCall->getArg(0);
3516 if (Arg->isInstantiationDependent()) return false;
3517
3518 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00003519 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00003520 << Arg->getSourceRange()
3521 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
3522
3523 return false;
3524}
3525
3526/// Handle __builtin_assume_aligned. This is declared
3527/// as (const void*, size_t, ...) and can take one optional constant int arg.
3528bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
3529 unsigned NumArgs = TheCall->getNumArgs();
3530
3531 if (NumArgs > 3)
3532 return Diag(TheCall->getLocEnd(),
3533 diag::err_typecheck_call_too_many_args_at_most)
3534 << 0 /*function call*/ << 3 << NumArgs
3535 << TheCall->getSourceRange();
3536
3537 // The alignment must be a constant integer.
3538 Expr *Arg = TheCall->getArg(1);
3539
3540 // We can't check the value of a dependent argument.
3541 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
3542 llvm::APSInt Result;
3543 if (SemaBuiltinConstantArg(TheCall, 1, Result))
3544 return true;
3545
3546 if (!Result.isPowerOf2())
3547 return Diag(TheCall->getLocStart(),
3548 diag::err_alignment_not_power_of_two)
3549 << Arg->getSourceRange();
3550 }
3551
3552 if (NumArgs > 2) {
3553 ExprResult Arg(TheCall->getArg(2));
3554 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3555 Context.getSizeType(), false);
3556 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3557 if (Arg.isInvalid()) return true;
3558 TheCall->setArg(2, Arg.get());
3559 }
Hal Finkelf0417332014-07-17 14:25:55 +00003560
3561 return false;
3562}
3563
Eric Christopher8d0c6212010-04-17 02:26:23 +00003564/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
3565/// TheCall is a constant expression.
3566bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
3567 llvm::APSInt &Result) {
3568 Expr *Arg = TheCall->getArg(ArgNum);
3569 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3570 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3571
3572 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
3573
3574 if (!Arg->isIntegerConstantExpr(Result, Context))
3575 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00003576 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00003577
Chris Lattnerd545ad12009-09-23 06:06:36 +00003578 return false;
3579}
3580
Richard Sandiford28940af2014-04-16 08:47:51 +00003581/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
3582/// TheCall is a constant expression in the range [Low, High].
3583bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
3584 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00003585 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00003586
3587 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00003588 Expr *Arg = TheCall->getArg(ArgNum);
3589 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00003590 return false;
3591
Eric Christopher8d0c6212010-04-17 02:26:23 +00003592 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00003593 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00003594 return true;
3595
Richard Sandiford28940af2014-04-16 08:47:51 +00003596 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00003597 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00003598 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00003599
3600 return false;
3601}
3602
Luke Cheeseman59b2d832015-06-15 17:51:01 +00003603/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
3604/// TheCall is an ARM/AArch64 special register string literal.
3605bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
3606 int ArgNum, unsigned ExpectedFieldNum,
3607 bool AllowName) {
3608 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
3609 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
3610 BuiltinID == ARM::BI__builtin_arm_rsr ||
3611 BuiltinID == ARM::BI__builtin_arm_rsrp ||
3612 BuiltinID == ARM::BI__builtin_arm_wsr ||
3613 BuiltinID == ARM::BI__builtin_arm_wsrp;
3614 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
3615 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
3616 BuiltinID == AArch64::BI__builtin_arm_rsr ||
3617 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
3618 BuiltinID == AArch64::BI__builtin_arm_wsr ||
3619 BuiltinID == AArch64::BI__builtin_arm_wsrp;
3620 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
3621
3622 // We can't check the value of a dependent argument.
3623 Expr *Arg = TheCall->getArg(ArgNum);
3624 if (Arg->isTypeDependent() || Arg->isValueDependent())
3625 return false;
3626
3627 // Check if the argument is a string literal.
3628 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3629 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
3630 << Arg->getSourceRange();
3631
3632 // Check the type of special register given.
3633 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3634 SmallVector<StringRef, 6> Fields;
3635 Reg.split(Fields, ":");
3636
3637 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
3638 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
3639 << Arg->getSourceRange();
3640
3641 // If the string is the name of a register then we cannot check that it is
3642 // valid here but if the string is of one the forms described in ACLE then we
3643 // can check that the supplied fields are integers and within the valid
3644 // ranges.
3645 if (Fields.size() > 1) {
3646 bool FiveFields = Fields.size() == 5;
3647
3648 bool ValidString = true;
3649 if (IsARMBuiltin) {
3650 ValidString &= Fields[0].startswith_lower("cp") ||
3651 Fields[0].startswith_lower("p");
3652 if (ValidString)
3653 Fields[0] =
3654 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
3655
3656 ValidString &= Fields[2].startswith_lower("c");
3657 if (ValidString)
3658 Fields[2] = Fields[2].drop_front(1);
3659
3660 if (FiveFields) {
3661 ValidString &= Fields[3].startswith_lower("c");
3662 if (ValidString)
3663 Fields[3] = Fields[3].drop_front(1);
3664 }
3665 }
3666
3667 SmallVector<int, 5> Ranges;
3668 if (FiveFields)
3669 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15});
3670 else
3671 Ranges.append({15, 7, 15});
3672
3673 for (unsigned i=0; i<Fields.size(); ++i) {
3674 int IntField;
3675 ValidString &= !Fields[i].getAsInteger(10, IntField);
3676 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
3677 }
3678
3679 if (!ValidString)
3680 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
3681 << Arg->getSourceRange();
3682
3683 } else if (IsAArch64Builtin && Fields.size() == 1) {
3684 // If the register name is one of those that appear in the condition below
3685 // and the special register builtin being used is one of the write builtins,
3686 // then we require that the argument provided for writing to the register
3687 // is an integer constant expression. This is because it will be lowered to
3688 // an MSR (immediate) instruction, so we need to know the immediate at
3689 // compile time.
3690 if (TheCall->getNumArgs() != 2)
3691 return false;
3692
3693 std::string RegLower = Reg.lower();
3694 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
3695 RegLower != "pan" && RegLower != "uao")
3696 return false;
3697
3698 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
3699 }
3700
3701 return false;
3702}
3703
Eli Friedmanc97d0142009-05-03 06:04:26 +00003704/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003705/// This checks that the target supports __builtin_longjmp and
3706/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003707bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003708 if (!Context.getTargetInfo().hasSjLjLowering())
3709 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
3710 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
3711
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003712 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00003713 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00003714
Eric Christopher8d0c6212010-04-17 02:26:23 +00003715 // TODO: This is less than ideal. Overload this to take a value.
3716 if (SemaBuiltinConstantArg(TheCall, 1, Result))
3717 return true;
3718
3719 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003720 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
3721 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
3722
3723 return false;
3724}
3725
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003726/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
3727/// This checks that the target supports __builtin_setjmp.
3728bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
3729 if (!Context.getTargetInfo().hasSjLjLowering())
3730 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
3731 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
3732 return false;
3733}
3734
Richard Smithd7293d72013-08-05 18:49:43 +00003735namespace {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003736class UncoveredArgHandler {
3737 enum { Unknown = -1, AllCovered = -2 };
3738 signed FirstUncoveredArg;
3739 SmallVector<const Expr *, 4> DiagnosticExprs;
3740
3741public:
3742 UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
3743
3744 bool hasUncoveredArg() const {
3745 return (FirstUncoveredArg >= 0);
3746 }
3747
3748 unsigned getUncoveredArg() const {
3749 assert(hasUncoveredArg() && "no uncovered argument");
3750 return FirstUncoveredArg;
3751 }
3752
3753 void setAllCovered() {
3754 // A string has been found with all arguments covered, so clear out
3755 // the diagnostics.
3756 DiagnosticExprs.clear();
3757 FirstUncoveredArg = AllCovered;
3758 }
3759
3760 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
3761 assert(NewFirstUncoveredArg >= 0 && "Outside range");
3762
3763 // Don't update if a previous string covers all arguments.
3764 if (FirstUncoveredArg == AllCovered)
3765 return;
3766
3767 // UncoveredArgHandler tracks the highest uncovered argument index
3768 // and with it all the strings that match this index.
3769 if (NewFirstUncoveredArg == FirstUncoveredArg)
3770 DiagnosticExprs.push_back(StrExpr);
3771 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
3772 DiagnosticExprs.clear();
3773 DiagnosticExprs.push_back(StrExpr);
3774 FirstUncoveredArg = NewFirstUncoveredArg;
3775 }
3776 }
3777
3778 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
3779};
3780
Richard Smithd7293d72013-08-05 18:49:43 +00003781enum StringLiteralCheckType {
3782 SLCT_NotALiteral,
3783 SLCT_UncheckedLiteral,
3784 SLCT_CheckedLiteral
3785};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003786} // end anonymous namespace
Richard Smithd7293d72013-08-05 18:49:43 +00003787
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00003788static void CheckFormatString(Sema &S, const StringLiteral *FExpr,
3789 const Expr *OrigFormatExpr,
3790 ArrayRef<const Expr *> Args,
3791 bool HasVAListArg, unsigned format_idx,
3792 unsigned firstDataArg,
3793 Sema::FormatStringType Type,
3794 bool inFunctionCall,
3795 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003796 llvm::SmallBitVector &CheckedVarArgs,
3797 UncoveredArgHandler &UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00003798
Richard Smith55ce3522012-06-25 20:30:08 +00003799// Determine if an expression is a string literal or constant string.
3800// If this function returns false on the arguments to a function expecting a
3801// format string, we will usually need to emit a warning.
3802// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00003803static StringLiteralCheckType
3804checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
3805 bool HasVAListArg, unsigned format_idx,
3806 unsigned firstDataArg, Sema::FormatStringType Type,
3807 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003808 llvm::SmallBitVector &CheckedVarArgs,
3809 UncoveredArgHandler &UncoveredArg) {
Ted Kremenek808829352010-09-09 03:51:39 +00003810 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00003811 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00003812 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003813
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003814 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00003815
Richard Smithd7293d72013-08-05 18:49:43 +00003816 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00003817 // Technically -Wformat-nonliteral does not warn about this case.
3818 // The behavior of printf and friends in this case is implementation
3819 // dependent. Ideally if the format string cannot be null then
3820 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00003821 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00003822
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003823 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00003824 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003825 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00003826 // The expression is a literal if both sub-expressions were, and it was
3827 // completely checked only if both sub-expressions were checked.
3828 const AbstractConditionalOperator *C =
3829 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003830
3831 // Determine whether it is necessary to check both sub-expressions, for
3832 // example, because the condition expression is a constant that can be
3833 // evaluated at compile time.
3834 bool CheckLeft = true, CheckRight = true;
3835
3836 bool Cond;
3837 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
3838 if (Cond)
3839 CheckRight = false;
3840 else
3841 CheckLeft = false;
3842 }
3843
3844 StringLiteralCheckType Left;
3845 if (!CheckLeft)
3846 Left = SLCT_UncheckedLiteral;
3847 else {
3848 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
3849 HasVAListArg, format_idx, firstDataArg,
3850 Type, CallType, InFunctionCall,
3851 CheckedVarArgs, UncoveredArg);
3852 if (Left == SLCT_NotALiteral || !CheckRight)
3853 return Left;
3854 }
3855
Richard Smith55ce3522012-06-25 20:30:08 +00003856 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00003857 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003858 HasVAListArg, format_idx, firstDataArg,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003859 Type, CallType, InFunctionCall, CheckedVarArgs,
3860 UncoveredArg);
3861
3862 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003863 }
3864
3865 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00003866 E = cast<ImplicitCastExpr>(E)->getSubExpr();
3867 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003868 }
3869
John McCallc07a0c72011-02-17 10:25:35 +00003870 case Stmt::OpaqueValueExprClass:
3871 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
3872 E = src;
3873 goto tryAgain;
3874 }
Richard Smith55ce3522012-06-25 20:30:08 +00003875 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00003876
Ted Kremeneka8890832011-02-24 23:03:04 +00003877 case Stmt::PredefinedExprClass:
3878 // While __func__, etc., are technically not string literals, they
3879 // cannot contain format specifiers and thus are not a security
3880 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00003881 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00003882
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003883 case Stmt::DeclRefExprClass: {
3884 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00003885
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003886 // As an exception, do not flag errors for variables binding to
3887 // const string literals.
3888 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
3889 bool isConstant = false;
3890 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003891
Richard Smithd7293d72013-08-05 18:49:43 +00003892 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
3893 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00003894 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00003895 isConstant = T.isConstant(S.Context) &&
3896 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00003897 } else if (T->isObjCObjectPointerType()) {
3898 // In ObjC, there is usually no "const ObjectPointer" type,
3899 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00003900 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003901 }
Mike Stump11289f42009-09-09 15:08:12 +00003902
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003903 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00003904 if (const Expr *Init = VD->getAnyInitializer()) {
3905 // Look through initializers like const char c[] = { "foo" }
3906 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3907 if (InitList->isStringLiteralInit())
3908 Init = InitList->getInit(0)->IgnoreParenImpCasts();
3909 }
Richard Smithd7293d72013-08-05 18:49:43 +00003910 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003911 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003912 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003913 /*InFunctionCall*/false, CheckedVarArgs,
3914 UncoveredArg);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00003915 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003916 }
Mike Stump11289f42009-09-09 15:08:12 +00003917
Anders Carlssonb012ca92009-06-28 19:55:58 +00003918 // For vprintf* functions (i.e., HasVAListArg==true), we add a
3919 // special check to see if the format string is a function parameter
3920 // of the function calling the printf function. If the function
3921 // has an attribute indicating it is a printf-like function, then we
3922 // should suppress warnings concerning non-literals being used in a call
3923 // to a vprintf function. For example:
3924 //
3925 // void
3926 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
3927 // va_list ap;
3928 // va_start(ap, fmt);
3929 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
3930 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00003931 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003932 if (HasVAListArg) {
3933 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
3934 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
3935 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003936 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003937 // adjust for implicit parameter
3938 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
3939 if (MD->isInstance())
3940 ++PVIndex;
3941 // We also check if the formats are compatible.
3942 // We can't pass a 'scanf' string to a 'printf' function.
3943 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00003944 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00003945 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003946 }
3947 }
3948 }
3949 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003950 }
Mike Stump11289f42009-09-09 15:08:12 +00003951
Richard Smith55ce3522012-06-25 20:30:08 +00003952 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003953 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003954
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00003955 case Stmt::CallExprClass:
3956 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003957 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00003958 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
3959 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
3960 unsigned ArgIndex = FA->getFormatIdx();
3961 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
3962 if (MD->isInstance())
3963 --ArgIndex;
3964 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00003965
Richard Smithd7293d72013-08-05 18:49:43 +00003966 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003967 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00003968 Type, CallType, InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003969 CheckedVarArgs, UncoveredArg);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003970 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3971 unsigned BuiltinID = FD->getBuiltinID();
3972 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
3973 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
3974 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00003975 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003976 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003977 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003978 InFunctionCall, CheckedVarArgs,
3979 UncoveredArg);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003980 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003981 }
3982 }
Mike Stump11289f42009-09-09 15:08:12 +00003983
Richard Smith55ce3522012-06-25 20:30:08 +00003984 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003985 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003986 case Stmt::ObjCStringLiteralClass:
3987 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00003988 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003989
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003990 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003991 StrE = ObjCFExpr->getString();
3992 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003993 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00003994
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003995 if (StrE) {
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00003996 CheckFormatString(S, StrE, E, Args, HasVAListArg, format_idx,
3997 firstDataArg, Type, InFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00003998 CheckedVarArgs, UncoveredArg);
Richard Smith55ce3522012-06-25 20:30:08 +00003999 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004000 }
Mike Stump11289f42009-09-09 15:08:12 +00004001
Richard Smith55ce3522012-06-25 20:30:08 +00004002 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004003 }
Mike Stump11289f42009-09-09 15:08:12 +00004004
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004005 default:
Richard Smith55ce3522012-06-25 20:30:08 +00004006 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004007 }
4008}
4009
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004010Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00004011 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004012 .Case("scanf", FST_Scanf)
4013 .Cases("printf", "printf0", FST_Printf)
4014 .Cases("NSString", "CFString", FST_NSString)
4015 .Case("strftime", FST_Strftime)
4016 .Case("strfmon", FST_Strfmon)
4017 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004018 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00004019 .Case("os_trace", FST_OSTrace)
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004020 .Default(FST_Unknown);
4021}
4022
Jordan Rose3e0ec582012-07-19 18:10:23 +00004023/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00004024/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00004025/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004026bool Sema::CheckFormatArguments(const FormatAttr *Format,
4027 ArrayRef<const Expr *> Args,
4028 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004029 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00004030 SourceLocation Loc, SourceRange Range,
4031 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00004032 FormatStringInfo FSI;
4033 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004034 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00004035 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00004036 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00004037 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004038}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00004039
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004040bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004041 bool HasVAListArg, unsigned format_idx,
4042 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004043 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00004044 SourceLocation Loc, SourceRange Range,
4045 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00004046 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004047 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004048 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00004049 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004050 }
Mike Stump11289f42009-09-09 15:08:12 +00004051
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004052 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00004053
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004054 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00004055 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004056 // Dynamically generated format strings are difficult to
4057 // automatically vet at compile time. Requiring that format strings
4058 // are string literals: (1) permits the checking of format strings by
4059 // the compiler and thereby (2) can practically remove the source of
4060 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00004061
Mike Stump11289f42009-09-09 15:08:12 +00004062 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00004063 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00004064 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00004065 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004066 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00004067 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00004068 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
4069 format_idx, firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004070 /*IsFunctionCall*/true, CheckedVarArgs,
4071 UncoveredArg);
4072
4073 // Generate a diagnostic where an uncovered argument is detected.
4074 if (UncoveredArg.hasUncoveredArg()) {
4075 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
4076 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
4077 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
4078 }
4079
Richard Smith55ce3522012-06-25 20:30:08 +00004080 if (CT != SLCT_NotALiteral)
4081 // Literal format string found, check done!
4082 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00004083
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00004084 // Strftime is particular as it always uses a single 'time' argument,
4085 // so it is safe to pass a non-literal string.
4086 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00004087 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00004088
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00004089 // Do not emit diag when the string param is a macro expansion and the
4090 // format is either NSString or CFString. This is a hack to prevent
4091 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
4092 // which are usually used in place of NS and CF string literals.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004093 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
4094 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
Richard Smith55ce3522012-06-25 20:30:08 +00004095 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00004096
Chris Lattnercc5d1c22009-04-29 04:59:47 +00004097 // If there are no arguments specified, warn with -Wformat-security, otherwise
4098 // warn only with -Wformat-nonliteral.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004099 if (Args.size() == firstDataArg) {
Bob Wilson57819fc2016-03-15 20:56:38 +00004100 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
4101 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004102 switch (Type) {
4103 default:
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004104 break;
4105 case FST_Kprintf:
4106 case FST_FreeBSDKPrintf:
4107 case FST_Printf:
Bob Wilson57819fc2016-03-15 20:56:38 +00004108 Diag(FormatLoc, diag::note_format_security_fixit)
4109 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004110 break;
4111 case FST_NSString:
Bob Wilson57819fc2016-03-15 20:56:38 +00004112 Diag(FormatLoc, diag::note_format_security_fixit)
4113 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004114 break;
4115 }
4116 } else {
4117 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00004118 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004119 }
Richard Smith55ce3522012-06-25 20:30:08 +00004120 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004121}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004122
Ted Kremenekab278de2010-01-28 23:39:18 +00004123namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00004124class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
4125protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00004126 Sema &S;
4127 const StringLiteral *FExpr;
4128 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00004129 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00004130 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00004131 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00004132 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004133 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00004134 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00004135 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00004136 bool usesPositionalArgs;
4137 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00004138 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00004139 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00004140 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004141 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004142
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004143public:
Ted Kremenek02087932010-07-16 02:11:22 +00004144 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00004145 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004146 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004147 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004148 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00004149 Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004150 llvm::SmallBitVector &CheckedVarArgs,
4151 UncoveredArgHandler &UncoveredArg)
Ted Kremenekab278de2010-01-28 23:39:18 +00004152 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004153 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
4154 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004155 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00004156 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00004157 inFunctionCall(inFunctionCall), CallType(callType),
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004158 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00004159 CoveredArgs.resize(numDataArgs);
4160 CoveredArgs.reset();
4161 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004162
Ted Kremenek019d2242010-01-29 01:50:07 +00004163 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004164
Ted Kremenek02087932010-07-16 02:11:22 +00004165 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004166 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004167
Jordan Rose92303592012-09-08 04:00:03 +00004168 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00004169 const analyze_format_string::FormatSpecifier &FS,
4170 const analyze_format_string::ConversionSpecifier &CS,
4171 const char *startSpecifier, unsigned specifierLen,
4172 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00004173
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004174 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00004175 const analyze_format_string::FormatSpecifier &FS,
4176 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004177
4178 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00004179 const analyze_format_string::ConversionSpecifier &CS,
4180 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004181
Craig Toppere14c0f82014-03-12 04:55:44 +00004182 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00004183
Craig Toppere14c0f82014-03-12 04:55:44 +00004184 void HandleInvalidPosition(const char *startSpecifier,
4185 unsigned specifierLen,
4186 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00004187
Craig Toppere14c0f82014-03-12 04:55:44 +00004188 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00004189
Craig Toppere14c0f82014-03-12 04:55:44 +00004190 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004191
Richard Trieu03cf7b72011-10-28 00:41:25 +00004192 template <typename Range>
Benjamin Kramer7320b992016-06-15 14:20:56 +00004193 static void
4194 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
4195 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
4196 bool IsStringLocation, Range StringRange,
4197 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00004198
Ted Kremenek02087932010-07-16 02:11:22 +00004199protected:
Ted Kremenekce815422010-07-19 21:25:57 +00004200 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
4201 const char *startSpec,
4202 unsigned specifierLen,
4203 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00004204
4205 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
4206 const char *startSpec,
4207 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00004208
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004209 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00004210 CharSourceRange getSpecifierRange(const char *startSpecifier,
4211 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00004212 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004213
Ted Kremenek5739de72010-01-29 01:06:55 +00004214 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004215
4216 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
4217 const analyze_format_string::ConversionSpecifier &CS,
4218 const char *startSpecifier, unsigned specifierLen,
4219 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00004220
4221 template <typename Range>
4222 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
4223 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00004224 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00004225};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004226} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00004227
Ted Kremenek02087932010-07-16 02:11:22 +00004228SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00004229 return OrigFormatExpr->getSourceRange();
4230}
4231
Ted Kremenek02087932010-07-16 02:11:22 +00004232CharSourceRange CheckFormatHandler::
4233getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00004234 SourceLocation Start = getLocationOfByte(startSpecifier);
4235 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
4236
4237 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00004238 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00004239
4240 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004241}
4242
Ted Kremenek02087932010-07-16 02:11:22 +00004243SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004244 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00004245}
4246
Ted Kremenek02087932010-07-16 02:11:22 +00004247void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
4248 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00004249 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
4250 getLocationOfByte(startSpecifier),
4251 /*IsStringLocation*/true,
4252 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00004253}
4254
Jordan Rose92303592012-09-08 04:00:03 +00004255void CheckFormatHandler::HandleInvalidLengthModifier(
4256 const analyze_format_string::FormatSpecifier &FS,
4257 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00004258 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00004259 using namespace analyze_format_string;
4260
4261 const LengthModifier &LM = FS.getLengthModifier();
4262 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4263
4264 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00004265 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00004266 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004267 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00004268 getLocationOfByte(LM.getStart()),
4269 /*IsStringLocation*/true,
4270 getSpecifierRange(startSpecifier, specifierLen));
4271
4272 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4273 << FixedLM->toString()
4274 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
4275
4276 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004277 FixItHint Hint;
4278 if (DiagID == diag::warn_format_nonsensical_length)
4279 Hint = FixItHint::CreateRemoval(LMRange);
4280
4281 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00004282 getLocationOfByte(LM.getStart()),
4283 /*IsStringLocation*/true,
4284 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00004285 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00004286 }
4287}
4288
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004289void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00004290 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004291 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004292 using namespace analyze_format_string;
4293
4294 const LengthModifier &LM = FS.getLengthModifier();
4295 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4296
4297 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00004298 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00004299 if (FixedLM) {
4300 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4301 << LM.toString() << 0,
4302 getLocationOfByte(LM.getStart()),
4303 /*IsStringLocation*/true,
4304 getSpecifierRange(startSpecifier, specifierLen));
4305
4306 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4307 << FixedLM->toString()
4308 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
4309
4310 } else {
4311 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4312 << LM.toString() << 0,
4313 getLocationOfByte(LM.getStart()),
4314 /*IsStringLocation*/true,
4315 getSpecifierRange(startSpecifier, specifierLen));
4316 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004317}
4318
4319void CheckFormatHandler::HandleNonStandardConversionSpecifier(
4320 const analyze_format_string::ConversionSpecifier &CS,
4321 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00004322 using namespace analyze_format_string;
4323
4324 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00004325 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00004326 if (FixedCS) {
4327 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4328 << CS.toString() << /*conversion specifier*/1,
4329 getLocationOfByte(CS.getStart()),
4330 /*IsStringLocation*/true,
4331 getSpecifierRange(startSpecifier, specifierLen));
4332
4333 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
4334 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
4335 << FixedCS->toString()
4336 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
4337 } else {
4338 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4339 << CS.toString() << /*conversion specifier*/1,
4340 getLocationOfByte(CS.getStart()),
4341 /*IsStringLocation*/true,
4342 getSpecifierRange(startSpecifier, specifierLen));
4343 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004344}
4345
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00004346void CheckFormatHandler::HandlePosition(const char *startPos,
4347 unsigned posLen) {
4348 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
4349 getLocationOfByte(startPos),
4350 /*IsStringLocation*/true,
4351 getSpecifierRange(startPos, posLen));
4352}
4353
Ted Kremenekd1668192010-02-27 01:41:03 +00004354void
Ted Kremenek02087932010-07-16 02:11:22 +00004355CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
4356 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004357 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
4358 << (unsigned) p,
4359 getLocationOfByte(startPos), /*IsStringLocation*/true,
4360 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00004361}
4362
Ted Kremenek02087932010-07-16 02:11:22 +00004363void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00004364 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004365 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
4366 getLocationOfByte(startPos),
4367 /*IsStringLocation*/true,
4368 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00004369}
4370
Ted Kremenek02087932010-07-16 02:11:22 +00004371void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004372 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00004373 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00004374 EmitFormatDiagnostic(
4375 S.PDiag(diag::warn_printf_format_string_contains_null_char),
4376 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
4377 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00004378 }
Ted Kremenek02087932010-07-16 02:11:22 +00004379}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004380
Jordan Rose58bbe422012-07-19 18:10:08 +00004381// Note that this may return NULL if there was an error parsing or building
4382// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00004383const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004384 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00004385}
4386
4387void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004388 // Does the number of data arguments exceed the number of
4389 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00004390 if (!HasVAListArg) {
4391 // Find any arguments that weren't covered.
4392 CoveredArgs.flip();
4393 signed notCoveredArg = CoveredArgs.find_first();
4394 if (notCoveredArg >= 0) {
4395 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004396 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
4397 } else {
4398 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00004399 }
4400 }
4401}
4402
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004403void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
4404 const Expr *ArgExpr) {
4405 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
4406 "Invalid state");
4407
4408 if (!ArgExpr)
4409 return;
4410
4411 SourceLocation Loc = ArgExpr->getLocStart();
4412
4413 if (S.getSourceManager().isInSystemMacro(Loc))
4414 return;
4415
4416 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
4417 for (auto E : DiagnosticExprs)
4418 PDiag << E->getSourceRange();
4419
4420 CheckFormatHandler::EmitFormatDiagnostic(
4421 S, IsFunctionCall, DiagnosticExprs[0],
4422 PDiag, Loc, /*IsStringLocation*/false,
4423 DiagnosticExprs[0]->getSourceRange());
4424}
4425
Ted Kremenekce815422010-07-19 21:25:57 +00004426bool
4427CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
4428 SourceLocation Loc,
4429 const char *startSpec,
4430 unsigned specifierLen,
4431 const char *csStart,
4432 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00004433 bool keepGoing = true;
4434 if (argIndex < NumDataArgs) {
4435 // Consider the argument coverered, even though the specifier doesn't
4436 // make sense.
4437 CoveredArgs.set(argIndex);
4438 }
4439 else {
4440 // If argIndex exceeds the number of data arguments we
4441 // don't issue a warning because that is just a cascade of warnings (and
4442 // they may have intended '%%' anyway). We don't want to continue processing
4443 // the format string after this point, however, as we will like just get
4444 // gibberish when trying to match arguments.
4445 keepGoing = false;
4446 }
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00004447
4448 StringRef Specifier(csStart, csLen);
4449
4450 // If the specifier in non-printable, it could be the first byte of a UTF-8
4451 // sequence. In that case, print the UTF-8 code point. If not, print the byte
4452 // hex value.
4453 std::string CodePointStr;
4454 if (!llvm::sys::locale::isPrint(*csStart)) {
4455 UTF32 CodePoint;
4456 const UTF8 **B = reinterpret_cast<const UTF8 **>(&csStart);
4457 const UTF8 *E =
4458 reinterpret_cast<const UTF8 *>(csStart + csLen);
4459 ConversionResult Result =
4460 llvm::convertUTF8Sequence(B, E, &CodePoint, strictConversion);
4461
4462 if (Result != conversionOK) {
4463 unsigned char FirstChar = *csStart;
4464 CodePoint = (UTF32)FirstChar;
4465 }
4466
4467 llvm::raw_string_ostream OS(CodePointStr);
4468 if (CodePoint < 256)
4469 OS << "\\x" << llvm::format("%02x", CodePoint);
4470 else if (CodePoint <= 0xFFFF)
4471 OS << "\\u" << llvm::format("%04x", CodePoint);
4472 else
4473 OS << "\\U" << llvm::format("%08x", CodePoint);
4474 OS.flush();
4475 Specifier = CodePointStr;
4476 }
4477
4478 EmitFormatDiagnostic(
4479 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
4480 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
4481
Ted Kremenekce815422010-07-19 21:25:57 +00004482 return keepGoing;
4483}
4484
Richard Trieu03cf7b72011-10-28 00:41:25 +00004485void
4486CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
4487 const char *startSpec,
4488 unsigned specifierLen) {
4489 EmitFormatDiagnostic(
4490 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
4491 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
4492}
4493
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004494bool
4495CheckFormatHandler::CheckNumArgs(
4496 const analyze_format_string::FormatSpecifier &FS,
4497 const analyze_format_string::ConversionSpecifier &CS,
4498 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
4499
4500 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004501 PartialDiagnostic PDiag = FS.usesPositionalArg()
4502 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
4503 << (argIndex+1) << NumDataArgs)
4504 : S.PDiag(diag::warn_printf_insufficient_data_args);
4505 EmitFormatDiagnostic(
4506 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
4507 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004508
4509 // Since more arguments than conversion tokens are given, by extension
4510 // all arguments are covered, so mark this as so.
4511 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004512 return false;
4513 }
4514 return true;
4515}
4516
Richard Trieu03cf7b72011-10-28 00:41:25 +00004517template<typename Range>
4518void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
4519 SourceLocation Loc,
4520 bool IsStringLocation,
4521 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00004522 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004523 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00004524 Loc, IsStringLocation, StringRange, FixIt);
4525}
4526
4527/// \brief If the format string is not within the funcion call, emit a note
4528/// so that the function call and string are in diagnostic messages.
4529///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00004530/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00004531/// call and only one diagnostic message will be produced. Otherwise, an
4532/// extra note will be emitted pointing to location of the format string.
4533///
4534/// \param ArgumentExpr the expression that is passed as the format string
4535/// argument in the function call. Used for getting locations when two
4536/// diagnostics are emitted.
4537///
4538/// \param PDiag the callee should already have provided any strings for the
4539/// diagnostic message. This function only adds locations and fixits
4540/// to diagnostics.
4541///
4542/// \param Loc primary location for diagnostic. If two diagnostics are
4543/// required, one will be at Loc and a new SourceLocation will be created for
4544/// the other one.
4545///
4546/// \param IsStringLocation if true, Loc points to the format string should be
4547/// used for the note. Otherwise, Loc points to the argument list and will
4548/// be used with PDiag.
4549///
4550/// \param StringRange some or all of the string to highlight. This is
4551/// templated so it can accept either a CharSourceRange or a SourceRange.
4552///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00004553/// \param FixIt optional fix it hint for the format string.
Benjamin Kramer7320b992016-06-15 14:20:56 +00004554template <typename Range>
4555void CheckFormatHandler::EmitFormatDiagnostic(
4556 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
4557 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
4558 Range StringRange, ArrayRef<FixItHint> FixIt) {
Jordan Roseaee34382012-09-05 22:56:26 +00004559 if (InFunctionCall) {
4560 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
4561 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00004562 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00004563 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004564 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
4565 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00004566
4567 const Sema::SemaDiagnosticBuilder &Note =
4568 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
4569 diag::note_format_string_defined);
4570
4571 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00004572 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00004573 }
4574}
4575
Ted Kremenek02087932010-07-16 02:11:22 +00004576//===--- CHECK: Printf format string checking ------------------------------===//
4577
4578namespace {
4579class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004580 bool ObjCContext;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004581
Ted Kremenek02087932010-07-16 02:11:22 +00004582public:
4583 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
4584 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004585 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00004586 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004587 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004588 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00004589 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004590 llvm::SmallBitVector &CheckedVarArgs,
4591 UncoveredArgHandler &UncoveredArg)
Richard Smithd7293d72013-08-05 18:49:43 +00004592 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
4593 numDataArgs, beg, hasVAListArg, Args,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004594 formatIdx, inFunctionCall, CallType, CheckedVarArgs,
4595 UncoveredArg),
Richard Smithd7293d72013-08-05 18:49:43 +00004596 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00004597 {}
4598
Ted Kremenek02087932010-07-16 02:11:22 +00004599 bool HandleInvalidPrintfConversionSpecifier(
4600 const analyze_printf::PrintfSpecifier &FS,
4601 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004602 unsigned specifierLen) override;
4603
Ted Kremenek02087932010-07-16 02:11:22 +00004604 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
4605 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004606 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00004607 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
4608 const char *StartSpecifier,
4609 unsigned SpecifierLen,
4610 const Expr *E);
4611
Ted Kremenek02087932010-07-16 02:11:22 +00004612 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
4613 const char *startSpecifier, unsigned specifierLen);
4614 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
4615 const analyze_printf::OptionalAmount &Amt,
4616 unsigned type,
4617 const char *startSpecifier, unsigned specifierLen);
4618 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
4619 const analyze_printf::OptionalFlag &flag,
4620 const char *startSpecifier, unsigned specifierLen);
4621 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
4622 const analyze_printf::OptionalFlag &ignoredFlag,
4623 const analyze_printf::OptionalFlag &flag,
4624 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004625 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00004626 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00004627
4628 void HandleEmptyObjCModifierFlag(const char *startFlag,
4629 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00004630
Ted Kremenek2b417712015-07-02 05:39:16 +00004631 void HandleInvalidObjCModifierFlag(const char *startFlag,
4632 unsigned flagLen) override;
4633
4634 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
4635 const char *flagsEnd,
4636 const char *conversionPosition)
4637 override;
4638};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004639} // end anonymous namespace
Ted Kremenek02087932010-07-16 02:11:22 +00004640
4641bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
4642 const analyze_printf::PrintfSpecifier &FS,
4643 const char *startSpecifier,
4644 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004645 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00004646 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00004647
Ted Kremenekce815422010-07-19 21:25:57 +00004648 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
4649 getLocationOfByte(CS.getStart()),
4650 startSpecifier, specifierLen,
4651 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00004652}
4653
Ted Kremenek02087932010-07-16 02:11:22 +00004654bool CheckPrintfHandler::HandleAmount(
4655 const analyze_format_string::OptionalAmount &Amt,
4656 unsigned k, const char *startSpecifier,
4657 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004658 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004659 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00004660 unsigned argIndex = Amt.getArgIndex();
4661 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004662 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
4663 << k,
4664 getLocationOfByte(Amt.getStart()),
4665 /*IsStringLocation*/true,
4666 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00004667 // Don't do any more checking. We will just emit
4668 // spurious errors.
4669 return false;
4670 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004671
Ted Kremenek5739de72010-01-29 01:06:55 +00004672 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00004673 // Although not in conformance with C99, we also allow the argument to be
4674 // an 'unsigned int' as that is a reasonably safe case. GCC also
4675 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00004676 CoveredArgs.set(argIndex);
4677 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00004678 if (!Arg)
4679 return false;
4680
Ted Kremenek5739de72010-01-29 01:06:55 +00004681 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004682
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004683 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
4684 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004685
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004686 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004687 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004688 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00004689 << T << Arg->getSourceRange(),
4690 getLocationOfByte(Amt.getStart()),
4691 /*IsStringLocation*/true,
4692 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00004693 // Don't do any more checking. We will just emit
4694 // spurious errors.
4695 return false;
4696 }
4697 }
4698 }
4699 return true;
4700}
Ted Kremenek5739de72010-01-29 01:06:55 +00004701
Tom Careb49ec692010-06-17 19:00:27 +00004702void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00004703 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004704 const analyze_printf::OptionalAmount &Amt,
4705 unsigned type,
4706 const char *startSpecifier,
4707 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004708 const analyze_printf::PrintfConversionSpecifier &CS =
4709 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00004710
Richard Trieu03cf7b72011-10-28 00:41:25 +00004711 FixItHint fixit =
4712 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
4713 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
4714 Amt.getConstantLength()))
4715 : FixItHint();
4716
4717 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
4718 << type << CS.toString(),
4719 getLocationOfByte(Amt.getStart()),
4720 /*IsStringLocation*/true,
4721 getSpecifierRange(startSpecifier, specifierLen),
4722 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00004723}
4724
Ted Kremenek02087932010-07-16 02:11:22 +00004725void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004726 const analyze_printf::OptionalFlag &flag,
4727 const char *startSpecifier,
4728 unsigned specifierLen) {
4729 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004730 const analyze_printf::PrintfConversionSpecifier &CS =
4731 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00004732 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
4733 << flag.toString() << CS.toString(),
4734 getLocationOfByte(flag.getPosition()),
4735 /*IsStringLocation*/true,
4736 getSpecifierRange(startSpecifier, specifierLen),
4737 FixItHint::CreateRemoval(
4738 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00004739}
4740
4741void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00004742 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004743 const analyze_printf::OptionalFlag &ignoredFlag,
4744 const analyze_printf::OptionalFlag &flag,
4745 const char *startSpecifier,
4746 unsigned specifierLen) {
4747 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00004748 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
4749 << ignoredFlag.toString() << flag.toString(),
4750 getLocationOfByte(ignoredFlag.getPosition()),
4751 /*IsStringLocation*/true,
4752 getSpecifierRange(startSpecifier, specifierLen),
4753 FixItHint::CreateRemoval(
4754 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00004755}
4756
Ted Kremenek2b417712015-07-02 05:39:16 +00004757// void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
4758// bool IsStringLocation, Range StringRange,
4759// ArrayRef<FixItHint> Fixit = None);
4760
4761void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
4762 unsigned flagLen) {
4763 // Warn about an empty flag.
4764 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
4765 getLocationOfByte(startFlag),
4766 /*IsStringLocation*/true,
4767 getSpecifierRange(startFlag, flagLen));
4768}
4769
4770void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
4771 unsigned flagLen) {
4772 // Warn about an invalid flag.
4773 auto Range = getSpecifierRange(startFlag, flagLen);
4774 StringRef flag(startFlag, flagLen);
4775 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
4776 getLocationOfByte(startFlag),
4777 /*IsStringLocation*/true,
4778 Range, FixItHint::CreateRemoval(Range));
4779}
4780
4781void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
4782 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
4783 // Warn about using '[...]' without a '@' conversion.
4784 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
4785 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
4786 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
4787 getLocationOfByte(conversionPosition),
4788 /*IsStringLocation*/true,
4789 Range, FixItHint::CreateRemoval(Range));
4790}
4791
Richard Smith55ce3522012-06-25 20:30:08 +00004792// Determines if the specified is a C++ class or struct containing
4793// a member with the specified name and kind (e.g. a CXXMethodDecl named
4794// "c_str()").
4795template<typename MemberKind>
4796static llvm::SmallPtrSet<MemberKind*, 1>
4797CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
4798 const RecordType *RT = Ty->getAs<RecordType>();
4799 llvm::SmallPtrSet<MemberKind*, 1> Results;
4800
4801 if (!RT)
4802 return Results;
4803 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00004804 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00004805 return Results;
4806
Alp Tokerb6cc5922014-05-03 03:45:55 +00004807 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00004808 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00004809 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00004810
4811 // We just need to include all members of the right kind turned up by the
4812 // filter, at this point.
4813 if (S.LookupQualifiedName(R, RT->getDecl()))
4814 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
4815 NamedDecl *decl = (*I)->getUnderlyingDecl();
4816 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
4817 Results.insert(FK);
4818 }
4819 return Results;
4820}
4821
Richard Smith2868a732014-02-28 01:36:39 +00004822/// Check if we could call '.c_str()' on an object.
4823///
4824/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
4825/// allow the call, or if it would be ambiguous).
4826bool Sema::hasCStrMethod(const Expr *E) {
4827 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
4828 MethodSet Results =
4829 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
4830 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
4831 MI != ME; ++MI)
4832 if ((*MI)->getMinRequiredArguments() == 0)
4833 return true;
4834 return false;
4835}
4836
Richard Smith55ce3522012-06-25 20:30:08 +00004837// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004838// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00004839// Returns true when a c_str() conversion method is found.
4840bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00004841 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00004842 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
4843
4844 MethodSet Results =
4845 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
4846
4847 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
4848 MI != ME; ++MI) {
4849 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00004850 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00004851 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00004852 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00004853 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00004854 S.Diag(E->getLocStart(), diag::note_printf_c_str)
4855 << "c_str()"
4856 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
4857 return true;
4858 }
4859 }
4860
4861 return false;
4862}
4863
Ted Kremenekab278de2010-01-28 23:39:18 +00004864bool
Ted Kremenek02087932010-07-16 02:11:22 +00004865CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00004866 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00004867 const char *startSpecifier,
4868 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004869 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00004870 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004871 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00004872
Ted Kremenek6cd69422010-07-19 22:01:06 +00004873 if (FS.consumesDataArgument()) {
4874 if (atFirstArg) {
4875 atFirstArg = false;
4876 usesPositionalArgs = FS.usesPositionalArg();
4877 }
4878 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004879 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
4880 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00004881 return false;
4882 }
Ted Kremenek5739de72010-01-29 01:06:55 +00004883 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004884
Ted Kremenekd1668192010-02-27 01:41:03 +00004885 // First check if the field width, precision, and conversion specifier
4886 // have matching data arguments.
4887 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
4888 startSpecifier, specifierLen)) {
4889 return false;
4890 }
4891
4892 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
4893 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004894 return false;
4895 }
4896
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004897 if (!CS.consumesDataArgument()) {
4898 // FIXME: Technically specifying a precision or field width here
4899 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00004900 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004901 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004902
Ted Kremenek4a49d982010-02-26 19:18:41 +00004903 // Consume the argument.
4904 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00004905 if (argIndex < NumDataArgs) {
4906 // The check to see if the argIndex is valid will come later.
4907 // We set the bit here because we may exit early from this
4908 // function if we encounter some other error.
4909 CoveredArgs.set(argIndex);
4910 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00004911
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004912 // FreeBSD kernel extensions.
4913 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
4914 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
4915 // We need at least two arguments.
4916 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
4917 return false;
4918
4919 // Claim the second argument.
4920 CoveredArgs.set(argIndex + 1);
4921
4922 // Type check the first argument (int for %b, pointer for %D)
4923 const Expr *Ex = getDataArg(argIndex);
4924 const analyze_printf::ArgType &AT =
4925 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
4926 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
4927 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
4928 EmitFormatDiagnostic(
4929 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4930 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
4931 << false << Ex->getSourceRange(),
4932 Ex->getLocStart(), /*IsStringLocation*/false,
4933 getSpecifierRange(startSpecifier, specifierLen));
4934
4935 // Type check the second argument (char * for both %b and %D)
4936 Ex = getDataArg(argIndex + 1);
4937 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
4938 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
4939 EmitFormatDiagnostic(
4940 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4941 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
4942 << false << Ex->getSourceRange(),
4943 Ex->getLocStart(), /*IsStringLocation*/false,
4944 getSpecifierRange(startSpecifier, specifierLen));
4945
4946 return true;
4947 }
4948
Ted Kremenek4a49d982010-02-26 19:18:41 +00004949 // Check for using an Objective-C specific conversion specifier
4950 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004951 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00004952 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
4953 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00004954 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004955
Tom Careb49ec692010-06-17 19:00:27 +00004956 // Check for invalid use of field width
4957 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00004958 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00004959 startSpecifier, specifierLen);
4960 }
4961
4962 // Check for invalid use of precision
4963 if (!FS.hasValidPrecision()) {
4964 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
4965 startSpecifier, specifierLen);
4966 }
4967
4968 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00004969 if (!FS.hasValidThousandsGroupingPrefix())
4970 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004971 if (!FS.hasValidLeadingZeros())
4972 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
4973 if (!FS.hasValidPlusPrefix())
4974 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00004975 if (!FS.hasValidSpacePrefix())
4976 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004977 if (!FS.hasValidAlternativeForm())
4978 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
4979 if (!FS.hasValidLeftJustified())
4980 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
4981
4982 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00004983 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
4984 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
4985 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004986 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
4987 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
4988 startSpecifier, specifierLen);
4989
4990 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00004991 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00004992 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4993 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00004994 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004995 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00004996 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004997 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4998 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00004999
Jordan Rose92303592012-09-08 04:00:03 +00005000 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
5001 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5002
Ted Kremenek9fcd8302010-01-29 01:43:31 +00005003 // The remaining checks depend on the data arguments.
5004 if (HasVAListArg)
5005 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005006
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005007 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00005008 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005009
Jordan Rose58bbe422012-07-19 18:10:08 +00005010 const Expr *Arg = getDataArg(argIndex);
5011 if (!Arg)
5012 return true;
5013
5014 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00005015}
5016
Jordan Roseaee34382012-09-05 22:56:26 +00005017static bool requiresParensToAddCast(const Expr *E) {
5018 // FIXME: We should have a general way to reason about operator
5019 // precedence and whether parens are actually needed here.
5020 // Take care of a few common cases where they aren't.
5021 const Expr *Inside = E->IgnoreImpCasts();
5022 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
5023 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
5024
5025 switch (Inside->getStmtClass()) {
5026 case Stmt::ArraySubscriptExprClass:
5027 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005028 case Stmt::CharacterLiteralClass:
5029 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005030 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005031 case Stmt::FloatingLiteralClass:
5032 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005033 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005034 case Stmt::ObjCArrayLiteralClass:
5035 case Stmt::ObjCBoolLiteralExprClass:
5036 case Stmt::ObjCBoxedExprClass:
5037 case Stmt::ObjCDictionaryLiteralClass:
5038 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005039 case Stmt::ObjCIvarRefExprClass:
5040 case Stmt::ObjCMessageExprClass:
5041 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005042 case Stmt::ObjCStringLiteralClass:
5043 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005044 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005045 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005046 case Stmt::UnaryOperatorClass:
5047 return false;
5048 default:
5049 return true;
5050 }
5051}
5052
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005053static std::pair<QualType, StringRef>
5054shouldNotPrintDirectly(const ASTContext &Context,
5055 QualType IntendedTy,
5056 const Expr *E) {
5057 // Use a 'while' to peel off layers of typedefs.
5058 QualType TyTy = IntendedTy;
5059 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
5060 StringRef Name = UserTy->getDecl()->getName();
5061 QualType CastTy = llvm::StringSwitch<QualType>(Name)
5062 .Case("NSInteger", Context.LongTy)
5063 .Case("NSUInteger", Context.UnsignedLongTy)
5064 .Case("SInt32", Context.IntTy)
5065 .Case("UInt32", Context.UnsignedIntTy)
5066 .Default(QualType());
5067
5068 if (!CastTy.isNull())
5069 return std::make_pair(CastTy, Name);
5070
5071 TyTy = UserTy->desugar();
5072 }
5073
5074 // Strip parens if necessary.
5075 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
5076 return shouldNotPrintDirectly(Context,
5077 PE->getSubExpr()->getType(),
5078 PE->getSubExpr());
5079
5080 // If this is a conditional expression, then its result type is constructed
5081 // via usual arithmetic conversions and thus there might be no necessary
5082 // typedef sugar there. Recurse to operands to check for NSInteger &
5083 // Co. usage condition.
5084 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5085 QualType TrueTy, FalseTy;
5086 StringRef TrueName, FalseName;
5087
5088 std::tie(TrueTy, TrueName) =
5089 shouldNotPrintDirectly(Context,
5090 CO->getTrueExpr()->getType(),
5091 CO->getTrueExpr());
5092 std::tie(FalseTy, FalseName) =
5093 shouldNotPrintDirectly(Context,
5094 CO->getFalseExpr()->getType(),
5095 CO->getFalseExpr());
5096
5097 if (TrueTy == FalseTy)
5098 return std::make_pair(TrueTy, TrueName);
5099 else if (TrueTy.isNull())
5100 return std::make_pair(FalseTy, FalseName);
5101 else if (FalseTy.isNull())
5102 return std::make_pair(TrueTy, TrueName);
5103 }
5104
5105 return std::make_pair(QualType(), StringRef());
5106}
5107
Richard Smith55ce3522012-06-25 20:30:08 +00005108bool
5109CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5110 const char *StartSpecifier,
5111 unsigned SpecifierLen,
5112 const Expr *E) {
5113 using namespace analyze_format_string;
5114 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005115 // Now type check the data expression that matches the
5116 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005117 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
5118 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00005119 if (!AT.isValid())
5120 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00005121
Jordan Rose598ec092012-12-05 18:44:40 +00005122 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00005123 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
5124 ExprTy = TET->getUnderlyingExpr()->getType();
5125 }
5126
Seth Cantrellb4802962015-03-04 03:12:10 +00005127 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
5128
5129 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00005130 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00005131 }
Jordan Rose98709982012-06-04 22:48:57 +00005132
Jordan Rose22b74712012-09-05 22:56:19 +00005133 // Look through argument promotions for our error message's reported type.
5134 // This includes the integral and floating promotions, but excludes array
5135 // and function pointer decay; seeing that an argument intended to be a
5136 // string has type 'char [6]' is probably more confusing than 'char *'.
5137 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5138 if (ICE->getCastKind() == CK_IntegralCast ||
5139 ICE->getCastKind() == CK_FloatingCast) {
5140 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00005141 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00005142
5143 // Check if we didn't match because of an implicit cast from a 'char'
5144 // or 'short' to an 'int'. This is done because printf is a varargs
5145 // function.
5146 if (ICE->getType() == S.Context.IntTy ||
5147 ICE->getType() == S.Context.UnsignedIntTy) {
5148 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00005149 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00005150 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00005151 }
Jordan Rose98709982012-06-04 22:48:57 +00005152 }
Jordan Rose598ec092012-12-05 18:44:40 +00005153 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
5154 // Special case for 'a', which has type 'int' in C.
5155 // Note, however, that we do /not/ want to treat multibyte constants like
5156 // 'MooV' as characters! This form is deprecated but still exists.
5157 if (ExprTy == S.Context.IntTy)
5158 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
5159 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00005160 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005161
Jordan Rosebc53ed12014-05-31 04:12:14 +00005162 // Look through enums to their underlying type.
5163 bool IsEnum = false;
5164 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
5165 ExprTy = EnumTy->getDecl()->getIntegerType();
5166 IsEnum = true;
5167 }
5168
Jordan Rose0e5badd2012-12-05 18:44:49 +00005169 // %C in an Objective-C context prints a unichar, not a wchar_t.
5170 // If the argument is an integer of some kind, believe the %C and suggest
5171 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00005172 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00005173 if (ObjCContext &&
5174 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
5175 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
5176 !ExprTy->isCharType()) {
5177 // 'unichar' is defined as a typedef of unsigned short, but we should
5178 // prefer using the typedef if it is visible.
5179 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00005180
5181 // While we are here, check if the value is an IntegerLiteral that happens
5182 // to be within the valid range.
5183 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
5184 const llvm::APInt &V = IL->getValue();
5185 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
5186 return true;
5187 }
5188
Jordan Rose0e5badd2012-12-05 18:44:49 +00005189 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
5190 Sema::LookupOrdinaryName);
5191 if (S.LookupName(Result, S.getCurScope())) {
5192 NamedDecl *ND = Result.getFoundDecl();
5193 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
5194 if (TD->getUnderlyingType() == IntendedTy)
5195 IntendedTy = S.Context.getTypedefType(TD);
5196 }
5197 }
5198 }
5199
5200 // Special-case some of Darwin's platform-independence types by suggesting
5201 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005202 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00005203 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005204 QualType CastTy;
5205 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
5206 if (!CastTy.isNull()) {
5207 IntendedTy = CastTy;
5208 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00005209 }
5210 }
5211
Jordan Rose22b74712012-09-05 22:56:19 +00005212 // We may be able to offer a FixItHint if it is a supported type.
5213 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00005214 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00005215 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005216
Jordan Rose22b74712012-09-05 22:56:19 +00005217 if (success) {
5218 // Get the fix string from the fixed format specifier
5219 SmallString<16> buf;
5220 llvm::raw_svector_ostream os(buf);
5221 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005222
Jordan Roseaee34382012-09-05 22:56:26 +00005223 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
5224
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005225 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00005226 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5227 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
5228 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5229 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00005230 // In this case, the specifier is wrong and should be changed to match
5231 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00005232 EmitFormatDiagnostic(S.PDiag(diag)
5233 << AT.getRepresentativeTypeName(S.Context)
5234 << IntendedTy << IsEnum << E->getSourceRange(),
5235 E->getLocStart(),
5236 /*IsStringLocation*/ false, SpecRange,
5237 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00005238 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00005239 // The canonical type for formatting this value is different from the
5240 // actual type of the expression. (This occurs, for example, with Darwin's
5241 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
5242 // should be printed as 'long' for 64-bit compatibility.)
5243 // Rather than emitting a normal format/argument mismatch, we want to
5244 // add a cast to the recommended type (and correct the format string
5245 // if necessary).
5246 SmallString<16> CastBuf;
5247 llvm::raw_svector_ostream CastFix(CastBuf);
5248 CastFix << "(";
5249 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
5250 CastFix << ")";
5251
5252 SmallVector<FixItHint,4> Hints;
5253 if (!AT.matchesType(S.Context, IntendedTy))
5254 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
5255
5256 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
5257 // If there's already a cast present, just replace it.
5258 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
5259 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
5260
5261 } else if (!requiresParensToAddCast(E)) {
5262 // If the expression has high enough precedence,
5263 // just write the C-style cast.
5264 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
5265 CastFix.str()));
5266 } else {
5267 // Otherwise, add parens around the expression as well as the cast.
5268 CastFix << "(";
5269 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
5270 CastFix.str()));
5271
Alp Tokerb6cc5922014-05-03 03:45:55 +00005272 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00005273 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
5274 }
5275
Jordan Rose0e5badd2012-12-05 18:44:49 +00005276 if (ShouldNotPrintDirectly) {
5277 // The expression has a type that should not be printed directly.
5278 // We extract the name from the typedef because we don't want to show
5279 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005280 StringRef Name;
5281 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
5282 Name = TypedefTy->getDecl()->getName();
5283 else
5284 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00005285 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00005286 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00005287 << E->getSourceRange(),
5288 E->getLocStart(), /*IsStringLocation=*/false,
5289 SpecRange, Hints);
5290 } else {
5291 // In this case, the expression could be printed using a different
5292 // specifier, but we've decided that the specifier is probably correct
5293 // and we should cast instead. Just use the normal warning message.
5294 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00005295 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5296 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00005297 << E->getSourceRange(),
5298 E->getLocStart(), /*IsStringLocation*/false,
5299 SpecRange, Hints);
5300 }
Jordan Roseaee34382012-09-05 22:56:26 +00005301 }
Jordan Rose22b74712012-09-05 22:56:19 +00005302 } else {
5303 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
5304 SpecifierLen);
5305 // Since the warning for passing non-POD types to variadic functions
5306 // was deferred until now, we emit a warning for non-POD
5307 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00005308 switch (S.isValidVarArgType(ExprTy)) {
5309 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00005310 case Sema::VAK_ValidInCXX11: {
5311 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5312 if (match == analyze_printf::ArgType::NoMatchPedantic) {
5313 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5314 }
Richard Smithd7293d72013-08-05 18:49:43 +00005315
Seth Cantrellb4802962015-03-04 03:12:10 +00005316 EmitFormatDiagnostic(
5317 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
5318 << IsEnum << CSR << E->getSourceRange(),
5319 E->getLocStart(), /*IsStringLocation*/ false, CSR);
5320 break;
5321 }
Richard Smithd7293d72013-08-05 18:49:43 +00005322 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00005323 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00005324 EmitFormatDiagnostic(
5325 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005326 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00005327 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00005328 << CallType
5329 << AT.getRepresentativeTypeName(S.Context)
5330 << CSR
5331 << E->getSourceRange(),
5332 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00005333 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00005334 break;
5335
5336 case Sema::VAK_Invalid:
5337 if (ExprTy->isObjCObjectType())
5338 EmitFormatDiagnostic(
5339 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
5340 << S.getLangOpts().CPlusPlus11
5341 << ExprTy
5342 << CallType
5343 << AT.getRepresentativeTypeName(S.Context)
5344 << CSR
5345 << E->getSourceRange(),
5346 E->getLocStart(), /*IsStringLocation*/false, CSR);
5347 else
5348 // FIXME: If this is an initializer list, suggest removing the braces
5349 // or inserting a cast to the target type.
5350 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
5351 << isa<InitListExpr>(E) << ExprTy << CallType
5352 << AT.getRepresentativeTypeName(S.Context)
5353 << E->getSourceRange();
5354 break;
5355 }
5356
5357 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
5358 "format string specifier index out of range");
5359 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005360 }
5361
Ted Kremenekab278de2010-01-28 23:39:18 +00005362 return true;
5363}
5364
Ted Kremenek02087932010-07-16 02:11:22 +00005365//===--- CHECK: Scanf format string checking ------------------------------===//
5366
5367namespace {
5368class CheckScanfHandler : public CheckFormatHandler {
5369public:
5370 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
5371 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005372 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005373 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005374 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00005375 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005376 llvm::SmallBitVector &CheckedVarArgs,
5377 UncoveredArgHandler &UncoveredArg)
Richard Smithd7293d72013-08-05 18:49:43 +00005378 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
5379 numDataArgs, beg, hasVAListArg,
5380 Args, formatIdx, inFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005381 CheckedVarArgs, UncoveredArg)
Jordan Rose3e0ec582012-07-19 18:10:23 +00005382 {}
Ted Kremenek02087932010-07-16 02:11:22 +00005383
5384 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
5385 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005386 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00005387
5388 bool HandleInvalidScanfConversionSpecifier(
5389 const analyze_scanf::ScanfSpecifier &FS,
5390 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005391 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00005392
Craig Toppere14c0f82014-03-12 04:55:44 +00005393 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00005394};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005395} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00005396
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00005397void CheckScanfHandler::HandleIncompleteScanList(const char *start,
5398 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005399 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
5400 getLocationOfByte(end), /*IsStringLocation*/true,
5401 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00005402}
5403
Ted Kremenekce815422010-07-19 21:25:57 +00005404bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
5405 const analyze_scanf::ScanfSpecifier &FS,
5406 const char *startSpecifier,
5407 unsigned specifierLen) {
5408
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005409 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00005410 FS.getConversionSpecifier();
5411
5412 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5413 getLocationOfByte(CS.getStart()),
5414 startSpecifier, specifierLen,
5415 CS.getStart(), CS.getLength());
5416}
5417
Ted Kremenek02087932010-07-16 02:11:22 +00005418bool CheckScanfHandler::HandleScanfSpecifier(
5419 const analyze_scanf::ScanfSpecifier &FS,
5420 const char *startSpecifier,
5421 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00005422 using namespace analyze_scanf;
5423 using namespace analyze_format_string;
5424
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005425 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00005426
Ted Kremenek6cd69422010-07-19 22:01:06 +00005427 // Handle case where '%' and '*' don't consume an argument. These shouldn't
5428 // be used to decide if we are using positional arguments consistently.
5429 if (FS.consumesDataArgument()) {
5430 if (atFirstArg) {
5431 atFirstArg = false;
5432 usesPositionalArgs = FS.usesPositionalArg();
5433 }
5434 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005435 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5436 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00005437 return false;
5438 }
Ted Kremenek02087932010-07-16 02:11:22 +00005439 }
5440
5441 // Check if the field with is non-zero.
5442 const OptionalAmount &Amt = FS.getFieldWidth();
5443 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
5444 if (Amt.getConstantAmount() == 0) {
5445 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
5446 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00005447 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
5448 getLocationOfByte(Amt.getStart()),
5449 /*IsStringLocation*/true, R,
5450 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00005451 }
5452 }
Seth Cantrellb4802962015-03-04 03:12:10 +00005453
Ted Kremenek02087932010-07-16 02:11:22 +00005454 if (!FS.consumesDataArgument()) {
5455 // FIXME: Technically specifying a precision or field width here
5456 // makes no sense. Worth issuing a warning at some point.
5457 return true;
5458 }
Seth Cantrellb4802962015-03-04 03:12:10 +00005459
Ted Kremenek02087932010-07-16 02:11:22 +00005460 // Consume the argument.
5461 unsigned argIndex = FS.getArgIndex();
5462 if (argIndex < NumDataArgs) {
5463 // The check to see if the argIndex is valid will come later.
5464 // We set the bit here because we may exit early from this
5465 // function if we encounter some other error.
5466 CoveredArgs.set(argIndex);
5467 }
Seth Cantrellb4802962015-03-04 03:12:10 +00005468
Ted Kremenek4407ea42010-07-20 20:04:47 +00005469 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00005470 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00005471 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5472 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00005473 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005474 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00005475 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005476 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5477 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005478
Jordan Rose92303592012-09-08 04:00:03 +00005479 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
5480 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5481
Ted Kremenek02087932010-07-16 02:11:22 +00005482 // The remaining checks depend on the data arguments.
5483 if (HasVAListArg)
5484 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00005485
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005486 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00005487 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00005488
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005489 // Check that the argument type matches the format specifier.
5490 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00005491 if (!Ex)
5492 return true;
5493
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00005494 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00005495
5496 if (!AT.isValid()) {
5497 return true;
5498 }
5499
Seth Cantrellb4802962015-03-04 03:12:10 +00005500 analyze_format_string::ArgType::MatchKind match =
5501 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00005502 if (match == analyze_format_string::ArgType::Match) {
5503 return true;
5504 }
Seth Cantrellb4802962015-03-04 03:12:10 +00005505
Seth Cantrell79340072015-03-04 05:58:08 +00005506 ScanfSpecifier fixedFS = FS;
5507 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
5508 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005509
Seth Cantrell79340072015-03-04 05:58:08 +00005510 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5511 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
5512 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5513 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005514
Seth Cantrell79340072015-03-04 05:58:08 +00005515 if (success) {
5516 // Get the fix string from the fixed format specifier.
5517 SmallString<128> buf;
5518 llvm::raw_svector_ostream os(buf);
5519 fixedFS.toString(os);
5520
5521 EmitFormatDiagnostic(
5522 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
5523 << Ex->getType() << false << Ex->getSourceRange(),
5524 Ex->getLocStart(),
5525 /*IsStringLocation*/ false,
5526 getSpecifierRange(startSpecifier, specifierLen),
5527 FixItHint::CreateReplacement(
5528 getSpecifierRange(startSpecifier, specifierLen), os.str()));
5529 } else {
5530 EmitFormatDiagnostic(S.PDiag(diag)
5531 << AT.getRepresentativeTypeName(S.Context)
5532 << Ex->getType() << false << Ex->getSourceRange(),
5533 Ex->getLocStart(),
5534 /*IsStringLocation*/ false,
5535 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005536 }
5537
Ted Kremenek02087932010-07-16 02:11:22 +00005538 return true;
5539}
5540
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005541static void CheckFormatString(Sema &S, const StringLiteral *FExpr,
5542 const Expr *OrigFormatExpr,
5543 ArrayRef<const Expr *> Args,
5544 bool HasVAListArg, unsigned format_idx,
5545 unsigned firstDataArg,
5546 Sema::FormatStringType Type,
5547 bool inFunctionCall,
5548 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005549 llvm::SmallBitVector &CheckedVarArgs,
5550 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00005551 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00005552 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005553 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005554 S, inFunctionCall, Args[format_idx],
5555 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00005556 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00005557 return;
5558 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005559
Ted Kremenekab278de2010-01-28 23:39:18 +00005560 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005561 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00005562 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005563 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005564 const ConstantArrayType *T =
5565 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005566 assert(T && "String literal not of constant array type!");
5567 size_t TypeSize = T->getSize().getZExtValue();
5568 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005569 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005570
5571 // Emit a warning if the string literal is truncated and does not contain an
5572 // embedded null character.
5573 if (TypeSize <= StrRef.size() &&
5574 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
5575 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005576 S, inFunctionCall, Args[format_idx],
5577 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005578 FExpr->getLocStart(),
5579 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
5580 return;
5581 }
5582
Ted Kremenekab278de2010-01-28 23:39:18 +00005583 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00005584 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005585 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005586 S, inFunctionCall, Args[format_idx],
5587 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00005588 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00005589 return;
5590 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005591
5592 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
5593 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSTrace) {
5594 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, firstDataArg,
5595 numDataArgs, (Type == Sema::FST_NSString ||
5596 Type == Sema::FST_OSTrace),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005597 Str, HasVAListArg, Args, format_idx,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005598 inFunctionCall, CallType, CheckedVarArgs,
5599 UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005600
Hans Wennborg23926bd2011-12-15 10:25:47 +00005601 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005602 S.getLangOpts(),
5603 S.Context.getTargetInfo(),
5604 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00005605 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005606 } else if (Type == Sema::FST_Scanf) {
5607 CheckScanfHandler H(S, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005608 Str, HasVAListArg, Args, format_idx,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005609 inFunctionCall, CallType, CheckedVarArgs,
5610 UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005611
Hans Wennborg23926bd2011-12-15 10:25:47 +00005612 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005613 S.getLangOpts(),
5614 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00005615 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005616 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00005617}
5618
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00005619bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
5620 // Str - The format string. NOTE: this is NOT null-terminated!
5621 StringRef StrRef = FExpr->getString();
5622 const char *Str = StrRef.data();
5623 // Account for cases where the string literal is truncated in a declaration.
5624 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
5625 assert(T && "String literal not of constant array type!");
5626 size_t TypeSize = T->getSize().getZExtValue();
5627 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
5628 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
5629 getLangOpts(),
5630 Context.getTargetInfo());
5631}
5632
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005633//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
5634
5635// Returns the related absolute value function that is larger, of 0 if one
5636// does not exist.
5637static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
5638 switch (AbsFunction) {
5639 default:
5640 return 0;
5641
5642 case Builtin::BI__builtin_abs:
5643 return Builtin::BI__builtin_labs;
5644 case Builtin::BI__builtin_labs:
5645 return Builtin::BI__builtin_llabs;
5646 case Builtin::BI__builtin_llabs:
5647 return 0;
5648
5649 case Builtin::BI__builtin_fabsf:
5650 return Builtin::BI__builtin_fabs;
5651 case Builtin::BI__builtin_fabs:
5652 return Builtin::BI__builtin_fabsl;
5653 case Builtin::BI__builtin_fabsl:
5654 return 0;
5655
5656 case Builtin::BI__builtin_cabsf:
5657 return Builtin::BI__builtin_cabs;
5658 case Builtin::BI__builtin_cabs:
5659 return Builtin::BI__builtin_cabsl;
5660 case Builtin::BI__builtin_cabsl:
5661 return 0;
5662
5663 case Builtin::BIabs:
5664 return Builtin::BIlabs;
5665 case Builtin::BIlabs:
5666 return Builtin::BIllabs;
5667 case Builtin::BIllabs:
5668 return 0;
5669
5670 case Builtin::BIfabsf:
5671 return Builtin::BIfabs;
5672 case Builtin::BIfabs:
5673 return Builtin::BIfabsl;
5674 case Builtin::BIfabsl:
5675 return 0;
5676
5677 case Builtin::BIcabsf:
5678 return Builtin::BIcabs;
5679 case Builtin::BIcabs:
5680 return Builtin::BIcabsl;
5681 case Builtin::BIcabsl:
5682 return 0;
5683 }
5684}
5685
5686// Returns the argument type of the absolute value function.
5687static QualType getAbsoluteValueArgumentType(ASTContext &Context,
5688 unsigned AbsType) {
5689 if (AbsType == 0)
5690 return QualType();
5691
5692 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
5693 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
5694 if (Error != ASTContext::GE_None)
5695 return QualType();
5696
5697 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
5698 if (!FT)
5699 return QualType();
5700
5701 if (FT->getNumParams() != 1)
5702 return QualType();
5703
5704 return FT->getParamType(0);
5705}
5706
5707// Returns the best absolute value function, or zero, based on type and
5708// current absolute value function.
5709static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
5710 unsigned AbsFunctionKind) {
5711 unsigned BestKind = 0;
5712 uint64_t ArgSize = Context.getTypeSize(ArgType);
5713 for (unsigned Kind = AbsFunctionKind; Kind != 0;
5714 Kind = getLargerAbsoluteValueFunction(Kind)) {
5715 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
5716 if (Context.getTypeSize(ParamType) >= ArgSize) {
5717 if (BestKind == 0)
5718 BestKind = Kind;
5719 else if (Context.hasSameType(ParamType, ArgType)) {
5720 BestKind = Kind;
5721 break;
5722 }
5723 }
5724 }
5725 return BestKind;
5726}
5727
5728enum AbsoluteValueKind {
5729 AVK_Integer,
5730 AVK_Floating,
5731 AVK_Complex
5732};
5733
5734static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
5735 if (T->isIntegralOrEnumerationType())
5736 return AVK_Integer;
5737 if (T->isRealFloatingType())
5738 return AVK_Floating;
5739 if (T->isAnyComplexType())
5740 return AVK_Complex;
5741
5742 llvm_unreachable("Type not integer, floating, or complex");
5743}
5744
5745// Changes the absolute value function to a different type. Preserves whether
5746// the function is a builtin.
5747static unsigned changeAbsFunction(unsigned AbsKind,
5748 AbsoluteValueKind ValueKind) {
5749 switch (ValueKind) {
5750 case AVK_Integer:
5751 switch (AbsKind) {
5752 default:
5753 return 0;
5754 case Builtin::BI__builtin_fabsf:
5755 case Builtin::BI__builtin_fabs:
5756 case Builtin::BI__builtin_fabsl:
5757 case Builtin::BI__builtin_cabsf:
5758 case Builtin::BI__builtin_cabs:
5759 case Builtin::BI__builtin_cabsl:
5760 return Builtin::BI__builtin_abs;
5761 case Builtin::BIfabsf:
5762 case Builtin::BIfabs:
5763 case Builtin::BIfabsl:
5764 case Builtin::BIcabsf:
5765 case Builtin::BIcabs:
5766 case Builtin::BIcabsl:
5767 return Builtin::BIabs;
5768 }
5769 case AVK_Floating:
5770 switch (AbsKind) {
5771 default:
5772 return 0;
5773 case Builtin::BI__builtin_abs:
5774 case Builtin::BI__builtin_labs:
5775 case Builtin::BI__builtin_llabs:
5776 case Builtin::BI__builtin_cabsf:
5777 case Builtin::BI__builtin_cabs:
5778 case Builtin::BI__builtin_cabsl:
5779 return Builtin::BI__builtin_fabsf;
5780 case Builtin::BIabs:
5781 case Builtin::BIlabs:
5782 case Builtin::BIllabs:
5783 case Builtin::BIcabsf:
5784 case Builtin::BIcabs:
5785 case Builtin::BIcabsl:
5786 return Builtin::BIfabsf;
5787 }
5788 case AVK_Complex:
5789 switch (AbsKind) {
5790 default:
5791 return 0;
5792 case Builtin::BI__builtin_abs:
5793 case Builtin::BI__builtin_labs:
5794 case Builtin::BI__builtin_llabs:
5795 case Builtin::BI__builtin_fabsf:
5796 case Builtin::BI__builtin_fabs:
5797 case Builtin::BI__builtin_fabsl:
5798 return Builtin::BI__builtin_cabsf;
5799 case Builtin::BIabs:
5800 case Builtin::BIlabs:
5801 case Builtin::BIllabs:
5802 case Builtin::BIfabsf:
5803 case Builtin::BIfabs:
5804 case Builtin::BIfabsl:
5805 return Builtin::BIcabsf;
5806 }
5807 }
5808 llvm_unreachable("Unable to convert function");
5809}
5810
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00005811static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005812 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
5813 if (!FnInfo)
5814 return 0;
5815
5816 switch (FDecl->getBuiltinID()) {
5817 default:
5818 return 0;
5819 case Builtin::BI__builtin_abs:
5820 case Builtin::BI__builtin_fabs:
5821 case Builtin::BI__builtin_fabsf:
5822 case Builtin::BI__builtin_fabsl:
5823 case Builtin::BI__builtin_labs:
5824 case Builtin::BI__builtin_llabs:
5825 case Builtin::BI__builtin_cabs:
5826 case Builtin::BI__builtin_cabsf:
5827 case Builtin::BI__builtin_cabsl:
5828 case Builtin::BIabs:
5829 case Builtin::BIlabs:
5830 case Builtin::BIllabs:
5831 case Builtin::BIfabs:
5832 case Builtin::BIfabsf:
5833 case Builtin::BIfabsl:
5834 case Builtin::BIcabs:
5835 case Builtin::BIcabsf:
5836 case Builtin::BIcabsl:
5837 return FDecl->getBuiltinID();
5838 }
5839 llvm_unreachable("Unknown Builtin type");
5840}
5841
5842// If the replacement is valid, emit a note with replacement function.
5843// Additionally, suggest including the proper header if not already included.
5844static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00005845 unsigned AbsKind, QualType ArgType) {
5846 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00005847 const char *HeaderName = nullptr;
5848 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00005849 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
5850 FunctionName = "std::abs";
5851 if (ArgType->isIntegralOrEnumerationType()) {
5852 HeaderName = "cstdlib";
5853 } else if (ArgType->isRealFloatingType()) {
5854 HeaderName = "cmath";
5855 } else {
5856 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005857 }
Richard Trieubeffb832014-04-15 23:47:53 +00005858
5859 // Lookup all std::abs
5860 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00005861 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00005862 R.suppressDiagnostics();
5863 S.LookupQualifiedName(R, Std);
5864
5865 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005866 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00005867 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
5868 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
5869 } else {
5870 FDecl = dyn_cast<FunctionDecl>(I);
5871 }
5872 if (!FDecl)
5873 continue;
5874
5875 // Found std::abs(), check that they are the right ones.
5876 if (FDecl->getNumParams() != 1)
5877 continue;
5878
5879 // Check that the parameter type can handle the argument.
5880 QualType ParamType = FDecl->getParamDecl(0)->getType();
5881 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
5882 S.Context.getTypeSize(ArgType) <=
5883 S.Context.getTypeSize(ParamType)) {
5884 // Found a function, don't need the header hint.
5885 EmitHeaderHint = false;
5886 break;
5887 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005888 }
Richard Trieubeffb832014-04-15 23:47:53 +00005889 }
5890 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00005891 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00005892 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
5893
5894 if (HeaderName) {
5895 DeclarationName DN(&S.Context.Idents.get(FunctionName));
5896 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
5897 R.suppressDiagnostics();
5898 S.LookupName(R, S.getCurScope());
5899
5900 if (R.isSingleResult()) {
5901 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
5902 if (FD && FD->getBuiltinID() == AbsKind) {
5903 EmitHeaderHint = false;
5904 } else {
5905 return;
5906 }
5907 } else if (!R.empty()) {
5908 return;
5909 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005910 }
5911 }
5912
5913 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00005914 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005915
Richard Trieubeffb832014-04-15 23:47:53 +00005916 if (!HeaderName)
5917 return;
5918
5919 if (!EmitHeaderHint)
5920 return;
5921
Alp Toker5d96e0a2014-07-11 20:53:51 +00005922 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
5923 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00005924}
5925
5926static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
5927 if (!FDecl)
5928 return false;
5929
5930 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
5931 return false;
5932
5933 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
5934
5935 while (ND && ND->isInlineNamespace()) {
5936 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005937 }
Richard Trieubeffb832014-04-15 23:47:53 +00005938
5939 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
5940 return false;
5941
5942 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
5943 return false;
5944
5945 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005946}
5947
5948// Warn when using the wrong abs() function.
5949void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
5950 const FunctionDecl *FDecl,
5951 IdentifierInfo *FnInfo) {
5952 if (Call->getNumArgs() != 1)
5953 return;
5954
5955 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00005956 bool IsStdAbs = IsFunctionStdAbs(FDecl);
5957 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005958 return;
5959
5960 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
5961 QualType ParamType = Call->getArg(0)->getType();
5962
Alp Toker5d96e0a2014-07-11 20:53:51 +00005963 // Unsigned types cannot be negative. Suggest removing the absolute value
5964 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005965 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00005966 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00005967 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005968 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
5969 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00005970 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005971 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
5972 return;
5973 }
5974
David Majnemer7f77eb92015-11-15 03:04:34 +00005975 // Taking the absolute value of a pointer is very suspicious, they probably
5976 // wanted to index into an array, dereference a pointer, call a function, etc.
5977 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
5978 unsigned DiagType = 0;
5979 if (ArgType->isFunctionType())
5980 DiagType = 1;
5981 else if (ArgType->isArrayType())
5982 DiagType = 2;
5983
5984 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
5985 return;
5986 }
5987
Richard Trieubeffb832014-04-15 23:47:53 +00005988 // std::abs has overloads which prevent most of the absolute value problems
5989 // from occurring.
5990 if (IsStdAbs)
5991 return;
5992
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005993 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
5994 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
5995
5996 // The argument and parameter are the same kind. Check if they are the right
5997 // size.
5998 if (ArgValueKind == ParamValueKind) {
5999 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
6000 return;
6001
6002 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
6003 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
6004 << FDecl << ArgType << ParamType;
6005
6006 if (NewAbsKind == 0)
6007 return;
6008
6009 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00006010 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006011 return;
6012 }
6013
6014 // ArgValueKind != ParamValueKind
6015 // The wrong type of absolute value function was used. Attempt to find the
6016 // proper one.
6017 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
6018 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
6019 if (NewAbsKind == 0)
6020 return;
6021
6022 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
6023 << FDecl << ParamValueKind << ArgValueKind;
6024
6025 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00006026 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006027}
6028
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006029//===--- CHECK: Standard memory functions ---------------------------------===//
6030
Nico Weber0e6daef2013-12-26 23:38:39 +00006031/// \brief Takes the expression passed to the size_t parameter of functions
6032/// such as memcmp, strncat, etc and warns if it's a comparison.
6033///
6034/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
6035static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
6036 IdentifierInfo *FnName,
6037 SourceLocation FnLoc,
6038 SourceLocation RParenLoc) {
6039 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
6040 if (!Size)
6041 return false;
6042
6043 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
6044 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
6045 return false;
6046
Nico Weber0e6daef2013-12-26 23:38:39 +00006047 SourceRange SizeRange = Size->getSourceRange();
6048 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
6049 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00006050 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00006051 << FnName << FixItHint::CreateInsertion(
6052 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00006053 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00006054 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00006055 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00006056 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
6057 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00006058
6059 return true;
6060}
6061
Reid Kleckner5fb5b122014-06-27 23:58:21 +00006062/// \brief Determine whether the given type is or contains a dynamic class type
6063/// (e.g., whether it has a vtable).
6064static const CXXRecordDecl *getContainedDynamicClass(QualType T,
6065 bool &IsContained) {
6066 // Look through array types while ignoring qualifiers.
6067 const Type *Ty = T->getBaseElementTypeUnsafe();
6068 IsContained = false;
6069
6070 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
6071 RD = RD ? RD->getDefinition() : nullptr;
Richard Trieu1c7237a2016-03-31 04:18:07 +00006072 if (!RD || RD->isInvalidDecl())
Reid Kleckner5fb5b122014-06-27 23:58:21 +00006073 return nullptr;
6074
6075 if (RD->isDynamicClass())
6076 return RD;
6077
6078 // Check all the fields. If any bases were dynamic, the class is dynamic.
6079 // It's impossible for a class to transitively contain itself by value, so
6080 // infinite recursion is impossible.
6081 for (auto *FD : RD->fields()) {
6082 bool SubContained;
6083 if (const CXXRecordDecl *ContainedRD =
6084 getContainedDynamicClass(FD->getType(), SubContained)) {
6085 IsContained = true;
6086 return ContainedRD;
6087 }
6088 }
6089
6090 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00006091}
6092
Chandler Carruth889ed862011-06-21 23:04:20 +00006093/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006094/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00006095static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00006096 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006097 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6098 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
6099 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00006100
Craig Topperc3ec1492014-05-26 06:22:03 +00006101 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006102}
6103
Chandler Carruth889ed862011-06-21 23:04:20 +00006104/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00006105static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006106 if (const UnaryExprOrTypeTraitExpr *SizeOf =
6107 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6108 if (SizeOf->getKind() == clang::UETT_SizeOf)
6109 return SizeOf->getTypeOfArgument();
6110
6111 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00006112}
6113
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006114/// \brief Check for dangerous or invalid arguments to memset().
6115///
Chandler Carruthac687262011-06-03 06:23:57 +00006116/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00006117/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
6118/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006119///
6120/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00006121void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00006122 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00006123 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00006124 assert(BId != 0);
6125
Ted Kremenekb5fabb22011-04-28 01:38:02 +00006126 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00006127 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00006128 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00006129 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00006130 return;
6131
Anna Zaks22122702012-01-17 00:37:07 +00006132 unsigned LastArg = (BId == Builtin::BImemset ||
6133 BId == Builtin::BIstrndup ? 1 : 2);
6134 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00006135 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006136
Nico Weber0e6daef2013-12-26 23:38:39 +00006137 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
6138 Call->getLocStart(), Call->getRParenLoc()))
6139 return;
6140
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006141 // We have special checking when the length is a sizeof expression.
6142 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
6143 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
6144 llvm::FoldingSetNodeID SizeOfArgID;
6145
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006146 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
6147 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00006148 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006149
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006150 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00006151 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006152 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00006153 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00006154
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006155 // Never warn about void type pointers. This can be used to suppress
6156 // false positives.
6157 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006158 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006159
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006160 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
6161 // actually comparing the expressions for equality. Because computing the
6162 // expression IDs can be expensive, we only do this if the diagnostic is
6163 // enabled.
6164 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006165 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
6166 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006167 // We only compute IDs for expressions if the warning is enabled, and
6168 // cache the sizeof arg's ID.
6169 if (SizeOfArgID == llvm::FoldingSetNodeID())
6170 SizeOfArg->Profile(SizeOfArgID, Context, true);
6171 llvm::FoldingSetNodeID DestID;
6172 Dest->Profile(DestID, Context, true);
6173 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00006174 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
6175 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006176 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00006177 StringRef ReadableName = FnName->getName();
6178
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006179 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00006180 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006181 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00006182 if (!PointeeTy->isIncompleteType() &&
6183 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006184 ActionIdx = 2; // If the pointee's size is sizeof(char),
6185 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00006186
6187 // If the function is defined as a builtin macro, do not show macro
6188 // expansion.
6189 SourceLocation SL = SizeOfArg->getExprLoc();
6190 SourceRange DSR = Dest->getSourceRange();
6191 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00006192 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00006193
6194 if (SM.isMacroArgExpansion(SL)) {
6195 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
6196 SL = SM.getSpellingLoc(SL);
6197 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
6198 SM.getSpellingLoc(DSR.getEnd()));
6199 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
6200 SM.getSpellingLoc(SSR.getEnd()));
6201 }
6202
Anna Zaksd08d9152012-05-30 23:14:52 +00006203 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006204 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00006205 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00006206 << PointeeTy
6207 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00006208 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00006209 << SSR);
6210 DiagRuntimeBehavior(SL, SizeOfArg,
6211 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
6212 << ActionIdx
6213 << SSR);
6214
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006215 break;
6216 }
6217 }
6218
6219 // Also check for cases where the sizeof argument is the exact same
6220 // type as the memory argument, and where it points to a user-defined
6221 // record type.
6222 if (SizeOfArgTy != QualType()) {
6223 if (PointeeTy->isRecordType() &&
6224 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
6225 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
6226 PDiag(diag::warn_sizeof_pointer_type_memaccess)
6227 << FnName << SizeOfArgTy << ArgIdx
6228 << PointeeTy << Dest->getSourceRange()
6229 << LenExpr->getSourceRange());
6230 break;
6231 }
Nico Weberc5e73862011-06-14 16:14:58 +00006232 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00006233 } else if (DestTy->isArrayType()) {
6234 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00006235 }
Nico Weberc5e73862011-06-14 16:14:58 +00006236
Nico Weberc44b35e2015-03-21 17:37:46 +00006237 if (PointeeTy == QualType())
6238 continue;
Anna Zaks22122702012-01-17 00:37:07 +00006239
Nico Weberc44b35e2015-03-21 17:37:46 +00006240 // Always complain about dynamic classes.
6241 bool IsContained;
6242 if (const CXXRecordDecl *ContainedRD =
6243 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00006244
Nico Weberc44b35e2015-03-21 17:37:46 +00006245 unsigned OperationType = 0;
6246 // "overwritten" if we're warning about the destination for any call
6247 // but memcmp; otherwise a verb appropriate to the call.
6248 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
6249 if (BId == Builtin::BImemcpy)
6250 OperationType = 1;
6251 else if(BId == Builtin::BImemmove)
6252 OperationType = 2;
6253 else if (BId == Builtin::BImemcmp)
6254 OperationType = 3;
6255 }
6256
John McCall31168b02011-06-15 23:02:42 +00006257 DiagRuntimeBehavior(
6258 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00006259 PDiag(diag::warn_dyn_class_memaccess)
6260 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
6261 << FnName << IsContained << ContainedRD << OperationType
6262 << Call->getCallee()->getSourceRange());
6263 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
6264 BId != Builtin::BImemset)
6265 DiagRuntimeBehavior(
6266 Dest->getExprLoc(), Dest,
6267 PDiag(diag::warn_arc_object_memaccess)
6268 << ArgIdx << FnName << PointeeTy
6269 << Call->getCallee()->getSourceRange());
6270 else
6271 continue;
6272
6273 DiagRuntimeBehavior(
6274 Dest->getExprLoc(), Dest,
6275 PDiag(diag::note_bad_memaccess_silence)
6276 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
6277 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006278 }
6279}
6280
Ted Kremenek6865f772011-08-18 20:55:45 +00006281// A little helper routine: ignore addition and subtraction of integer literals.
6282// This intentionally does not ignore all integer constant expressions because
6283// we don't want to remove sizeof().
6284static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
6285 Ex = Ex->IgnoreParenCasts();
6286
6287 for (;;) {
6288 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
6289 if (!BO || !BO->isAdditiveOp())
6290 break;
6291
6292 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
6293 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
6294
6295 if (isa<IntegerLiteral>(RHS))
6296 Ex = LHS;
6297 else if (isa<IntegerLiteral>(LHS))
6298 Ex = RHS;
6299 else
6300 break;
6301 }
6302
6303 return Ex;
6304}
6305
Anna Zaks13b08572012-08-08 21:42:23 +00006306static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
6307 ASTContext &Context) {
6308 // Only handle constant-sized or VLAs, but not flexible members.
6309 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
6310 // Only issue the FIXIT for arrays of size > 1.
6311 if (CAT->getSize().getSExtValue() <= 1)
6312 return false;
6313 } else if (!Ty->isVariableArrayType()) {
6314 return false;
6315 }
6316 return true;
6317}
6318
Ted Kremenek6865f772011-08-18 20:55:45 +00006319// Warn if the user has made the 'size' argument to strlcpy or strlcat
6320// be the size of the source, instead of the destination.
6321void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
6322 IdentifierInfo *FnName) {
6323
6324 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00006325 unsigned NumArgs = Call->getNumArgs();
6326 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00006327 return;
6328
6329 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
6330 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00006331 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00006332
6333 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
6334 Call->getLocStart(), Call->getRParenLoc()))
6335 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00006336
6337 // Look for 'strlcpy(dst, x, sizeof(x))'
6338 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
6339 CompareWithSrc = Ex;
6340 else {
6341 // Look for 'strlcpy(dst, x, strlen(x))'
6342 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00006343 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
6344 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00006345 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
6346 }
6347 }
6348
6349 if (!CompareWithSrc)
6350 return;
6351
6352 // Determine if the argument to sizeof/strlen is equal to the source
6353 // argument. In principle there's all kinds of things you could do
6354 // here, for instance creating an == expression and evaluating it with
6355 // EvaluateAsBooleanCondition, but this uses a more direct technique:
6356 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
6357 if (!SrcArgDRE)
6358 return;
6359
6360 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
6361 if (!CompareWithSrcDRE ||
6362 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
6363 return;
6364
6365 const Expr *OriginalSizeArg = Call->getArg(2);
6366 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
6367 << OriginalSizeArg->getSourceRange() << FnName;
6368
6369 // Output a FIXIT hint if the destination is an array (rather than a
6370 // pointer to an array). This could be enhanced to handle some
6371 // pointers if we know the actual size, like if DstArg is 'array+2'
6372 // we could say 'sizeof(array)-2'.
6373 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00006374 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00006375 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00006376
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00006377 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00006378 llvm::raw_svector_ostream OS(sizeString);
6379 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00006380 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00006381 OS << ")";
6382
6383 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
6384 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
6385 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00006386}
6387
Anna Zaks314cd092012-02-01 19:08:57 +00006388/// Check if two expressions refer to the same declaration.
6389static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
6390 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
6391 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
6392 return D1->getDecl() == D2->getDecl();
6393 return false;
6394}
6395
6396static const Expr *getStrlenExprArg(const Expr *E) {
6397 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6398 const FunctionDecl *FD = CE->getDirectCallee();
6399 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00006400 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00006401 return CE->getArg(0)->IgnoreParenCasts();
6402 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006403 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00006404}
6405
6406// Warn on anti-patterns as the 'size' argument to strncat.
6407// The correct size argument should look like following:
6408// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
6409void Sema::CheckStrncatArguments(const CallExpr *CE,
6410 IdentifierInfo *FnName) {
6411 // Don't crash if the user has the wrong number of arguments.
6412 if (CE->getNumArgs() < 3)
6413 return;
6414 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
6415 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
6416 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
6417
Nico Weber0e6daef2013-12-26 23:38:39 +00006418 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
6419 CE->getRParenLoc()))
6420 return;
6421
Anna Zaks314cd092012-02-01 19:08:57 +00006422 // Identify common expressions, which are wrongly used as the size argument
6423 // to strncat and may lead to buffer overflows.
6424 unsigned PatternType = 0;
6425 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
6426 // - sizeof(dst)
6427 if (referToTheSameDecl(SizeOfArg, DstArg))
6428 PatternType = 1;
6429 // - sizeof(src)
6430 else if (referToTheSameDecl(SizeOfArg, SrcArg))
6431 PatternType = 2;
6432 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
6433 if (BE->getOpcode() == BO_Sub) {
6434 const Expr *L = BE->getLHS()->IgnoreParenCasts();
6435 const Expr *R = BE->getRHS()->IgnoreParenCasts();
6436 // - sizeof(dst) - strlen(dst)
6437 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
6438 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
6439 PatternType = 1;
6440 // - sizeof(src) - (anything)
6441 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
6442 PatternType = 2;
6443 }
6444 }
6445
6446 if (PatternType == 0)
6447 return;
6448
Anna Zaks5069aa32012-02-03 01:27:37 +00006449 // Generate the diagnostic.
6450 SourceLocation SL = LenArg->getLocStart();
6451 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00006452 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00006453
6454 // If the function is defined as a builtin macro, do not show macro expansion.
6455 if (SM.isMacroArgExpansion(SL)) {
6456 SL = SM.getSpellingLoc(SL);
6457 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
6458 SM.getSpellingLoc(SR.getEnd()));
6459 }
6460
Anna Zaks13b08572012-08-08 21:42:23 +00006461 // Check if the destination is an array (rather than a pointer to an array).
6462 QualType DstTy = DstArg->getType();
6463 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
6464 Context);
6465 if (!isKnownSizeArray) {
6466 if (PatternType == 1)
6467 Diag(SL, diag::warn_strncat_wrong_size) << SR;
6468 else
6469 Diag(SL, diag::warn_strncat_src_size) << SR;
6470 return;
6471 }
6472
Anna Zaks314cd092012-02-01 19:08:57 +00006473 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00006474 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00006475 else
Anna Zaks5069aa32012-02-03 01:27:37 +00006476 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00006477
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00006478 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00006479 llvm::raw_svector_ostream OS(sizeString);
6480 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00006481 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00006482 OS << ") - ";
6483 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00006484 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00006485 OS << ") - 1";
6486
Anna Zaks5069aa32012-02-03 01:27:37 +00006487 Diag(SL, diag::note_strncat_wrong_size)
6488 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00006489}
6490
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006491//===--- CHECK: Return Address of Stack Variable --------------------------===//
6492
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006493static const Expr *EvalVal(const Expr *E,
6494 SmallVectorImpl<const DeclRefExpr *> &refVars,
6495 const Decl *ParentDecl);
6496static const Expr *EvalAddr(const Expr *E,
6497 SmallVectorImpl<const DeclRefExpr *> &refVars,
6498 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006499
6500/// CheckReturnStackAddr - Check if a return statement returns the address
6501/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006502static void
6503CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
6504 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00006505
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006506 const Expr *stackE = nullptr;
6507 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006508
6509 // Perform checking for returned stack addresses, local blocks,
6510 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00006511 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006512 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006513 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00006514 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006515 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006516 }
6517
Craig Topperc3ec1492014-05-26 06:22:03 +00006518 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006519 return; // Nothing suspicious was found.
6520
6521 SourceLocation diagLoc;
6522 SourceRange diagRange;
6523 if (refVars.empty()) {
6524 diagLoc = stackE->getLocStart();
6525 diagRange = stackE->getSourceRange();
6526 } else {
6527 // We followed through a reference variable. 'stackE' contains the
6528 // problematic expression but we will warn at the return statement pointing
6529 // at the reference variable. We will later display the "trail" of
6530 // reference variables using notes.
6531 diagLoc = refVars[0]->getLocStart();
6532 diagRange = refVars[0]->getSourceRange();
6533 }
6534
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006535 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
6536 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00006537 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006538 << DR->getDecl()->getDeclName() << diagRange;
6539 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006540 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006541 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006542 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006543 } else { // local temporary.
Craig Topperda7b27f2015-11-17 05:40:09 +00006544 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
6545 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006546 }
6547
6548 // Display the "trail" of reference variables that we followed until we
6549 // found the problematic expression using notes.
6550 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006551 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006552 // If this var binds to another reference var, show the range of the next
6553 // var, otherwise the var binds to the problematic expression, in which case
6554 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006555 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
6556 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006557 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
6558 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006559 }
6560}
6561
6562/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
6563/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006564/// to a location on the stack, a local block, an address of a label, or a
6565/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006566/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006567/// encounter a subexpression that (1) clearly does not lead to one of the
6568/// above problematic expressions (2) is something we cannot determine leads to
6569/// a problematic expression based on such local checking.
6570///
6571/// Both EvalAddr and EvalVal follow through reference variables to evaluate
6572/// the expression that they point to. Such variables are added to the
6573/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006574///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00006575/// EvalAddr processes expressions that are pointers that are used as
6576/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006577/// At the base case of the recursion is a check for the above problematic
6578/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006579///
6580/// This implementation handles:
6581///
6582/// * pointer-to-pointer casts
6583/// * implicit conversions from array references to pointers
6584/// * taking the address of fields
6585/// * arbitrary interplay between "&" and "*" operators
6586/// * pointer arithmetic from an address of a stack variable
6587/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006588static const Expr *EvalAddr(const Expr *E,
6589 SmallVectorImpl<const DeclRefExpr *> &refVars,
6590 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006591 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00006592 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006593
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006594 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00006595 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00006596 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006597 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00006598 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00006599
Peter Collingbourne91147592011-04-15 00:35:48 +00006600 E = E->IgnoreParens();
6601
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006602 // Our "symbolic interpreter" is just a dispatch off the currently
6603 // viewed AST node. We then recursively traverse the AST by calling
6604 // EvalAddr and EvalVal appropriately.
6605 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006606 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006607 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006608
Richard Smith40f08eb2014-01-30 22:05:38 +00006609 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00006610 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00006611 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00006612
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006613 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006614 // If this is a reference variable, follow through to the expression that
6615 // it points to.
6616 if (V->hasLocalStorage() &&
6617 V->getType()->isReferenceType() && V->hasInit()) {
6618 // Add the reference variable to the "trail".
6619 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006620 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006621 }
6622
Craig Topperc3ec1492014-05-26 06:22:03 +00006623 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006624 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006625
Chris Lattner934edb22007-12-28 05:31:15 +00006626 case Stmt::UnaryOperatorClass: {
6627 // The only unary operator that make sense to handle here
6628 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006629 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006630
John McCalle3027922010-08-25 11:45:40 +00006631 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006632 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006633 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006634 }
Mike Stump11289f42009-09-09 15:08:12 +00006635
Chris Lattner934edb22007-12-28 05:31:15 +00006636 case Stmt::BinaryOperatorClass: {
6637 // Handle pointer arithmetic. All other binary operators are not valid
6638 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006639 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00006640 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00006641
John McCalle3027922010-08-25 11:45:40 +00006642 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00006643 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006644
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006645 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00006646
6647 // Determine which argument is the real pointer base. It could be
6648 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006649 if (!Base->getType()->isPointerType())
6650 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00006651
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006652 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006653 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00006654 }
Steve Naroff2752a172008-09-10 19:17:48 +00006655
Chris Lattner934edb22007-12-28 05:31:15 +00006656 // For conditional operators we need to see if either the LHS or RHS are
6657 // valid DeclRefExpr*s. If one of them is valid, we return it.
6658 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006659 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006660
Chris Lattner934edb22007-12-28 05:31:15 +00006661 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006662 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006663 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006664 // In C++, we can have a throw-expression, which has 'void' type.
6665 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006666 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006667 return LHS;
6668 }
Chris Lattner934edb22007-12-28 05:31:15 +00006669
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006670 // In C++, we can have a throw-expression, which has 'void' type.
6671 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00006672 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006673
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006674 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00006675 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006676
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006677 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00006678 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006679 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00006680 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006681
6682 case Stmt::AddrLabelExprClass:
6683 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00006684
John McCall28fc7092011-11-10 05:35:25 +00006685 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006686 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
6687 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00006688
Ted Kremenekc3b4c522008-08-07 00:49:01 +00006689 // For casts, we need to handle conversions from arrays to
6690 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00006691 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00006692 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00006693 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00006694 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00006695 case Stmt::CXXStaticCastExprClass:
6696 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00006697 case Stmt::CXXConstCastExprClass:
6698 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006699 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00006700 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00006701 case CK_LValueToRValue:
6702 case CK_NoOp:
6703 case CK_BaseToDerived:
6704 case CK_DerivedToBase:
6705 case CK_UncheckedDerivedToBase:
6706 case CK_Dynamic:
6707 case CK_CPointerToObjCPointerCast:
6708 case CK_BlockPointerToObjCPointerCast:
6709 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006710 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00006711
6712 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006713 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00006714
Richard Trieudadefde2014-07-02 04:39:38 +00006715 case CK_BitCast:
6716 if (SubExpr->getType()->isAnyPointerType() ||
6717 SubExpr->getType()->isBlockPointerType() ||
6718 SubExpr->getType()->isObjCQualifiedIdType())
6719 return EvalAddr(SubExpr, refVars, ParentDecl);
6720 else
6721 return nullptr;
6722
Eli Friedman8195ad72012-02-23 23:04:32 +00006723 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00006724 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00006725 }
Chris Lattner934edb22007-12-28 05:31:15 +00006726 }
Mike Stump11289f42009-09-09 15:08:12 +00006727
Douglas Gregorfe314812011-06-21 17:03:29 +00006728 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006729 if (const Expr *Result =
6730 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
6731 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00006732 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00006733 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006734
Chris Lattner934edb22007-12-28 05:31:15 +00006735 // Everything else: we simply don't reason about them.
6736 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00006737 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00006738 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006739}
Mike Stump11289f42009-09-09 15:08:12 +00006740
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006741/// EvalVal - This function is complements EvalAddr in the mutual recursion.
6742/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006743static const Expr *EvalVal(const Expr *E,
6744 SmallVectorImpl<const DeclRefExpr *> &refVars,
6745 const Decl *ParentDecl) {
6746 do {
6747 // We should only be called for evaluating non-pointer expressions, or
6748 // expressions with a pointer type that are not used as references but
6749 // instead
6750 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00006751
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006752 // Our "symbolic interpreter" is just a dispatch off the currently
6753 // viewed AST node. We then recursively traverse the AST by calling
6754 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00006755
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006756 E = E->IgnoreParens();
6757 switch (E->getStmtClass()) {
6758 case Stmt::ImplicitCastExprClass: {
6759 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
6760 if (IE->getValueKind() == VK_LValue) {
6761 E = IE->getSubExpr();
6762 continue;
6763 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006764 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006765 }
Richard Smith40f08eb2014-01-30 22:05:38 +00006766
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006767 case Stmt::ExprWithCleanupsClass:
6768 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
6769 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006770
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006771 case Stmt::DeclRefExprClass: {
6772 // When we hit a DeclRefExpr we are looking at code that refers to a
6773 // variable's name. If it's not a reference variable we check if it has
6774 // local storage within the function, and if so, return the expression.
6775 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6776
6777 // If we leave the immediate function, the lifetime isn't about to end.
6778 if (DR->refersToEnclosingVariableOrCapture())
6779 return nullptr;
6780
6781 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
6782 // Check if it refers to itself, e.g. "int& i = i;".
6783 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006784 return DR;
6785
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006786 if (V->hasLocalStorage()) {
6787 if (!V->getType()->isReferenceType())
6788 return DR;
6789
6790 // Reference variable, follow through to the expression that
6791 // it points to.
6792 if (V->hasInit()) {
6793 // Add the reference variable to the "trail".
6794 refVars.push_back(DR);
6795 return EvalVal(V->getInit(), refVars, V);
6796 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006797 }
6798 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006799
6800 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006801 }
Mike Stump11289f42009-09-09 15:08:12 +00006802
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006803 case Stmt::UnaryOperatorClass: {
6804 // The only unary operator that make sense to handle here
6805 // is Deref. All others don't resolve to a "name." This includes
6806 // handling all sorts of rvalues passed to a unary operator.
6807 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006808
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006809 if (U->getOpcode() == UO_Deref)
6810 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00006811
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006812 return nullptr;
6813 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006814
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006815 case Stmt::ArraySubscriptExprClass: {
6816 // Array subscripts are potential references to data on the stack. We
6817 // retrieve the DeclRefExpr* for the array variable if it indeed
6818 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00006819 const auto *ASE = cast<ArraySubscriptExpr>(E);
6820 if (ASE->isTypeDependent())
6821 return nullptr;
6822 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006823 }
Mike Stump11289f42009-09-09 15:08:12 +00006824
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006825 case Stmt::OMPArraySectionExprClass: {
6826 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
6827 ParentDecl);
6828 }
Mike Stump11289f42009-09-09 15:08:12 +00006829
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006830 case Stmt::ConditionalOperatorClass: {
6831 // For conditional operators we need to see if either the LHS or RHS are
6832 // non-NULL Expr's. If one is non-NULL, we return it.
6833 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00006834
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006835 // Handle the GNU extension for missing LHS.
6836 if (const Expr *LHSExpr = C->getLHS()) {
6837 // In C++, we can have a throw-expression, which has 'void' type.
6838 if (!LHSExpr->getType()->isVoidType())
6839 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
6840 return LHS;
6841 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006842
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006843 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006844 if (C->getRHS()->getType()->isVoidType())
6845 return nullptr;
6846
6847 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006848 }
6849
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006850 // Accesses to members are potential references to data on the stack.
6851 case Stmt::MemberExprClass: {
6852 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00006853
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006854 // Check for indirect access. We only want direct field accesses.
6855 if (M->isArrow())
6856 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006857
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006858 // Check whether the member type is itself a reference, in which case
6859 // we're not going to refer to the member, but to what the member refers
6860 // to.
6861 if (M->getMemberDecl()->getType()->isReferenceType())
6862 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006863
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006864 return EvalVal(M->getBase(), refVars, ParentDecl);
6865 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00006866
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006867 case Stmt::MaterializeTemporaryExprClass:
6868 if (const Expr *Result =
6869 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
6870 refVars, ParentDecl))
6871 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006872 return E;
6873
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006874 default:
6875 // Check that we don't return or take the address of a reference to a
6876 // temporary. This is only useful in C++.
6877 if (!E->isTypeDependent() && E->isRValue())
6878 return E;
6879
6880 // Everything else: we simply don't reason about them.
6881 return nullptr;
6882 }
6883 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006884}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006885
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006886void
6887Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
6888 SourceLocation ReturnLoc,
6889 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00006890 const AttrVec *Attrs,
6891 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006892 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
6893
6894 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00006895 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
6896 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00006897 CheckNonNullExpr(*this, RetValExp))
6898 Diag(ReturnLoc, diag::warn_null_ret)
6899 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00006900
6901 // C++11 [basic.stc.dynamic.allocation]p4:
6902 // If an allocation function declared with a non-throwing
6903 // exception-specification fails to allocate storage, it shall return
6904 // a null pointer. Any other allocation function that fails to allocate
6905 // storage shall indicate failure only by throwing an exception [...]
6906 if (FD) {
6907 OverloadedOperatorKind Op = FD->getOverloadedOperator();
6908 if (Op == OO_New || Op == OO_Array_New) {
6909 const FunctionProtoType *Proto
6910 = FD->getType()->castAs<FunctionProtoType>();
6911 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
6912 CheckNonNullExpr(*this, RetValExp))
6913 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
6914 << FD << getLangOpts().CPlusPlus11;
6915 }
6916 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006917}
6918
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006919//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
6920
6921/// Check for comparisons of floating point operands using != and ==.
6922/// Issue a warning if these are no self-comparisons, as they are not likely
6923/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00006924void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00006925 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
6926 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006927
6928 // Special case: check for x == x (which is OK).
6929 // Do not emit warnings for such cases.
6930 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
6931 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
6932 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00006933 return;
Mike Stump11289f42009-09-09 15:08:12 +00006934
Ted Kremenekeda40e22007-11-29 00:59:04 +00006935 // Special case: check for comparisons against literals that can be exactly
6936 // represented by APFloat. In such cases, do not emit a warning. This
6937 // is a heuristic: often comparison against such literals are used to
6938 // detect if a value in a variable has not changed. This clearly can
6939 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00006940 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
6941 if (FLL->isExact())
6942 return;
6943 } else
6944 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
6945 if (FLR->isExact())
6946 return;
Mike Stump11289f42009-09-09 15:08:12 +00006947
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006948 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00006949 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00006950 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00006951 return;
Mike Stump11289f42009-09-09 15:08:12 +00006952
David Blaikie1f4ff152012-07-16 20:47:22 +00006953 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00006954 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00006955 return;
Mike Stump11289f42009-09-09 15:08:12 +00006956
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006957 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00006958 Diag(Loc, diag::warn_floatingpoint_eq)
6959 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006960}
John McCallca01b222010-01-04 23:21:16 +00006961
John McCall70aa5392010-01-06 05:24:50 +00006962//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
6963//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00006964
John McCall70aa5392010-01-06 05:24:50 +00006965namespace {
John McCallca01b222010-01-04 23:21:16 +00006966
John McCall70aa5392010-01-06 05:24:50 +00006967/// Structure recording the 'active' range of an integer-valued
6968/// expression.
6969struct IntRange {
6970 /// The number of bits active in the int.
6971 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00006972
John McCall70aa5392010-01-06 05:24:50 +00006973 /// True if the int is known not to have negative values.
6974 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00006975
John McCall70aa5392010-01-06 05:24:50 +00006976 IntRange(unsigned Width, bool NonNegative)
6977 : Width(Width), NonNegative(NonNegative)
6978 {}
John McCallca01b222010-01-04 23:21:16 +00006979
John McCall817d4af2010-11-10 23:38:19 +00006980 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00006981 static IntRange forBoolType() {
6982 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00006983 }
6984
John McCall817d4af2010-11-10 23:38:19 +00006985 /// Returns the range of an opaque value of the given integral type.
6986 static IntRange forValueOfType(ASTContext &C, QualType T) {
6987 return forValueOfCanonicalType(C,
6988 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00006989 }
6990
John McCall817d4af2010-11-10 23:38:19 +00006991 /// Returns the range of an opaque value of a canonical integral type.
6992 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00006993 assert(T->isCanonicalUnqualified());
6994
6995 if (const VectorType *VT = dyn_cast<VectorType>(T))
6996 T = VT->getElementType().getTypePtr();
6997 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
6998 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00006999 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7000 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00007001
David Majnemer6a426652013-06-07 22:07:20 +00007002 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00007003 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00007004 EnumDecl *Enum = ET->getDecl();
7005 if (!Enum->isCompleteDefinition())
7006 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00007007
David Majnemer6a426652013-06-07 22:07:20 +00007008 unsigned NumPositive = Enum->getNumPositiveBits();
7009 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00007010
David Majnemer6a426652013-06-07 22:07:20 +00007011 if (NumNegative == 0)
7012 return IntRange(NumPositive, true/*NonNegative*/);
7013 else
7014 return IntRange(std::max(NumPositive + 1, NumNegative),
7015 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00007016 }
John McCall70aa5392010-01-06 05:24:50 +00007017
7018 const BuiltinType *BT = cast<BuiltinType>(T);
7019 assert(BT->isInteger());
7020
7021 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7022 }
7023
John McCall817d4af2010-11-10 23:38:19 +00007024 /// Returns the "target" range of a canonical integral type, i.e.
7025 /// the range of values expressible in the type.
7026 ///
7027 /// This matches forValueOfCanonicalType except that enums have the
7028 /// full range of their type, not the range of their enumerators.
7029 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
7030 assert(T->isCanonicalUnqualified());
7031
7032 if (const VectorType *VT = dyn_cast<VectorType>(T))
7033 T = VT->getElementType().getTypePtr();
7034 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7035 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00007036 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7037 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00007038 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00007039 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00007040
7041 const BuiltinType *BT = cast<BuiltinType>(T);
7042 assert(BT->isInteger());
7043
7044 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7045 }
7046
7047 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00007048 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00007049 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00007050 L.NonNegative && R.NonNegative);
7051 }
7052
John McCall817d4af2010-11-10 23:38:19 +00007053 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00007054 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00007055 return IntRange(std::min(L.Width, R.Width),
7056 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00007057 }
7058};
7059
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007060IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00007061 if (value.isSigned() && value.isNegative())
7062 return IntRange(value.getMinSignedBits(), false);
7063
7064 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00007065 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00007066
7067 // isNonNegative() just checks the sign bit without considering
7068 // signedness.
7069 return IntRange(value.getActiveBits(), true);
7070}
7071
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007072IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
7073 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00007074 if (result.isInt())
7075 return GetValueRange(C, result.getInt(), MaxWidth);
7076
7077 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00007078 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
7079 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
7080 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
7081 R = IntRange::join(R, El);
7082 }
John McCall70aa5392010-01-06 05:24:50 +00007083 return R;
7084 }
7085
7086 if (result.isComplexInt()) {
7087 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
7088 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
7089 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00007090 }
7091
7092 // This can happen with lossless casts to intptr_t of "based" lvalues.
7093 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00007094 // FIXME: The only reason we need to pass the type in here is to get
7095 // the sign right on this one case. It would be nice if APValue
7096 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007097 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00007098 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00007099}
John McCall70aa5392010-01-06 05:24:50 +00007100
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007101QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00007102 QualType Ty = E->getType();
7103 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
7104 Ty = AtomicRHS->getValueType();
7105 return Ty;
7106}
7107
John McCall70aa5392010-01-06 05:24:50 +00007108/// Pseudo-evaluate the given integer expression, estimating the
7109/// range of values it might take.
7110///
7111/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007112IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00007113 E = E->IgnoreParens();
7114
7115 // Try a full evaluation first.
7116 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00007117 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00007118 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00007119
7120 // I think we only want to look through implicit casts here; if the
7121 // user has an explicit widening cast, we should treat the value as
7122 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007123 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00007124 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00007125 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
7126
Eli Friedmane6d33952013-07-08 20:20:06 +00007127 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00007128
George Burgess IVdf1ed002016-01-13 01:52:39 +00007129 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
7130 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00007131
John McCall70aa5392010-01-06 05:24:50 +00007132 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00007133 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00007134 return OutputTypeRange;
7135
7136 IntRange SubRange
7137 = GetExprRange(C, CE->getSubExpr(),
7138 std::min(MaxWidth, OutputTypeRange.Width));
7139
7140 // Bail out if the subexpr's range is as wide as the cast type.
7141 if (SubRange.Width >= OutputTypeRange.Width)
7142 return OutputTypeRange;
7143
7144 // Otherwise, we take the smaller width, and we're non-negative if
7145 // either the output type or the subexpr is.
7146 return IntRange(SubRange.Width,
7147 SubRange.NonNegative || OutputTypeRange.NonNegative);
7148 }
7149
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007150 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00007151 // If we can fold the condition, just take that operand.
7152 bool CondResult;
7153 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
7154 return GetExprRange(C, CondResult ? CO->getTrueExpr()
7155 : CO->getFalseExpr(),
7156 MaxWidth);
7157
7158 // Otherwise, conservatively merge.
7159 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
7160 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
7161 return IntRange::join(L, R);
7162 }
7163
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007164 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00007165 switch (BO->getOpcode()) {
7166
7167 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00007168 case BO_LAnd:
7169 case BO_LOr:
7170 case BO_LT:
7171 case BO_GT:
7172 case BO_LE:
7173 case BO_GE:
7174 case BO_EQ:
7175 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00007176 return IntRange::forBoolType();
7177
John McCallc3688382011-07-13 06:35:24 +00007178 // The type of the assignments is the type of the LHS, so the RHS
7179 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00007180 case BO_MulAssign:
7181 case BO_DivAssign:
7182 case BO_RemAssign:
7183 case BO_AddAssign:
7184 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00007185 case BO_XorAssign:
7186 case BO_OrAssign:
7187 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00007188 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00007189
John McCallc3688382011-07-13 06:35:24 +00007190 // Simple assignments just pass through the RHS, which will have
7191 // been coerced to the LHS type.
7192 case BO_Assign:
7193 // TODO: bitfields?
7194 return GetExprRange(C, BO->getRHS(), MaxWidth);
7195
John McCall70aa5392010-01-06 05:24:50 +00007196 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00007197 case BO_PtrMemD:
7198 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00007199 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00007200
John McCall2ce81ad2010-01-06 22:07:33 +00007201 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00007202 case BO_And:
7203 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00007204 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
7205 GetExprRange(C, BO->getRHS(), MaxWidth));
7206
John McCall70aa5392010-01-06 05:24:50 +00007207 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00007208 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00007209 // ...except that we want to treat '1 << (blah)' as logically
7210 // positive. It's an important idiom.
7211 if (IntegerLiteral *I
7212 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
7213 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00007214 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00007215 return IntRange(R.Width, /*NonNegative*/ true);
7216 }
7217 }
7218 // fallthrough
7219
John McCalle3027922010-08-25 11:45:40 +00007220 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00007221 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00007222
John McCall2ce81ad2010-01-06 22:07:33 +00007223 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00007224 case BO_Shr:
7225 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00007226 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
7227
7228 // If the shift amount is a positive constant, drop the width by
7229 // that much.
7230 llvm::APSInt shift;
7231 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
7232 shift.isNonNegative()) {
7233 unsigned zext = shift.getZExtValue();
7234 if (zext >= L.Width)
7235 L.Width = (L.NonNegative ? 0 : 1);
7236 else
7237 L.Width -= zext;
7238 }
7239
7240 return L;
7241 }
7242
7243 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00007244 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00007245 return GetExprRange(C, BO->getRHS(), MaxWidth);
7246
John McCall2ce81ad2010-01-06 22:07:33 +00007247 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00007248 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00007249 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00007250 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00007251 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007252
John McCall51431812011-07-14 22:39:48 +00007253 // The width of a division result is mostly determined by the size
7254 // of the LHS.
7255 case BO_Div: {
7256 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00007257 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00007258 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
7259
7260 // If the divisor is constant, use that.
7261 llvm::APSInt divisor;
7262 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
7263 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
7264 if (log2 >= L.Width)
7265 L.Width = (L.NonNegative ? 0 : 1);
7266 else
7267 L.Width = std::min(L.Width - log2, MaxWidth);
7268 return L;
7269 }
7270
7271 // Otherwise, just use the LHS's width.
7272 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
7273 return IntRange(L.Width, L.NonNegative && R.NonNegative);
7274 }
7275
7276 // The result of a remainder can't be larger than the result of
7277 // either side.
7278 case BO_Rem: {
7279 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00007280 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00007281 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
7282 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
7283
7284 IntRange meet = IntRange::meet(L, R);
7285 meet.Width = std::min(meet.Width, MaxWidth);
7286 return meet;
7287 }
7288
7289 // The default behavior is okay for these.
7290 case BO_Mul:
7291 case BO_Add:
7292 case BO_Xor:
7293 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00007294 break;
7295 }
7296
John McCall51431812011-07-14 22:39:48 +00007297 // The default case is to treat the operation as if it were closed
7298 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00007299 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
7300 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
7301 return IntRange::join(L, R);
7302 }
7303
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007304 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00007305 switch (UO->getOpcode()) {
7306 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00007307 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00007308 return IntRange::forBoolType();
7309
7310 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00007311 case UO_Deref:
7312 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00007313 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00007314
7315 default:
7316 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
7317 }
7318 }
7319
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007320 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00007321 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
7322
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007323 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00007324 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00007325 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00007326
Eli Friedmane6d33952013-07-08 20:20:06 +00007327 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00007328}
John McCall263a48b2010-01-04 23:31:57 +00007329
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007330IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00007331 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00007332}
7333
John McCall263a48b2010-01-04 23:31:57 +00007334/// Checks whether the given value, which currently has the given
7335/// source semantics, has the same value when coerced through the
7336/// target semantics.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007337bool IsSameFloatAfterCast(const llvm::APFloat &value,
7338 const llvm::fltSemantics &Src,
7339 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00007340 llvm::APFloat truncated = value;
7341
7342 bool ignored;
7343 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
7344 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
7345
7346 return truncated.bitwiseIsEqual(value);
7347}
7348
7349/// Checks whether the given value, which currently has the given
7350/// source semantics, has the same value when coerced through the
7351/// target semantics.
7352///
7353/// The value might be a vector of floats (or a complex number).
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007354bool IsSameFloatAfterCast(const APValue &value,
7355 const llvm::fltSemantics &Src,
7356 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00007357 if (value.isFloat())
7358 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
7359
7360 if (value.isVector()) {
7361 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
7362 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
7363 return false;
7364 return true;
7365 }
7366
7367 assert(value.isComplexFloat());
7368 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
7369 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
7370}
7371
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007372void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007373
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007374bool IsZero(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00007375 // Suppress cases where we are comparing against an enum constant.
7376 if (const DeclRefExpr *DR =
7377 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
7378 if (isa<EnumConstantDecl>(DR->getDecl()))
7379 return false;
7380
7381 // Suppress cases where the '0' value is expanded from a macro.
7382 if (E->getLocStart().isMacroID())
7383 return false;
7384
John McCallcc7e5bf2010-05-06 08:58:33 +00007385 llvm::APSInt Value;
7386 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
7387}
7388
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007389bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00007390 // Strip off implicit integral promotions.
7391 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00007392 if (ICE->getCastKind() != CK_IntegralCast &&
7393 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00007394 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00007395 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00007396 }
7397
7398 return E->getType()->isEnumeralType();
7399}
7400
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007401void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00007402 // Disable warning in template instantiations.
7403 if (!S.ActiveTemplateInstantiations.empty())
7404 return;
7405
John McCalle3027922010-08-25 11:45:40 +00007406 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00007407 if (E->isValueDependent())
7408 return;
7409
John McCalle3027922010-08-25 11:45:40 +00007410 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007411 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00007412 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00007413 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00007414 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007415 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00007416 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00007417 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00007418 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007419 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00007420 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00007421 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00007422 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007423 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00007424 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00007425 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
7426 }
7427}
7428
Benjamin Kramer7320b992016-06-15 14:20:56 +00007429void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant,
7430 Expr *Other, const llvm::APSInt &Value,
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007431 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00007432 // Disable warning in template instantiations.
7433 if (!S.ActiveTemplateInstantiations.empty())
7434 return;
7435
Richard Trieu0f097742014-04-04 04:13:47 +00007436 // TODO: Investigate using GetExprRange() to get tighter bounds
7437 // on the bit ranges.
7438 QualType OtherT = Other->getType();
David Majnemer7800f1f2015-05-23 01:32:17 +00007439 if (const auto *AT = OtherT->getAs<AtomicType>())
Justin Bogner4f42fc42014-07-21 18:01:53 +00007440 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00007441 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
7442 unsigned OtherWidth = OtherRange.Width;
7443
7444 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
7445
Richard Trieu560910c2012-11-14 22:50:24 +00007446 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00007447 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00007448 return;
7449
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007450 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00007451 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00007452
Richard Trieu0f097742014-04-04 04:13:47 +00007453 // Used for diagnostic printout.
7454 enum {
7455 LiteralConstant = 0,
7456 CXXBoolLiteralTrue,
7457 CXXBoolLiteralFalse
7458 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00007459
Richard Trieu0f097742014-04-04 04:13:47 +00007460 if (!OtherIsBooleanType) {
7461 QualType ConstantT = Constant->getType();
7462 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00007463
Richard Trieu0f097742014-04-04 04:13:47 +00007464 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
7465 return;
7466 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
7467 "comparison with non-integer type");
7468
7469 bool ConstantSigned = ConstantT->isSignedIntegerType();
7470 bool CommonSigned = CommonT->isSignedIntegerType();
7471
7472 bool EqualityOnly = false;
7473
7474 if (CommonSigned) {
7475 // The common type is signed, therefore no signed to unsigned conversion.
7476 if (!OtherRange.NonNegative) {
7477 // Check that the constant is representable in type OtherT.
7478 if (ConstantSigned) {
7479 if (OtherWidth >= Value.getMinSignedBits())
7480 return;
7481 } else { // !ConstantSigned
7482 if (OtherWidth >= Value.getActiveBits() + 1)
7483 return;
7484 }
7485 } else { // !OtherSigned
7486 // Check that the constant is representable in type OtherT.
7487 // Negative values are out of range.
7488 if (ConstantSigned) {
7489 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
7490 return;
7491 } else { // !ConstantSigned
7492 if (OtherWidth >= Value.getActiveBits())
7493 return;
7494 }
Richard Trieu560910c2012-11-14 22:50:24 +00007495 }
Richard Trieu0f097742014-04-04 04:13:47 +00007496 } else { // !CommonSigned
7497 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00007498 if (OtherWidth >= Value.getActiveBits())
7499 return;
Craig Toppercf360162014-06-18 05:13:11 +00007500 } else { // OtherSigned
7501 assert(!ConstantSigned &&
7502 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00007503 // Check to see if the constant is representable in OtherT.
7504 if (OtherWidth > Value.getActiveBits())
7505 return;
7506 // Check to see if the constant is equivalent to a negative value
7507 // cast to CommonT.
7508 if (S.Context.getIntWidth(ConstantT) ==
7509 S.Context.getIntWidth(CommonT) &&
7510 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
7511 return;
7512 // The constant value rests between values that OtherT can represent
7513 // after conversion. Relational comparison still works, but equality
7514 // comparisons will be tautological.
7515 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00007516 }
7517 }
Richard Trieu0f097742014-04-04 04:13:47 +00007518
7519 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
7520
7521 if (op == BO_EQ || op == BO_NE) {
7522 IsTrue = op == BO_NE;
7523 } else if (EqualityOnly) {
7524 return;
7525 } else if (RhsConstant) {
7526 if (op == BO_GT || op == BO_GE)
7527 IsTrue = !PositiveConstant;
7528 else // op == BO_LT || op == BO_LE
7529 IsTrue = PositiveConstant;
7530 } else {
7531 if (op == BO_LT || op == BO_LE)
7532 IsTrue = !PositiveConstant;
7533 else // op == BO_GT || op == BO_GE
7534 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00007535 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007536 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00007537 // Other isKnownToHaveBooleanValue
7538 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
7539 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
7540 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
7541
7542 static const struct LinkedConditions {
7543 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
7544 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
7545 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
7546 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
7547 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
7548 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
7549
7550 } TruthTable = {
7551 // Constant on LHS. | Constant on RHS. |
7552 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
7553 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
7554 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
7555 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
7556 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
7557 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
7558 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
7559 };
7560
7561 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
7562
7563 enum ConstantValue ConstVal = Zero;
7564 if (Value.isUnsigned() || Value.isNonNegative()) {
7565 if (Value == 0) {
7566 LiteralOrBoolConstant =
7567 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
7568 ConstVal = Zero;
7569 } else if (Value == 1) {
7570 LiteralOrBoolConstant =
7571 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
7572 ConstVal = One;
7573 } else {
7574 LiteralOrBoolConstant = LiteralConstant;
7575 ConstVal = GT_One;
7576 }
7577 } else {
7578 ConstVal = LT_Zero;
7579 }
7580
7581 CompareBoolWithConstantResult CmpRes;
7582
7583 switch (op) {
7584 case BO_LT:
7585 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
7586 break;
7587 case BO_GT:
7588 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
7589 break;
7590 case BO_LE:
7591 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
7592 break;
7593 case BO_GE:
7594 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
7595 break;
7596 case BO_EQ:
7597 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
7598 break;
7599 case BO_NE:
7600 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
7601 break;
7602 default:
7603 CmpRes = Unkwn;
7604 break;
7605 }
7606
7607 if (CmpRes == AFals) {
7608 IsTrue = false;
7609 } else if (CmpRes == ATrue) {
7610 IsTrue = true;
7611 } else {
7612 return;
7613 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007614 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00007615
7616 // If this is a comparison to an enum constant, include that
7617 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00007618 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00007619 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
7620 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
7621
7622 SmallString<64> PrettySourceValue;
7623 llvm::raw_svector_ostream OS(PrettySourceValue);
7624 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00007625 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00007626 else
7627 OS << Value;
7628
Richard Trieu0f097742014-04-04 04:13:47 +00007629 S.DiagRuntimeBehavior(
7630 E->getOperatorLoc(), E,
7631 S.PDiag(diag::warn_out_of_range_compare)
7632 << OS.str() << LiteralOrBoolConstant
7633 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
7634 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007635}
7636
John McCallcc7e5bf2010-05-06 08:58:33 +00007637/// Analyze the operands of the given comparison. Implements the
7638/// fallback case from AnalyzeComparison.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007639void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00007640 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
7641 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00007642}
John McCall263a48b2010-01-04 23:31:57 +00007643
John McCallca01b222010-01-04 23:21:16 +00007644/// \brief Implements -Wsign-compare.
7645///
Richard Trieu82402a02011-09-15 21:56:47 +00007646/// \param E the binary operator to check for warnings
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007647void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007648 // The type the comparison is being performed in.
7649 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00007650
7651 // Only analyze comparison operators where both sides have been converted to
7652 // the same type.
7653 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
7654 return AnalyzeImpConvsInComparison(S, E);
7655
7656 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00007657 if (E->isValueDependent())
7658 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007659
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007660 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
7661 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007662
7663 bool IsComparisonConstant = false;
7664
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007665 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007666 // of 'true' or 'false'.
7667 if (T->isIntegralType(S.Context)) {
7668 llvm::APSInt RHSValue;
7669 bool IsRHSIntegralLiteral =
7670 RHS->isIntegerConstantExpr(RHSValue, S.Context);
7671 llvm::APSInt LHSValue;
7672 bool IsLHSIntegralLiteral =
7673 LHS->isIntegerConstantExpr(LHSValue, S.Context);
7674 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
7675 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
7676 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
7677 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
7678 else
7679 IsComparisonConstant =
7680 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007681 } else if (!T->hasUnsignedIntegerRepresentation())
7682 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007683
John McCallcc7e5bf2010-05-06 08:58:33 +00007684 // We don't do anything special if this isn't an unsigned integral
7685 // comparison: we're only interested in integral comparisons, and
7686 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00007687 //
7688 // We also don't care about value-dependent expressions or expressions
7689 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007690 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00007691 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007692
John McCallcc7e5bf2010-05-06 08:58:33 +00007693 // Check to see if one of the (unmodified) operands is of different
7694 // signedness.
7695 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00007696 if (LHS->getType()->hasSignedIntegerRepresentation()) {
7697 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00007698 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00007699 signedOperand = LHS;
7700 unsignedOperand = RHS;
7701 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
7702 signedOperand = RHS;
7703 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00007704 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00007705 CheckTrivialUnsignedComparison(S, E);
7706 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007707 }
7708
John McCallcc7e5bf2010-05-06 08:58:33 +00007709 // Otherwise, calculate the effective range of the signed operand.
7710 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00007711
John McCallcc7e5bf2010-05-06 08:58:33 +00007712 // Go ahead and analyze implicit conversions in the operands. Note
7713 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00007714 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
7715 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00007716
John McCallcc7e5bf2010-05-06 08:58:33 +00007717 // If the signed range is non-negative, -Wsign-compare won't fire,
7718 // but we should still check for comparisons which are always true
7719 // or false.
7720 if (signedRange.NonNegative)
7721 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007722
7723 // For (in)equality comparisons, if the unsigned operand is a
7724 // constant which cannot collide with a overflowed signed operand,
7725 // then reinterpreting the signed operand as unsigned will not
7726 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00007727 if (E->isEqualityOp()) {
7728 unsigned comparisonWidth = S.Context.getIntWidth(T);
7729 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00007730
John McCallcc7e5bf2010-05-06 08:58:33 +00007731 // We should never be unable to prove that the unsigned operand is
7732 // non-negative.
7733 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
7734
7735 if (unsignedRange.Width < comparisonWidth)
7736 return;
7737 }
7738
Douglas Gregorbfb4a212012-05-01 01:53:49 +00007739 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
7740 S.PDiag(diag::warn_mixed_sign_comparison)
7741 << LHS->getType() << RHS->getType()
7742 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00007743}
7744
John McCall1f425642010-11-11 03:21:53 +00007745/// Analyzes an attempt to assign the given value to a bitfield.
7746///
7747/// Returns true if there was something fishy about the attempt.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007748bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
7749 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00007750 assert(Bitfield->isBitField());
7751 if (Bitfield->isInvalidDecl())
7752 return false;
7753
John McCalldeebbcf2010-11-11 05:33:51 +00007754 // White-list bool bitfields.
7755 if (Bitfield->getType()->isBooleanType())
7756 return false;
7757
Douglas Gregor789adec2011-02-04 13:09:01 +00007758 // Ignore value- or type-dependent expressions.
7759 if (Bitfield->getBitWidth()->isValueDependent() ||
7760 Bitfield->getBitWidth()->isTypeDependent() ||
7761 Init->isValueDependent() ||
7762 Init->isTypeDependent())
7763 return false;
7764
John McCall1f425642010-11-11 03:21:53 +00007765 Expr *OriginalInit = Init->IgnoreParenImpCasts();
7766
Richard Smith5fab0c92011-12-28 19:48:30 +00007767 llvm::APSInt Value;
7768 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00007769 return false;
7770
John McCall1f425642010-11-11 03:21:53 +00007771 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00007772 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00007773
7774 if (OriginalWidth <= FieldWidth)
7775 return false;
7776
Eli Friedmanc267a322012-01-26 23:11:39 +00007777 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00007778 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00007779 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00007780
Eli Friedmanc267a322012-01-26 23:11:39 +00007781 // Check whether the stored value is equal to the original value.
7782 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00007783 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00007784 return false;
7785
Eli Friedmanc267a322012-01-26 23:11:39 +00007786 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00007787 // therefore don't strictly fit into a signed bitfield of width 1.
7788 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00007789 return false;
7790
John McCall1f425642010-11-11 03:21:53 +00007791 std::string PrettyValue = Value.toString(10);
7792 std::string PrettyTrunc = TruncatedValue.toString(10);
7793
7794 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
7795 << PrettyValue << PrettyTrunc << OriginalInit->getType()
7796 << Init->getSourceRange();
7797
7798 return true;
7799}
7800
John McCalld2a53122010-11-09 23:24:47 +00007801/// Analyze the given simple or compound assignment for warning-worthy
7802/// operations.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007803void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00007804 // Just recurse on the LHS.
7805 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
7806
7807 // We want to recurse on the RHS as normal unless we're assigning to
7808 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00007809 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007810 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00007811 E->getOperatorLoc())) {
7812 // Recurse, ignoring any implicit conversions on the RHS.
7813 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
7814 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00007815 }
7816 }
7817
7818 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
7819}
7820
John McCall263a48b2010-01-04 23:31:57 +00007821/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007822void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
7823 SourceLocation CContext, unsigned diag,
7824 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00007825 if (pruneControlFlow) {
7826 S.DiagRuntimeBehavior(E->getExprLoc(), E,
7827 S.PDiag(diag)
7828 << SourceType << T << E->getSourceRange()
7829 << SourceRange(CContext));
7830 return;
7831 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00007832 S.Diag(E->getExprLoc(), diag)
7833 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
7834}
7835
Chandler Carruth7f3654f2011-04-05 06:47:57 +00007836/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007837void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
7838 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00007839 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00007840}
7841
Richard Trieube234c32016-04-21 21:04:55 +00007842
7843/// Diagnose an implicit cast from a floating point value to an integer value.
7844void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
7845
7846 SourceLocation CContext) {
7847 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
7848 const bool PruneWarnings = !S.ActiveTemplateInstantiations.empty();
7849
7850 Expr *InnerE = E->IgnoreParenImpCasts();
7851 // We also want to warn on, e.g., "int i = -1.234"
7852 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
7853 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
7854 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
7855
7856 const bool IsLiteral =
7857 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
7858
7859 llvm::APFloat Value(0.0);
7860 bool IsConstant =
7861 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
7862 if (!IsConstant) {
Richard Trieu891f0f12016-04-22 22:14:32 +00007863 return DiagnoseImpCast(S, E, T, CContext,
7864 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +00007865 }
7866
Chandler Carruth016ef402011-04-10 08:36:24 +00007867 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +00007868
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00007869 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
7870 T->hasUnsignedIntegerRepresentation());
Richard Trieube234c32016-04-21 21:04:55 +00007871 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
7872 &isExact) == llvm::APFloat::opOK &&
Richard Trieu891f0f12016-04-22 22:14:32 +00007873 isExact) {
Richard Trieube234c32016-04-21 21:04:55 +00007874 if (IsLiteral) return;
7875 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
7876 PruneWarnings);
7877 }
7878
7879 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +00007880 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +00007881 // Warn on floating point literal to integer.
7882 DiagID = diag::warn_impcast_literal_float_to_integer;
7883 } else if (IntegerValue == 0) {
7884 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
7885 return DiagnoseImpCast(S, E, T, CContext,
7886 diag::warn_impcast_float_integer, PruneWarnings);
7887 }
7888 // Warn on non-zero to zero conversion.
7889 DiagID = diag::warn_impcast_float_to_integer_zero;
7890 } else {
7891 if (IntegerValue.isUnsigned()) {
7892 if (!IntegerValue.isMaxValue()) {
7893 return DiagnoseImpCast(S, E, T, CContext,
7894 diag::warn_impcast_float_integer, PruneWarnings);
7895 }
7896 } else { // IntegerValue.isSigned()
7897 if (!IntegerValue.isMaxSignedValue() &&
7898 !IntegerValue.isMinSignedValue()) {
7899 return DiagnoseImpCast(S, E, T, CContext,
7900 diag::warn_impcast_float_integer, PruneWarnings);
7901 }
7902 }
7903 // Warn on evaluatable floating point expression to integer conversion.
7904 DiagID = diag::warn_impcast_float_to_integer;
7905 }
Chandler Carruth016ef402011-04-10 08:36:24 +00007906
Eli Friedman07185912013-08-29 23:44:43 +00007907 // FIXME: Force the precision of the source value down so we don't print
7908 // digits which are usually useless (we don't really care here if we
7909 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
7910 // would automatically print the shortest representation, but it's a bit
7911 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00007912 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00007913 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
7914 precision = (precision * 59 + 195) / 196;
7915 Value.toString(PrettySourceValue, precision);
7916
David Blaikie9b88cc02012-05-15 17:18:27 +00007917 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +00007918 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +00007919 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00007920 else
David Blaikie9b88cc02012-05-15 17:18:27 +00007921 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00007922
Richard Trieube234c32016-04-21 21:04:55 +00007923 if (PruneWarnings) {
7924 S.DiagRuntimeBehavior(E->getExprLoc(), E,
7925 S.PDiag(DiagID)
7926 << E->getType() << T.getUnqualifiedType()
7927 << PrettySourceValue << PrettyTargetValue
7928 << E->getSourceRange() << SourceRange(CContext));
7929 } else {
7930 S.Diag(E->getExprLoc(), DiagID)
7931 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
7932 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
7933 }
Chandler Carruth016ef402011-04-10 08:36:24 +00007934}
7935
John McCall18a2c2c2010-11-09 22:22:12 +00007936std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
7937 if (!Range.Width) return "0";
7938
7939 llvm::APSInt ValueInRange = Value;
7940 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00007941 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00007942 return ValueInRange.toString(10);
7943}
7944
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007945bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007946 if (!isa<ImplicitCastExpr>(Ex))
7947 return false;
7948
7949 Expr *InnerE = Ex->IgnoreParenImpCasts();
7950 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
7951 const Type *Source =
7952 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
7953 if (Target->isDependentType())
7954 return false;
7955
7956 const BuiltinType *FloatCandidateBT =
7957 dyn_cast<BuiltinType>(ToBool ? Source : Target);
7958 const Type *BoolCandidateType = ToBool ? Target : Source;
7959
7960 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
7961 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
7962}
7963
7964void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
7965 SourceLocation CC) {
7966 unsigned NumArgs = TheCall->getNumArgs();
7967 for (unsigned i = 0; i < NumArgs; ++i) {
7968 Expr *CurrA = TheCall->getArg(i);
7969 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
7970 continue;
7971
7972 bool IsSwapped = ((i > 0) &&
7973 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
7974 IsSwapped |= ((i < (NumArgs - 1)) &&
7975 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
7976 if (IsSwapped) {
7977 // Warn on this floating-point to bool conversion.
7978 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
7979 CurrA->getType(), CC,
7980 diag::warn_impcast_floating_point_to_bool);
7981 }
7982 }
7983}
7984
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007985void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00007986 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
7987 E->getExprLoc()))
7988 return;
7989
Richard Trieu09d6b802016-01-08 23:35:06 +00007990 // Don't warn on functions which have return type nullptr_t.
7991 if (isa<CallExpr>(E))
7992 return;
7993
Richard Trieu5b993502014-10-15 03:42:06 +00007994 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
7995 const Expr::NullPointerConstantKind NullKind =
7996 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
7997 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
7998 return;
7999
8000 // Return if target type is a safe conversion.
8001 if (T->isAnyPointerType() || T->isBlockPointerType() ||
8002 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
8003 return;
8004
8005 SourceLocation Loc = E->getSourceRange().getBegin();
8006
Richard Trieu0a5e1662016-02-13 00:58:53 +00008007 // Venture through the macro stacks to get to the source of macro arguments.
8008 // The new location is a better location than the complete location that was
8009 // passed in.
8010 while (S.SourceMgr.isMacroArgExpansion(Loc))
8011 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
8012
8013 while (S.SourceMgr.isMacroArgExpansion(CC))
8014 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
8015
Richard Trieu5b993502014-10-15 03:42:06 +00008016 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +00008017 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
8018 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
8019 Loc, S.SourceMgr, S.getLangOpts());
8020 if (MacroName == "NULL")
8021 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
Richard Trieu5b993502014-10-15 03:42:06 +00008022 }
8023
8024 // Only warn if the null and context location are in the same macro expansion.
8025 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
8026 return;
8027
8028 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
8029 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
8030 << FixItHint::CreateReplacement(Loc,
8031 S.getFixItZeroLiteralForType(T, Loc));
8032}
8033
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008034void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8035 ObjCArrayLiteral *ArrayLiteral);
8036void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8037 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +00008038
8039/// Check a single element within a collection literal against the
8040/// target element type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008041void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
8042 Expr *Element, unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00008043 // Skip a bitcast to 'id' or qualified 'id'.
8044 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
8045 if (ICE->getCastKind() == CK_BitCast &&
8046 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
8047 Element = ICE->getSubExpr();
8048 }
8049
8050 QualType ElementType = Element->getType();
8051 ExprResult ElementResult(Element);
8052 if (ElementType->getAs<ObjCObjectPointerType>() &&
8053 S.CheckSingleAssignmentConstraints(TargetElementType,
8054 ElementResult,
8055 false, false)
8056 != Sema::Compatible) {
8057 S.Diag(Element->getLocStart(),
8058 diag::warn_objc_collection_literal_element)
8059 << ElementType << ElementKind << TargetElementType
8060 << Element->getSourceRange();
8061 }
8062
8063 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
8064 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
8065 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
8066 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
8067}
8068
8069/// Check an Objective-C array literal being converted to the given
8070/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008071void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8072 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00008073 if (!S.NSArrayDecl)
8074 return;
8075
8076 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8077 if (!TargetObjCPtr)
8078 return;
8079
8080 if (TargetObjCPtr->isUnspecialized() ||
8081 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8082 != S.NSArrayDecl->getCanonicalDecl())
8083 return;
8084
8085 auto TypeArgs = TargetObjCPtr->getTypeArgs();
8086 if (TypeArgs.size() != 1)
8087 return;
8088
8089 QualType TargetElementType = TypeArgs[0];
8090 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
8091 checkObjCCollectionLiteralElement(S, TargetElementType,
8092 ArrayLiteral->getElement(I),
8093 0);
8094 }
8095}
8096
8097/// Check an Objective-C dictionary literal being converted to the given
8098/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008099void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8100 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00008101 if (!S.NSDictionaryDecl)
8102 return;
8103
8104 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8105 if (!TargetObjCPtr)
8106 return;
8107
8108 if (TargetObjCPtr->isUnspecialized() ||
8109 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8110 != S.NSDictionaryDecl->getCanonicalDecl())
8111 return;
8112
8113 auto TypeArgs = TargetObjCPtr->getTypeArgs();
8114 if (TypeArgs.size() != 2)
8115 return;
8116
8117 QualType TargetKeyType = TypeArgs[0];
8118 QualType TargetObjectType = TypeArgs[1];
8119 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
8120 auto Element = DictionaryLiteral->getKeyValueElement(I);
8121 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
8122 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
8123 }
8124}
8125
Richard Trieufc404c72016-02-05 23:02:38 +00008126// Helper function to filter out cases for constant width constant conversion.
8127// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008128bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
8129 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +00008130 // If initializing from a constant, and the constant starts with '0',
8131 // then it is a binary, octal, or hexadecimal. Allow these constants
8132 // to fill all the bits, even if there is a sign change.
8133 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
8134 const char FirstLiteralCharacter =
8135 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
8136 if (FirstLiteralCharacter == '0')
8137 return false;
8138 }
8139
8140 // If the CC location points to a '{', and the type is char, then assume
8141 // assume it is an array initialization.
8142 if (CC.isValid() && T->isCharType()) {
8143 const char FirstContextCharacter =
8144 S.getSourceManager().getCharacterData(CC)[0];
8145 if (FirstContextCharacter == '{')
8146 return false;
8147 }
8148
8149 return true;
8150}
8151
John McCallcc7e5bf2010-05-06 08:58:33 +00008152void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00008153 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008154 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00008155
John McCallcc7e5bf2010-05-06 08:58:33 +00008156 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
8157 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
8158 if (Source == Target) return;
8159 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00008160
Chandler Carruthc22845a2011-07-26 05:40:03 +00008161 // If the conversion context location is invalid don't complain. We also
8162 // don't want to emit a warning if the issue occurs from the expansion of
8163 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
8164 // delay this check as long as possible. Once we detect we are in that
8165 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008166 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00008167 return;
8168
Richard Trieu021baa32011-09-23 20:10:00 +00008169 // Diagnose implicit casts to bool.
8170 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
8171 if (isa<StringLiteral>(E))
8172 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00008173 // and expressions, for instance, assert(0 && "error here"), are
8174 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00008175 return DiagnoseImpCast(S, E, T, CC,
8176 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00008177 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
8178 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
8179 // This covers the literal expressions that evaluate to Objective-C
8180 // objects.
8181 return DiagnoseImpCast(S, E, T, CC,
8182 diag::warn_impcast_objective_c_literal_to_bool);
8183 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00008184 if (Source->isPointerType() || Source->canDecayToPointerType()) {
8185 // Warn on pointer to bool conversion that is always true.
8186 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
8187 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00008188 }
Richard Trieu021baa32011-09-23 20:10:00 +00008189 }
John McCall263a48b2010-01-04 23:31:57 +00008190
Douglas Gregor5054cb02015-07-07 03:58:22 +00008191 // Check implicit casts from Objective-C collection literals to specialized
8192 // collection types, e.g., NSArray<NSString *> *.
8193 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
8194 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
8195 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
8196 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
8197
John McCall263a48b2010-01-04 23:31:57 +00008198 // Strip vector types.
8199 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008200 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008201 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008202 return;
John McCallacf0ee52010-10-08 02:01:28 +00008203 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008204 }
Chris Lattneree7286f2011-06-14 04:51:15 +00008205
8206 // If the vector cast is cast between two vectors of the same size, it is
8207 // a bitcast, not a conversion.
8208 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
8209 return;
John McCall263a48b2010-01-04 23:31:57 +00008210
8211 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
8212 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
8213 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00008214 if (auto VecTy = dyn_cast<VectorType>(Target))
8215 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00008216
8217 // Strip complex types.
8218 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008219 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008220 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008221 return;
8222
John McCallacf0ee52010-10-08 02:01:28 +00008223 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008224 }
John McCall263a48b2010-01-04 23:31:57 +00008225
8226 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
8227 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
8228 }
8229
8230 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
8231 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
8232
8233 // If the source is floating point...
8234 if (SourceBT && SourceBT->isFloatingPoint()) {
8235 // ...and the target is floating point...
8236 if (TargetBT && TargetBT->isFloatingPoint()) {
8237 // ...then warn if we're dropping FP rank.
8238
8239 // Builtin FP kinds are ordered by increasing FP rank.
8240 if (SourceBT->getKind() > TargetBT->getKind()) {
8241 // Don't warn about float constants that are precisely
8242 // representable in the target type.
8243 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00008244 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00008245 // Value might be a float, a float vector, or a float complex.
8246 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00008247 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
8248 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00008249 return;
8250 }
8251
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008252 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008253 return;
8254
John McCallacf0ee52010-10-08 02:01:28 +00008255 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +00008256 }
8257 // ... or possibly if we're increasing rank, too
8258 else if (TargetBT->getKind() > SourceBT->getKind()) {
8259 if (S.SourceMgr.isInSystemMacro(CC))
8260 return;
8261
8262 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +00008263 }
8264 return;
8265 }
8266
Richard Trieube234c32016-04-21 21:04:55 +00008267 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00008268 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008269 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008270 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00008271
Richard Trieube234c32016-04-21 21:04:55 +00008272 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00008273 }
John McCall263a48b2010-01-04 23:31:57 +00008274
Richard Smith54894fd2015-12-30 01:06:52 +00008275 // Detect the case where a call result is converted from floating-point to
8276 // to bool, and the final argument to the call is converted from bool, to
8277 // discover this typo:
8278 //
8279 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
8280 //
8281 // FIXME: This is an incredibly special case; is there some more general
8282 // way to detect this class of misplaced-parentheses bug?
8283 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008284 // Check last argument of function call to see if it is an
8285 // implicit cast from a type matching the type the result
8286 // is being cast to.
8287 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +00008288 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008289 Expr *LastA = CEx->getArg(NumArgs - 1);
8290 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +00008291 if (isa<ImplicitCastExpr>(LastA) &&
8292 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008293 // Warn on this floating-point to bool conversion
8294 DiagnoseImpCast(S, E, T, CC,
8295 diag::warn_impcast_floating_point_to_bool);
8296 }
8297 }
8298 }
John McCall263a48b2010-01-04 23:31:57 +00008299 return;
8300 }
8301
Richard Trieu5b993502014-10-15 03:42:06 +00008302 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00008303
David Blaikie9366d2b2012-06-19 21:19:06 +00008304 if (!Source->isIntegerType() || !Target->isIntegerType())
8305 return;
8306
David Blaikie7555b6a2012-05-15 16:56:36 +00008307 // TODO: remove this early return once the false positives for constant->bool
8308 // in templates, macros, etc, are reduced or removed.
8309 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
8310 return;
8311
John McCallcc7e5bf2010-05-06 08:58:33 +00008312 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00008313 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00008314
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008315 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00008316 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008317 // TODO: this should happen for bitfield stores, too.
8318 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +00008319 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008320 if (S.SourceMgr.isInSystemMacro(CC))
8321 return;
8322
John McCall18a2c2c2010-11-09 22:22:12 +00008323 std::string PrettySourceValue = Value.toString(10);
8324 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008325
Ted Kremenek33ba9952011-10-22 02:37:33 +00008326 S.DiagRuntimeBehavior(E->getExprLoc(), E,
8327 S.PDiag(diag::warn_impcast_integer_precision_constant)
8328 << PrettySourceValue << PrettyTargetValue
8329 << E->getType() << T << E->getSourceRange()
8330 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00008331 return;
8332 }
8333
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008334 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
8335 if (S.SourceMgr.isInSystemMacro(CC))
8336 return;
8337
David Blaikie9455da02012-04-12 22:40:54 +00008338 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00008339 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
8340 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00008341 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00008342 }
8343
Richard Trieudcb55572016-01-29 23:51:16 +00008344 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
8345 SourceRange.NonNegative && Source->isSignedIntegerType()) {
8346 // Warn when doing a signed to signed conversion, warn if the positive
8347 // source value is exactly the width of the target type, which will
8348 // cause a negative value to be stored.
8349
8350 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +00008351 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
8352 !S.SourceMgr.isInSystemMacro(CC)) {
8353 if (isSameWidthConstantConversion(S, E, T, CC)) {
8354 std::string PrettySourceValue = Value.toString(10);
8355 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +00008356
Richard Trieufc404c72016-02-05 23:02:38 +00008357 S.DiagRuntimeBehavior(
8358 E->getExprLoc(), E,
8359 S.PDiag(diag::warn_impcast_integer_precision_constant)
8360 << PrettySourceValue << PrettyTargetValue << E->getType() << T
8361 << E->getSourceRange() << clang::SourceRange(CC));
8362 return;
Richard Trieudcb55572016-01-29 23:51:16 +00008363 }
8364 }
Richard Trieufc404c72016-02-05 23:02:38 +00008365
Richard Trieudcb55572016-01-29 23:51:16 +00008366 // Fall through for non-constants to give a sign conversion warning.
8367 }
8368
John McCallcc7e5bf2010-05-06 08:58:33 +00008369 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
8370 (!TargetRange.NonNegative && SourceRange.NonNegative &&
8371 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008372 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008373 return;
8374
John McCallcc7e5bf2010-05-06 08:58:33 +00008375 unsigned DiagID = diag::warn_impcast_integer_sign;
8376
8377 // Traditionally, gcc has warned about this under -Wsign-compare.
8378 // We also want to warn about it in -Wconversion.
8379 // So if -Wconversion is off, use a completely identical diagnostic
8380 // in the sign-compare group.
8381 // The conditional-checking code will
8382 if (ICContext) {
8383 DiagID = diag::warn_impcast_integer_sign_conditional;
8384 *ICContext = true;
8385 }
8386
John McCallacf0ee52010-10-08 02:01:28 +00008387 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00008388 }
8389
Douglas Gregora78f1932011-02-22 02:45:07 +00008390 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00008391 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
8392 // type, to give us better diagnostics.
8393 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00008394 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00008395 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8396 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
8397 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
8398 SourceType = S.Context.getTypeDeclType(Enum);
8399 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
8400 }
8401 }
8402
Douglas Gregora78f1932011-02-22 02:45:07 +00008403 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
8404 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00008405 if (SourceEnum->getDecl()->hasNameForLinkage() &&
8406 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008407 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008408 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008409 return;
8410
Douglas Gregor364f7db2011-03-12 00:14:31 +00008411 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00008412 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008413 }
John McCall263a48b2010-01-04 23:31:57 +00008414}
8415
David Blaikie18e9ac72012-05-15 21:57:38 +00008416void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
8417 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00008418
8419void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00008420 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008421 E = E->IgnoreParenImpCasts();
8422
8423 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00008424 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00008425
John McCallacf0ee52010-10-08 02:01:28 +00008426 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008427 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00008428 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00008429}
8430
David Blaikie18e9ac72012-05-15 21:57:38 +00008431void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
8432 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00008433 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00008434
8435 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00008436 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
8437 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00008438
8439 // If -Wconversion would have warned about either of the candidates
8440 // for a signedness conversion to the context type...
8441 if (!Suspicious) return;
8442
8443 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008444 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00008445 return;
8446
John McCallcc7e5bf2010-05-06 08:58:33 +00008447 // ...then check whether it would have warned about either of the
8448 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00008449 if (E->getType() == T) return;
8450
8451 Suspicious = false;
8452 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
8453 E->getType(), CC, &Suspicious);
8454 if (!Suspicious)
8455 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00008456 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00008457}
8458
Richard Trieu65724892014-11-15 06:37:39 +00008459/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
8460/// Input argument E is a logical expression.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008461void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +00008462 if (S.getLangOpts().Bool)
8463 return;
8464 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
8465}
8466
John McCallcc7e5bf2010-05-06 08:58:33 +00008467/// AnalyzeImplicitConversions - Find and report any interesting
8468/// implicit conversions in the given expression. There are a couple
8469/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00008470void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00008471 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00008472 Expr *E = OrigE->IgnoreParenImpCasts();
8473
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00008474 if (E->isTypeDependent() || E->isValueDependent())
8475 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00008476
John McCallcc7e5bf2010-05-06 08:58:33 +00008477 // For conditional operators, we analyze the arguments as if they
8478 // were being fed directly into the output.
8479 if (isa<ConditionalOperator>(E)) {
8480 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00008481 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00008482 return;
8483 }
8484
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008485 // Check implicit argument conversions for function calls.
8486 if (CallExpr *Call = dyn_cast<CallExpr>(E))
8487 CheckImplicitArgumentConversions(S, Call, CC);
8488
John McCallcc7e5bf2010-05-06 08:58:33 +00008489 // Go ahead and check any implicit conversions we might have skipped.
8490 // The non-canonical typecheck is just an optimization;
8491 // CheckImplicitConversion will filter out dead implicit conversions.
8492 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00008493 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008494
8495 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +00008496
8497 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
8498 // The bound subexpressions in a PseudoObjectExpr are not reachable
8499 // as transitive children.
8500 // FIXME: Use a more uniform representation for this.
8501 for (auto *SE : POE->semantics())
8502 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
8503 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00008504 }
Richard Smithd7bed4d2015-11-22 02:57:17 +00008505
John McCallcc7e5bf2010-05-06 08:58:33 +00008506 // Skip past explicit casts.
8507 if (isa<ExplicitCastExpr>(E)) {
8508 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00008509 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008510 }
8511
John McCalld2a53122010-11-09 23:24:47 +00008512 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8513 // Do a somewhat different check with comparison operators.
8514 if (BO->isComparisonOp())
8515 return AnalyzeComparison(S, BO);
8516
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008517 // And with simple assignments.
8518 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00008519 return AnalyzeAssignment(S, BO);
8520 }
John McCallcc7e5bf2010-05-06 08:58:33 +00008521
8522 // These break the otherwise-useful invariant below. Fortunately,
8523 // we don't really need to recurse into them, because any internal
8524 // expressions should have been analyzed already when they were
8525 // built into statements.
8526 if (isa<StmtExpr>(E)) return;
8527
8528 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00008529 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00008530
8531 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00008532 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00008533 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00008534 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +00008535 for (Stmt *SubStmt : E->children()) {
8536 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00008537 if (!ChildExpr)
8538 continue;
8539
Richard Trieu955231d2014-01-25 01:10:35 +00008540 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00008541 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00008542 // Ignore checking string literals that are in logical and operators.
8543 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00008544 continue;
8545 AnalyzeImplicitConversions(S, ChildExpr, CC);
8546 }
Richard Trieu791b86e2014-11-19 06:08:18 +00008547
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00008548 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00008549 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
8550 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00008551 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00008552
8553 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
8554 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00008555 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00008556 }
Richard Trieu791b86e2014-11-19 06:08:18 +00008557
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00008558 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
8559 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00008560 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008561}
8562
8563} // end anonymous namespace
8564
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00008565static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
8566 unsigned Start, unsigned End) {
8567 bool IllegalParams = false;
8568 for (unsigned I = Start; I <= End; ++I) {
8569 QualType Ty = TheCall->getArg(I)->getType();
8570 // Taking into account implicit conversions,
8571 // allow any integer within 32 bits range
8572 if (!Ty->isIntegerType() ||
8573 S.Context.getTypeSizeInChars(Ty).getQuantity() > 4) {
8574 S.Diag(TheCall->getArg(I)->getLocStart(),
8575 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
8576 IllegalParams = true;
8577 }
8578 // Potentially emit standard warnings for implicit conversions if enabled
8579 // using -Wconversion.
8580 CheckImplicitConversion(S, TheCall->getArg(I), S.Context.UnsignedIntTy,
8581 TheCall->getArg(I)->getLocStart());
8582 }
8583 return IllegalParams;
8584}
8585
Richard Trieuc1888e02014-06-28 23:25:37 +00008586// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
8587// Returns true when emitting a warning about taking the address of a reference.
8588static bool CheckForReference(Sema &SemaRef, const Expr *E,
Benjamin Kramer7320b992016-06-15 14:20:56 +00008589 const PartialDiagnostic &PD) {
Richard Trieuc1888e02014-06-28 23:25:37 +00008590 E = E->IgnoreParenImpCasts();
8591
8592 const FunctionDecl *FD = nullptr;
8593
8594 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8595 if (!DRE->getDecl()->getType()->isReferenceType())
8596 return false;
8597 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
8598 if (!M->getMemberDecl()->getType()->isReferenceType())
8599 return false;
8600 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00008601 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00008602 return false;
8603 FD = Call->getDirectCallee();
8604 } else {
8605 return false;
8606 }
8607
8608 SemaRef.Diag(E->getExprLoc(), PD);
8609
8610 // If possible, point to location of function.
8611 if (FD) {
8612 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
8613 }
8614
8615 return true;
8616}
8617
Richard Trieu4cbff5c2014-08-08 22:41:43 +00008618// Returns true if the SourceLocation is expanded from any macro body.
8619// Returns false if the SourceLocation is invalid, is from not in a macro
8620// expansion, or is from expanded from a top-level macro argument.
8621static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
8622 if (Loc.isInvalid())
8623 return false;
8624
8625 while (Loc.isMacroID()) {
8626 if (SM.isMacroBodyExpansion(Loc))
8627 return true;
8628 Loc = SM.getImmediateMacroCallerLoc(Loc);
8629 }
8630
8631 return false;
8632}
8633
Richard Trieu3bb8b562014-02-26 02:36:06 +00008634/// \brief Diagnose pointers that are always non-null.
8635/// \param E the expression containing the pointer
8636/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
8637/// compared to a null pointer
8638/// \param IsEqual True when the comparison is equal to a null pointer
8639/// \param Range Extra SourceRange to highlight in the diagnostic
8640void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
8641 Expr::NullPointerConstantKind NullKind,
8642 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00008643 if (!E)
8644 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008645
8646 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00008647 if (E->getExprLoc().isMacroID()) {
8648 const SourceManager &SM = getSourceManager();
8649 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
8650 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00008651 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00008652 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00008653 E = E->IgnoreImpCasts();
8654
8655 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
8656
Richard Trieuf7432752014-06-06 21:39:26 +00008657 if (isa<CXXThisExpr>(E)) {
8658 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
8659 : diag::warn_this_bool_conversion;
8660 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
8661 return;
8662 }
8663
Richard Trieu3bb8b562014-02-26 02:36:06 +00008664 bool IsAddressOf = false;
8665
8666 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
8667 if (UO->getOpcode() != UO_AddrOf)
8668 return;
8669 IsAddressOf = true;
8670 E = UO->getSubExpr();
8671 }
8672
Richard Trieuc1888e02014-06-28 23:25:37 +00008673 if (IsAddressOf) {
8674 unsigned DiagID = IsCompare
8675 ? diag::warn_address_of_reference_null_compare
8676 : diag::warn_address_of_reference_bool_conversion;
8677 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
8678 << IsEqual;
8679 if (CheckForReference(*this, E, PD)) {
8680 return;
8681 }
8682 }
8683
Nick Lewyckybc85ec82016-06-15 05:18:39 +00008684 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
8685 bool IsParam = isa<NonNullAttr>(NonnullAttr);
George Burgess IV850269a2015-12-08 22:02:00 +00008686 std::string Str;
8687 llvm::raw_string_ostream S(Str);
8688 E->printPretty(S, nullptr, getPrintingPolicy());
8689 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
8690 : diag::warn_cast_nonnull_to_bool;
8691 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
8692 << E->getSourceRange() << Range << IsEqual;
Nick Lewyckybc85ec82016-06-15 05:18:39 +00008693 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
George Burgess IV850269a2015-12-08 22:02:00 +00008694 };
8695
8696 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
8697 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
8698 if (auto *Callee = Call->getDirectCallee()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00008699 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
8700 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00008701 return;
8702 }
8703 }
8704 }
8705
Richard Trieu3bb8b562014-02-26 02:36:06 +00008706 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00008707 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008708 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
8709 D = R->getDecl();
8710 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
8711 D = M->getMemberDecl();
8712 }
8713
8714 // Weak Decls can be null.
8715 if (!D || D->isWeak())
8716 return;
George Burgess IV850269a2015-12-08 22:02:00 +00008717
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008718 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +00008719 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
8720 if (getCurFunction() &&
8721 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00008722 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
8723 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00008724 return;
8725 }
8726
8727 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
David Majnemera3debed2016-06-24 05:33:44 +00008728 auto ParamIter = llvm::find(FD->parameters(), PV);
George Burgess IV850269a2015-12-08 22:02:00 +00008729 assert(ParamIter != FD->param_end());
8730 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
8731
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008732 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
8733 if (!NonNull->args_size()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00008734 ComplainAboutNonnullParamOrCall(NonNull);
George Burgess IV850269a2015-12-08 22:02:00 +00008735 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008736 }
George Burgess IV850269a2015-12-08 22:02:00 +00008737
8738 for (unsigned ArgNo : NonNull->args()) {
8739 if (ArgNo == ParamNo) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00008740 ComplainAboutNonnullParamOrCall(NonNull);
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008741 return;
8742 }
George Burgess IV850269a2015-12-08 22:02:00 +00008743 }
8744 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008745 }
8746 }
George Burgess IV850269a2015-12-08 22:02:00 +00008747 }
8748
Richard Trieu3bb8b562014-02-26 02:36:06 +00008749 QualType T = D->getType();
8750 const bool IsArray = T->isArrayType();
8751 const bool IsFunction = T->isFunctionType();
8752
Richard Trieuc1888e02014-06-28 23:25:37 +00008753 // Address of function is used to silence the function warning.
8754 if (IsAddressOf && IsFunction) {
8755 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008756 }
8757
8758 // Found nothing.
8759 if (!IsAddressOf && !IsFunction && !IsArray)
8760 return;
8761
8762 // Pretty print the expression for the diagnostic.
8763 std::string Str;
8764 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00008765 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00008766
8767 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
8768 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +00008769 enum {
8770 AddressOf,
8771 FunctionPointer,
8772 ArrayPointer
8773 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008774 if (IsAddressOf)
8775 DiagType = AddressOf;
8776 else if (IsFunction)
8777 DiagType = FunctionPointer;
8778 else if (IsArray)
8779 DiagType = ArrayPointer;
8780 else
8781 llvm_unreachable("Could not determine diagnostic.");
8782 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
8783 << Range << IsEqual;
8784
8785 if (!IsFunction)
8786 return;
8787
8788 // Suggest '&' to silence the function warning.
8789 Diag(E->getExprLoc(), diag::note_function_warning_silence)
8790 << FixItHint::CreateInsertion(E->getLocStart(), "&");
8791
8792 // Check to see if '()' fixit should be emitted.
8793 QualType ReturnType;
8794 UnresolvedSet<4> NonTemplateOverloads;
8795 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
8796 if (ReturnType.isNull())
8797 return;
8798
8799 if (IsCompare) {
8800 // There are two cases here. If there is null constant, the only suggest
8801 // for a pointer return type. If the null is 0, then suggest if the return
8802 // type is a pointer or an integer type.
8803 if (!ReturnType->isPointerType()) {
8804 if (NullKind == Expr::NPCK_ZeroExpression ||
8805 NullKind == Expr::NPCK_ZeroLiteral) {
8806 if (!ReturnType->isIntegerType())
8807 return;
8808 } else {
8809 return;
8810 }
8811 }
8812 } else { // !IsCompare
8813 // For function to bool, only suggest if the function pointer has bool
8814 // return type.
8815 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
8816 return;
8817 }
8818 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00008819 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00008820}
8821
John McCallcc7e5bf2010-05-06 08:58:33 +00008822/// Diagnoses "dangerous" implicit conversions within the given
8823/// expression (which is a full expression). Implements -Wconversion
8824/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00008825///
8826/// \param CC the "context" location of the implicit conversion, i.e.
8827/// the most location of the syntactic entity requiring the implicit
8828/// conversion
8829void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008830 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00008831 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00008832 return;
8833
8834 // Don't diagnose for value- or type-dependent expressions.
8835 if (E->isTypeDependent() || E->isValueDependent())
8836 return;
8837
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008838 // Check for array bounds violations in cases where the check isn't triggered
8839 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
8840 // ArraySubscriptExpr is on the RHS of a variable initialization.
8841 CheckArrayAccess(E);
8842
John McCallacf0ee52010-10-08 02:01:28 +00008843 // This is not the right CC for (e.g.) a variable initialization.
8844 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008845}
8846
Richard Trieu65724892014-11-15 06:37:39 +00008847/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
8848/// Input argument E is a logical expression.
8849void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
8850 ::CheckBoolLikeConversion(*this, E, CC);
8851}
8852
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008853/// Diagnose when expression is an integer constant expression and its evaluation
8854/// results in integer overflow
8855void Sema::CheckForIntOverflow (Expr *E) {
Akira Hatanakadfe2156f2016-02-10 06:06:06 +00008856 // Use a work list to deal with nested struct initializers.
8857 SmallVector<Expr *, 2> Exprs(1, E);
8858
8859 do {
8860 Expr *E = Exprs.pop_back_val();
8861
8862 if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
8863 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
8864 continue;
8865 }
8866
8867 if (auto InitList = dyn_cast<InitListExpr>(E))
8868 Exprs.append(InitList->inits().begin(), InitList->inits().end());
8869 } while (!Exprs.empty());
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008870}
8871
Richard Smithc406cb72013-01-17 01:17:56 +00008872namespace {
8873/// \brief Visitor for expressions which looks for unsequenced operations on the
8874/// same object.
8875class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00008876 typedef EvaluatedExprVisitor<SequenceChecker> Base;
8877
Richard Smithc406cb72013-01-17 01:17:56 +00008878 /// \brief A tree of sequenced regions within an expression. Two regions are
8879 /// unsequenced if one is an ancestor or a descendent of the other. When we
8880 /// finish processing an expression with sequencing, such as a comma
8881 /// expression, we fold its tree nodes into its parent, since they are
8882 /// unsequenced with respect to nodes we will visit later.
8883 class SequenceTree {
8884 struct Value {
8885 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
8886 unsigned Parent : 31;
Aaron Ballmanaffa1c32016-07-06 18:33:01 +00008887 unsigned Merged : 1;
Richard Smithc406cb72013-01-17 01:17:56 +00008888 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008889 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00008890
8891 public:
8892 /// \brief A region within an expression which may be sequenced with respect
8893 /// to some other region.
8894 class Seq {
8895 explicit Seq(unsigned N) : Index(N) {}
8896 unsigned Index;
8897 friend class SequenceTree;
8898 public:
8899 Seq() : Index(0) {}
8900 };
8901
8902 SequenceTree() { Values.push_back(Value(0)); }
8903 Seq root() const { return Seq(0); }
8904
8905 /// \brief Create a new sequence of operations, which is an unsequenced
8906 /// subset of \p Parent. This sequence of operations is sequenced with
8907 /// respect to other children of \p Parent.
8908 Seq allocate(Seq Parent) {
8909 Values.push_back(Value(Parent.Index));
8910 return Seq(Values.size() - 1);
8911 }
8912
8913 /// \brief Merge a sequence of operations into its parent.
8914 void merge(Seq S) {
8915 Values[S.Index].Merged = true;
8916 }
8917
8918 /// \brief Determine whether two operations are unsequenced. This operation
8919 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
8920 /// should have been merged into its parent as appropriate.
8921 bool isUnsequenced(Seq Cur, Seq Old) {
8922 unsigned C = representative(Cur.Index);
8923 unsigned Target = representative(Old.Index);
8924 while (C >= Target) {
8925 if (C == Target)
8926 return true;
8927 C = Values[C].Parent;
8928 }
8929 return false;
8930 }
8931
8932 private:
8933 /// \brief Pick a representative for a sequence.
8934 unsigned representative(unsigned K) {
8935 if (Values[K].Merged)
8936 // Perform path compression as we go.
8937 return Values[K].Parent = representative(Values[K].Parent);
8938 return K;
8939 }
8940 };
8941
8942 /// An object for which we can track unsequenced uses.
8943 typedef NamedDecl *Object;
8944
8945 /// Different flavors of object usage which we track. We only track the
8946 /// least-sequenced usage of each kind.
8947 enum UsageKind {
8948 /// A read of an object. Multiple unsequenced reads are OK.
8949 UK_Use,
8950 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00008951 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00008952 UK_ModAsValue,
8953 /// A modification of an object which is not sequenced before the value
8954 /// computation of the expression, such as n++.
8955 UK_ModAsSideEffect,
8956
8957 UK_Count = UK_ModAsSideEffect + 1
8958 };
8959
8960 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00008961 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00008962 Expr *Use;
8963 SequenceTree::Seq Seq;
8964 };
8965
8966 struct UsageInfo {
8967 UsageInfo() : Diagnosed(false) {}
8968 Usage Uses[UK_Count];
8969 /// Have we issued a diagnostic for this variable already?
8970 bool Diagnosed;
8971 };
8972 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
8973
8974 Sema &SemaRef;
8975 /// Sequenced regions within the expression.
8976 SequenceTree Tree;
8977 /// Declaration modifications and references which we have seen.
8978 UsageInfoMap UsageMap;
8979 /// The region we are currently within.
8980 SequenceTree::Seq Region;
8981 /// Filled in with declarations which were modified as a side-effect
8982 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008983 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00008984 /// Expressions to check later. We defer checking these to reduce
8985 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008986 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00008987
8988 /// RAII object wrapping the visitation of a sequenced subexpression of an
8989 /// expression. At the end of this process, the side-effects of the evaluation
8990 /// become sequenced with respect to the value computation of the result, so
8991 /// we downgrade any UK_ModAsSideEffect within the evaluation to
8992 /// UK_ModAsValue.
8993 struct SequencedSubexpression {
8994 SequencedSubexpression(SequenceChecker &Self)
8995 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
8996 Self.ModAsSideEffect = &ModAsSideEffect;
8997 }
8998 ~SequencedSubexpression() {
David Majnemerf7e36092016-06-23 00:15:04 +00008999 for (auto &M : llvm::reverse(ModAsSideEffect)) {
9000 UsageInfo &U = Self.UsageMap[M.first];
Richard Smithe8efd992014-12-03 01:05:50 +00009001 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
David Majnemerf7e36092016-06-23 00:15:04 +00009002 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
9003 SideEffectUsage = M.second;
Richard Smithc406cb72013-01-17 01:17:56 +00009004 }
9005 Self.ModAsSideEffect = OldModAsSideEffect;
9006 }
9007
9008 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009009 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
9010 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00009011 };
9012
Richard Smith40238f02013-06-20 22:21:56 +00009013 /// RAII object wrapping the visitation of a subexpression which we might
9014 /// choose to evaluate as a constant. If any subexpression is evaluated and
9015 /// found to be non-constant, this allows us to suppress the evaluation of
9016 /// the outer expression.
9017 class EvaluationTracker {
9018 public:
9019 EvaluationTracker(SequenceChecker &Self)
9020 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
9021 Self.EvalTracker = this;
9022 }
9023 ~EvaluationTracker() {
9024 Self.EvalTracker = Prev;
9025 if (Prev)
9026 Prev->EvalOK &= EvalOK;
9027 }
9028
9029 bool evaluate(const Expr *E, bool &Result) {
9030 if (!EvalOK || E->isValueDependent())
9031 return false;
9032 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
9033 return EvalOK;
9034 }
9035
9036 private:
9037 SequenceChecker &Self;
9038 EvaluationTracker *Prev;
9039 bool EvalOK;
9040 } *EvalTracker;
9041
Richard Smithc406cb72013-01-17 01:17:56 +00009042 /// \brief Find the object which is produced by the specified expression,
9043 /// if any.
9044 Object getObject(Expr *E, bool Mod) const {
9045 E = E->IgnoreParenCasts();
9046 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9047 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
9048 return getObject(UO->getSubExpr(), Mod);
9049 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9050 if (BO->getOpcode() == BO_Comma)
9051 return getObject(BO->getRHS(), Mod);
9052 if (Mod && BO->isAssignmentOp())
9053 return getObject(BO->getLHS(), Mod);
9054 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9055 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
9056 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
9057 return ME->getMemberDecl();
9058 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9059 // FIXME: If this is a reference, map through to its value.
9060 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00009061 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00009062 }
9063
9064 /// \brief Note that an object was modified or used by an expression.
9065 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
9066 Usage &U = UI.Uses[UK];
9067 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
9068 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
9069 ModAsSideEffect->push_back(std::make_pair(O, U));
9070 U.Use = Ref;
9071 U.Seq = Region;
9072 }
9073 }
9074 /// \brief Check whether a modification or use conflicts with a prior usage.
9075 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
9076 bool IsModMod) {
9077 if (UI.Diagnosed)
9078 return;
9079
9080 const Usage &U = UI.Uses[OtherKind];
9081 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
9082 return;
9083
9084 Expr *Mod = U.Use;
9085 Expr *ModOrUse = Ref;
9086 if (OtherKind == UK_Use)
9087 std::swap(Mod, ModOrUse);
9088
9089 SemaRef.Diag(Mod->getExprLoc(),
9090 IsModMod ? diag::warn_unsequenced_mod_mod
9091 : diag::warn_unsequenced_mod_use)
9092 << O << SourceRange(ModOrUse->getExprLoc());
9093 UI.Diagnosed = true;
9094 }
9095
9096 void notePreUse(Object O, Expr *Use) {
9097 UsageInfo &U = UsageMap[O];
9098 // Uses conflict with other modifications.
9099 checkUsage(O, U, Use, UK_ModAsValue, false);
9100 }
9101 void notePostUse(Object O, Expr *Use) {
9102 UsageInfo &U = UsageMap[O];
9103 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
9104 addUsage(U, O, Use, UK_Use);
9105 }
9106
9107 void notePreMod(Object O, Expr *Mod) {
9108 UsageInfo &U = UsageMap[O];
9109 // Modifications conflict with other modifications and with uses.
9110 checkUsage(O, U, Mod, UK_ModAsValue, true);
9111 checkUsage(O, U, Mod, UK_Use, false);
9112 }
9113 void notePostMod(Object O, Expr *Use, UsageKind UK) {
9114 UsageInfo &U = UsageMap[O];
9115 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
9116 addUsage(U, O, Use, UK);
9117 }
9118
9119public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009120 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00009121 : Base(S.Context), SemaRef(S), Region(Tree.root()),
9122 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00009123 Visit(E);
9124 }
9125
9126 void VisitStmt(Stmt *S) {
9127 // Skip all statements which aren't expressions for now.
9128 }
9129
9130 void VisitExpr(Expr *E) {
9131 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00009132 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00009133 }
9134
9135 void VisitCastExpr(CastExpr *E) {
9136 Object O = Object();
9137 if (E->getCastKind() == CK_LValueToRValue)
9138 O = getObject(E->getSubExpr(), false);
9139
9140 if (O)
9141 notePreUse(O, E);
9142 VisitExpr(E);
9143 if (O)
9144 notePostUse(O, E);
9145 }
9146
9147 void VisitBinComma(BinaryOperator *BO) {
9148 // C++11 [expr.comma]p1:
9149 // Every value computation and side effect associated with the left
9150 // expression is sequenced before every value computation and side
9151 // effect associated with the right expression.
9152 SequenceTree::Seq LHS = Tree.allocate(Region);
9153 SequenceTree::Seq RHS = Tree.allocate(Region);
9154 SequenceTree::Seq OldRegion = Region;
9155
9156 {
9157 SequencedSubexpression SeqLHS(*this);
9158 Region = LHS;
9159 Visit(BO->getLHS());
9160 }
9161
9162 Region = RHS;
9163 Visit(BO->getRHS());
9164
9165 Region = OldRegion;
9166
9167 // Forget that LHS and RHS are sequenced. They are both unsequenced
9168 // with respect to other stuff.
9169 Tree.merge(LHS);
9170 Tree.merge(RHS);
9171 }
9172
9173 void VisitBinAssign(BinaryOperator *BO) {
9174 // The modification is sequenced after the value computation of the LHS
9175 // and RHS, so check it before inspecting the operands and update the
9176 // map afterwards.
9177 Object O = getObject(BO->getLHS(), true);
9178 if (!O)
9179 return VisitExpr(BO);
9180
9181 notePreMod(O, BO);
9182
9183 // C++11 [expr.ass]p7:
9184 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
9185 // only once.
9186 //
9187 // Therefore, for a compound assignment operator, O is considered used
9188 // everywhere except within the evaluation of E1 itself.
9189 if (isa<CompoundAssignOperator>(BO))
9190 notePreUse(O, BO);
9191
9192 Visit(BO->getLHS());
9193
9194 if (isa<CompoundAssignOperator>(BO))
9195 notePostUse(O, BO);
9196
9197 Visit(BO->getRHS());
9198
Richard Smith83e37bee2013-06-26 23:16:51 +00009199 // C++11 [expr.ass]p1:
9200 // the assignment is sequenced [...] before the value computation of the
9201 // assignment expression.
9202 // C11 6.5.16/3 has no such rule.
9203 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
9204 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00009205 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009206
Richard Smithc406cb72013-01-17 01:17:56 +00009207 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
9208 VisitBinAssign(CAO);
9209 }
9210
9211 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
9212 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
9213 void VisitUnaryPreIncDec(UnaryOperator *UO) {
9214 Object O = getObject(UO->getSubExpr(), true);
9215 if (!O)
9216 return VisitExpr(UO);
9217
9218 notePreMod(O, UO);
9219 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00009220 // C++11 [expr.pre.incr]p1:
9221 // the expression ++x is equivalent to x+=1
9222 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
9223 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00009224 }
9225
9226 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
9227 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
9228 void VisitUnaryPostIncDec(UnaryOperator *UO) {
9229 Object O = getObject(UO->getSubExpr(), true);
9230 if (!O)
9231 return VisitExpr(UO);
9232
9233 notePreMod(O, UO);
9234 Visit(UO->getSubExpr());
9235 notePostMod(O, UO, UK_ModAsSideEffect);
9236 }
9237
9238 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
9239 void VisitBinLOr(BinaryOperator *BO) {
9240 // The side-effects of the LHS of an '&&' are sequenced before the
9241 // value computation of the RHS, and hence before the value computation
9242 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
9243 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00009244 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00009245 {
9246 SequencedSubexpression Sequenced(*this);
9247 Visit(BO->getLHS());
9248 }
9249
9250 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00009251 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00009252 if (!Result)
9253 Visit(BO->getRHS());
9254 } else {
9255 // Check for unsequenced operations in the RHS, treating it as an
9256 // entirely separate evaluation.
9257 //
9258 // FIXME: If there are operations in the RHS which are unsequenced
9259 // with respect to operations outside the RHS, and those operations
9260 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00009261 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00009262 }
Richard Smithc406cb72013-01-17 01:17:56 +00009263 }
9264 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00009265 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00009266 {
9267 SequencedSubexpression Sequenced(*this);
9268 Visit(BO->getLHS());
9269 }
9270
9271 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00009272 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00009273 if (Result)
9274 Visit(BO->getRHS());
9275 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00009276 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00009277 }
Richard Smithc406cb72013-01-17 01:17:56 +00009278 }
9279
9280 // Only visit the condition, unless we can be sure which subexpression will
9281 // be chosen.
9282 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00009283 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00009284 {
9285 SequencedSubexpression Sequenced(*this);
9286 Visit(CO->getCond());
9287 }
Richard Smithc406cb72013-01-17 01:17:56 +00009288
9289 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00009290 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00009291 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00009292 else {
Richard Smithd33f5202013-01-17 23:18:09 +00009293 WorkList.push_back(CO->getTrueExpr());
9294 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00009295 }
Richard Smithc406cb72013-01-17 01:17:56 +00009296 }
9297
Richard Smithe3dbfe02013-06-30 10:40:20 +00009298 void VisitCallExpr(CallExpr *CE) {
9299 // C++11 [intro.execution]p15:
9300 // When calling a function [...], every value computation and side effect
9301 // associated with any argument expression, or with the postfix expression
9302 // designating the called function, is sequenced before execution of every
9303 // expression or statement in the body of the function [and thus before
9304 // the value computation of its result].
9305 SequencedSubexpression Sequenced(*this);
9306 Base::VisitCallExpr(CE);
9307
9308 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
9309 }
9310
Richard Smithc406cb72013-01-17 01:17:56 +00009311 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00009312 // This is a call, so all subexpressions are sequenced before the result.
9313 SequencedSubexpression Sequenced(*this);
9314
Richard Smithc406cb72013-01-17 01:17:56 +00009315 if (!CCE->isListInitialization())
9316 return VisitExpr(CCE);
9317
9318 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009319 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00009320 SequenceTree::Seq Parent = Region;
9321 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
9322 E = CCE->arg_end();
9323 I != E; ++I) {
9324 Region = Tree.allocate(Parent);
9325 Elts.push_back(Region);
9326 Visit(*I);
9327 }
9328
9329 // Forget that the initializers are sequenced.
9330 Region = Parent;
9331 for (unsigned I = 0; I < Elts.size(); ++I)
9332 Tree.merge(Elts[I]);
9333 }
9334
9335 void VisitInitListExpr(InitListExpr *ILE) {
9336 if (!SemaRef.getLangOpts().CPlusPlus11)
9337 return VisitExpr(ILE);
9338
9339 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009340 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00009341 SequenceTree::Seq Parent = Region;
9342 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
9343 Expr *E = ILE->getInit(I);
9344 if (!E) continue;
9345 Region = Tree.allocate(Parent);
9346 Elts.push_back(Region);
9347 Visit(E);
9348 }
9349
9350 // Forget that the initializers are sequenced.
9351 Region = Parent;
9352 for (unsigned I = 0; I < Elts.size(); ++I)
9353 Tree.merge(Elts[I]);
9354 }
9355};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009356} // end anonymous namespace
Richard Smithc406cb72013-01-17 01:17:56 +00009357
9358void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009359 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00009360 WorkList.push_back(E);
9361 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00009362 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00009363 SequenceChecker(*this, Item, WorkList);
9364 }
Richard Smithc406cb72013-01-17 01:17:56 +00009365}
9366
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009367void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
9368 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00009369 CheckImplicitConversions(E, CheckLoc);
9370 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009371 if (!IsConstexpr && !E->isValueDependent())
9372 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00009373}
9374
John McCall1f425642010-11-11 03:21:53 +00009375void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
9376 FieldDecl *BitField,
9377 Expr *Init) {
9378 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
9379}
9380
David Majnemer61a5bbf2015-04-07 22:08:51 +00009381static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
9382 SourceLocation Loc) {
9383 if (!PType->isVariablyModifiedType())
9384 return;
9385 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
9386 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
9387 return;
9388 }
David Majnemerdf8f73f2015-04-09 19:53:25 +00009389 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
9390 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
9391 return;
9392 }
David Majnemer61a5bbf2015-04-07 22:08:51 +00009393 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
9394 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
9395 return;
9396 }
9397
9398 const ArrayType *AT = S.Context.getAsArrayType(PType);
9399 if (!AT)
9400 return;
9401
9402 if (AT->getSizeModifier() != ArrayType::Star) {
9403 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
9404 return;
9405 }
9406
9407 S.Diag(Loc, diag::err_array_star_in_function_definition);
9408}
9409
Mike Stump0c2ec772010-01-21 03:59:47 +00009410/// CheckParmsForFunctionDef - Check that the parameters of the given
9411/// function are appropriate for the definition of a function. This
9412/// takes care of any checks that cannot be performed on the
9413/// declaration itself, e.g., that the types of each of the function
9414/// parameters are complete.
David Majnemer59f77922016-06-24 04:05:48 +00009415bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
Douglas Gregorb524d902010-11-01 18:37:59 +00009416 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00009417 bool HasInvalidParm = false;
David Majnemer59f77922016-06-24 04:05:48 +00009418 for (ParmVarDecl *Param : Parameters) {
Mike Stump0c2ec772010-01-21 03:59:47 +00009419 // C99 6.7.5.3p4: the parameters in a parameter type list in a
9420 // function declarator that is part of a function definition of
9421 // that function shall not have incomplete type.
9422 //
9423 // This is also C++ [dcl.fct]p6.
9424 if (!Param->isInvalidDecl() &&
9425 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00009426 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00009427 Param->setInvalidDecl();
9428 HasInvalidParm = true;
9429 }
9430
9431 // C99 6.9.1p5: If the declarator includes a parameter type list, the
9432 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00009433 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00009434 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00009435 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00009436 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00009437 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00009438
9439 // C99 6.7.5.3p12:
9440 // If the function declarator is not part of a definition of that
9441 // function, parameters may have incomplete type and may use the [*]
9442 // notation in their sequences of declarator specifiers to specify
9443 // variable length array types.
9444 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +00009445 // FIXME: This diagnostic should point the '[*]' if source-location
9446 // information is added for it.
9447 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00009448
9449 // MSVC destroys objects passed by value in the callee. Therefore a
9450 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00009451 // object's destructor. However, we don't perform any direct access check
9452 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00009453 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
9454 .getCXXABI()
9455 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00009456 if (!Param->isInvalidDecl()) {
9457 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
9458 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
9459 if (!ClassDecl->isInvalidDecl() &&
9460 !ClassDecl->hasIrrelevantDestructor() &&
9461 !ClassDecl->isDependentContext()) {
9462 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
9463 MarkFunctionReferenced(Param->getLocation(), Destructor);
9464 DiagnoseUseOfDecl(Destructor, Param->getLocation());
9465 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00009466 }
9467 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00009468 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009469
9470 // Parameters with the pass_object_size attribute only need to be marked
9471 // constant at function definitions. Because we lack information about
9472 // whether we're on a declaration or definition when we're instantiating the
9473 // attribute, we need to check for constness here.
9474 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
9475 if (!Param->getType().isConstQualified())
9476 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
9477 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +00009478 }
9479
9480 return HasInvalidParm;
9481}
John McCall2b5c1b22010-08-12 21:44:57 +00009482
9483/// CheckCastAlign - Implements -Wcast-align, which warns when a
9484/// pointer cast increases the alignment requirements.
9485void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
9486 // This is actually a lot of work to potentially be doing on every
9487 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009488 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00009489 return;
9490
9491 // Ignore dependent types.
9492 if (T->isDependentType() || Op->getType()->isDependentType())
9493 return;
9494
9495 // Require that the destination be a pointer type.
9496 const PointerType *DestPtr = T->getAs<PointerType>();
9497 if (!DestPtr) return;
9498
9499 // If the destination has alignment 1, we're done.
9500 QualType DestPointee = DestPtr->getPointeeType();
9501 if (DestPointee->isIncompleteType()) return;
9502 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
9503 if (DestAlign.isOne()) return;
9504
9505 // Require that the source be a pointer type.
9506 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
9507 if (!SrcPtr) return;
9508 QualType SrcPointee = SrcPtr->getPointeeType();
9509
9510 // Whitelist casts from cv void*. We already implicitly
9511 // whitelisted casts to cv void*, since they have alignment 1.
9512 // Also whitelist casts involving incomplete types, which implicitly
9513 // includes 'void'.
9514 if (SrcPointee->isIncompleteType()) return;
9515
9516 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
9517 if (SrcAlign >= DestAlign) return;
9518
9519 Diag(TRange.getBegin(), diag::warn_cast_align)
9520 << Op->getType() << T
9521 << static_cast<unsigned>(SrcAlign.getQuantity())
9522 << static_cast<unsigned>(DestAlign.getQuantity())
9523 << TRange << Op->getSourceRange();
9524}
9525
Chandler Carruth28389f02011-08-05 09:10:50 +00009526/// \brief Check whether this array fits the idiom of a size-one tail padded
9527/// array member of a struct.
9528///
9529/// We avoid emitting out-of-bounds access warnings for such arrays as they are
9530/// commonly used to emulate flexible arrays in C89 code.
Benjamin Kramer7320b992016-06-15 14:20:56 +00009531static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
Chandler Carruth28389f02011-08-05 09:10:50 +00009532 const NamedDecl *ND) {
9533 if (Size != 1 || !ND) return false;
9534
9535 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
9536 if (!FD) return false;
9537
9538 // Don't consider sizes resulting from macro expansions or template argument
9539 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00009540
9541 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00009542 while (TInfo) {
9543 TypeLoc TL = TInfo->getTypeLoc();
9544 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00009545 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
9546 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00009547 TInfo = TDL->getTypeSourceInfo();
9548 continue;
9549 }
David Blaikie6adc78e2013-02-18 22:06:02 +00009550 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
9551 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00009552 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
9553 return false;
9554 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00009555 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00009556 }
Chandler Carruth28389f02011-08-05 09:10:50 +00009557
9558 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00009559 if (!RD) return false;
9560 if (RD->isUnion()) return false;
9561 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
9562 if (!CRD->isStandardLayout()) return false;
9563 }
Chandler Carruth28389f02011-08-05 09:10:50 +00009564
Benjamin Kramer8c543672011-08-06 03:04:42 +00009565 // See if this is the last field decl in the record.
9566 const Decl *D = FD;
9567 while ((D = D->getNextDeclInContext()))
9568 if (isa<FieldDecl>(D))
9569 return false;
9570 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00009571}
9572
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009573void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009574 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00009575 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009576 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009577 if (IndexExpr->isValueDependent())
9578 return;
9579
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009580 const Type *EffectiveType =
9581 BaseExpr->getType()->getPointeeOrArrayElementType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009582 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009583 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009584 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009585 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00009586 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00009587
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009588 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +00009589 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +00009590 return;
Richard Smith13f67182011-12-16 19:31:14 +00009591 if (IndexNegated)
9592 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00009593
Craig Topperc3ec1492014-05-26 06:22:03 +00009594 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00009595 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
9596 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00009597 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00009598 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00009599
Ted Kremeneke4b316c2011-02-23 23:06:04 +00009600 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00009601 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00009602 if (!size.isStrictlyPositive())
9603 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009604
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009605 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
Nico Weber7c299802011-09-17 22:59:41 +00009606 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009607 // Make sure we're comparing apples to apples when comparing index to size
9608 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
9609 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00009610 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00009611 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009612 if (ptrarith_typesize != array_typesize) {
9613 // There's a cast to a different size type involved
9614 uint64_t ratio = array_typesize / ptrarith_typesize;
9615 // TODO: Be smarter about handling cases where array_typesize is not a
9616 // multiple of ptrarith_typesize
9617 if (ptrarith_typesize * ratio == array_typesize)
9618 size *= llvm::APInt(size.getBitWidth(), ratio);
9619 }
9620 }
9621
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009622 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009623 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00009624 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009625 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00009626
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009627 // For array subscripting the index must be less than size, but for pointer
9628 // arithmetic also allow the index (offset) to be equal to size since
9629 // computing the next address after the end of the array is legal and
9630 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00009631 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00009632 return;
9633
9634 // Also don't warn for arrays of size 1 which are members of some
9635 // structure. These are often used to approximate flexible arrays in C89
9636 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009637 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00009638 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009639
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009640 // Suppress the warning if the subscript expression (as identified by the
9641 // ']' location) and the index expression are both from macro expansions
9642 // within a system header.
9643 if (ASE) {
9644 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
9645 ASE->getRBracketLoc());
9646 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
9647 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
9648 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00009649 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009650 return;
9651 }
9652 }
9653
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009654 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009655 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009656 DiagID = diag::warn_array_index_exceeds_bounds;
9657
9658 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
9659 PDiag(DiagID) << index.toString(10, true)
9660 << size.toString(10, true)
9661 << (unsigned)size.getLimitedValue(~0U)
9662 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00009663 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009664 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009665 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009666 DiagID = diag::warn_ptr_arith_precedes_bounds;
9667 if (index.isNegative()) index = -index;
9668 }
9669
9670 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
9671 PDiag(DiagID) << index.toString(10, true)
9672 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00009673 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00009674
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00009675 if (!ND) {
9676 // Try harder to find a NamedDecl to point at in the note.
9677 while (const ArraySubscriptExpr *ASE =
9678 dyn_cast<ArraySubscriptExpr>(BaseExpr))
9679 BaseExpr = ASE->getBase()->IgnoreParenCasts();
9680 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
9681 ND = dyn_cast<NamedDecl>(DRE->getDecl());
9682 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
9683 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
9684 }
9685
Chandler Carruth1af88f12011-02-17 21:10:52 +00009686 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009687 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
9688 PDiag(diag::note_array_index_out_of_bounds)
9689 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00009690}
9691
Ted Kremenekdf26df72011-03-01 18:41:00 +00009692void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009693 int AllowOnePastEnd = 0;
9694 while (expr) {
9695 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00009696 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009697 case Stmt::ArraySubscriptExprClass: {
9698 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009699 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009700 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00009701 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009702 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +00009703 case Stmt::OMPArraySectionExprClass: {
9704 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
9705 if (ASE->getLowerBound())
9706 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
9707 /*ASE=*/nullptr, AllowOnePastEnd > 0);
9708 return;
9709 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009710 case Stmt::UnaryOperatorClass: {
9711 // Only unwrap the * and & unary operators
9712 const UnaryOperator *UO = cast<UnaryOperator>(expr);
9713 expr = UO->getSubExpr();
9714 switch (UO->getOpcode()) {
9715 case UO_AddrOf:
9716 AllowOnePastEnd++;
9717 break;
9718 case UO_Deref:
9719 AllowOnePastEnd--;
9720 break;
9721 default:
9722 return;
9723 }
9724 break;
9725 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00009726 case Stmt::ConditionalOperatorClass: {
9727 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
9728 if (const Expr *lhs = cond->getLHS())
9729 CheckArrayAccess(lhs);
9730 if (const Expr *rhs = cond->getRHS())
9731 CheckArrayAccess(rhs);
9732 return;
9733 }
9734 default:
9735 return;
9736 }
Peter Collingbourne91147592011-04-15 00:35:48 +00009737 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00009738}
John McCall31168b02011-06-15 23:02:42 +00009739
9740//===--- CHECK: Objective-C retain cycles ----------------------------------//
9741
9742namespace {
9743 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00009744 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00009745 VarDecl *Variable;
9746 SourceRange Range;
9747 SourceLocation Loc;
9748 bool Indirect;
9749
9750 void setLocsFrom(Expr *e) {
9751 Loc = e->getExprLoc();
9752 Range = e->getSourceRange();
9753 }
9754 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009755} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +00009756
9757/// Consider whether capturing the given variable can possibly lead to
9758/// a retain cycle.
9759static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00009760 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00009761 // lifetime. In MRR, it's captured strongly if the variable is
9762 // __block and has an appropriate type.
9763 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
9764 return false;
9765
9766 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009767 if (ref)
9768 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00009769 return true;
9770}
9771
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009772static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00009773 while (true) {
9774 e = e->IgnoreParens();
9775 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
9776 switch (cast->getCastKind()) {
9777 case CK_BitCast:
9778 case CK_LValueBitCast:
9779 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00009780 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00009781 e = cast->getSubExpr();
9782 continue;
9783
John McCall31168b02011-06-15 23:02:42 +00009784 default:
9785 return false;
9786 }
9787 }
9788
9789 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
9790 ObjCIvarDecl *ivar = ref->getDecl();
9791 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
9792 return false;
9793
9794 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009795 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00009796 return false;
9797
9798 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
9799 owner.Indirect = true;
9800 return true;
9801 }
9802
9803 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
9804 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
9805 if (!var) return false;
9806 return considerVariable(var, ref, owner);
9807 }
9808
John McCall31168b02011-06-15 23:02:42 +00009809 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
9810 if (member->isArrow()) return false;
9811
9812 // Don't count this as an indirect ownership.
9813 e = member->getBase();
9814 continue;
9815 }
9816
John McCallfe96e0b2011-11-06 09:01:30 +00009817 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
9818 // Only pay attention to pseudo-objects on property references.
9819 ObjCPropertyRefExpr *pre
9820 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
9821 ->IgnoreParens());
9822 if (!pre) return false;
9823 if (pre->isImplicitProperty()) return false;
9824 ObjCPropertyDecl *property = pre->getExplicitProperty();
9825 if (!property->isRetaining() &&
9826 !(property->getPropertyIvarDecl() &&
9827 property->getPropertyIvarDecl()->getType()
9828 .getObjCLifetime() == Qualifiers::OCL_Strong))
9829 return false;
9830
9831 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009832 if (pre->isSuperReceiver()) {
9833 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
9834 if (!owner.Variable)
9835 return false;
9836 owner.Loc = pre->getLocation();
9837 owner.Range = pre->getSourceRange();
9838 return true;
9839 }
John McCallfe96e0b2011-11-06 09:01:30 +00009840 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
9841 ->getSourceExpr());
9842 continue;
9843 }
9844
John McCall31168b02011-06-15 23:02:42 +00009845 // Array ivars?
9846
9847 return false;
9848 }
9849}
9850
9851namespace {
9852 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
9853 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
9854 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009855 Context(Context), Variable(variable), Capturer(nullptr),
9856 VarWillBeReased(false) {}
9857 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +00009858 VarDecl *Variable;
9859 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009860 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +00009861
9862 void VisitDeclRefExpr(DeclRefExpr *ref) {
9863 if (ref->getDecl() == Variable && !Capturer)
9864 Capturer = ref;
9865 }
9866
John McCall31168b02011-06-15 23:02:42 +00009867 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
9868 if (Capturer) return;
9869 Visit(ref->getBase());
9870 if (Capturer && ref->isFreeIvar())
9871 Capturer = ref;
9872 }
9873
9874 void VisitBlockExpr(BlockExpr *block) {
9875 // Look inside nested blocks
9876 if (block->getBlockDecl()->capturesVariable(Variable))
9877 Visit(block->getBlockDecl()->getBody());
9878 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00009879
9880 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
9881 if (Capturer) return;
9882 if (OVE->getSourceExpr())
9883 Visit(OVE->getSourceExpr());
9884 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009885 void VisitBinaryOperator(BinaryOperator *BinOp) {
9886 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
9887 return;
9888 Expr *LHS = BinOp->getLHS();
9889 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
9890 if (DRE->getDecl() != Variable)
9891 return;
9892 if (Expr *RHS = BinOp->getRHS()) {
9893 RHS = RHS->IgnoreParenCasts();
9894 llvm::APSInt Value;
9895 VarWillBeReased =
9896 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
9897 }
9898 }
9899 }
John McCall31168b02011-06-15 23:02:42 +00009900 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009901} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +00009902
9903/// Check whether the given argument is a block which captures a
9904/// variable.
9905static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
9906 assert(owner.Variable && owner.Loc.isValid());
9907
9908 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00009909
9910 // Look through [^{...} copy] and Block_copy(^{...}).
9911 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
9912 Selector Cmd = ME->getSelector();
9913 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
9914 e = ME->getInstanceReceiver();
9915 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +00009916 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +00009917 e = e->IgnoreParenCasts();
9918 }
9919 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
9920 if (CE->getNumArgs() == 1) {
9921 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00009922 if (Fn) {
9923 const IdentifierInfo *FnI = Fn->getIdentifier();
9924 if (FnI && FnI->isStr("_Block_copy")) {
9925 e = CE->getArg(0)->IgnoreParenCasts();
9926 }
9927 }
Jordan Rose67e887c2012-09-17 17:54:30 +00009928 }
9929 }
9930
John McCall31168b02011-06-15 23:02:42 +00009931 BlockExpr *block = dyn_cast<BlockExpr>(e);
9932 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +00009933 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00009934
9935 FindCaptureVisitor visitor(S.Context, owner.Variable);
9936 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009937 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +00009938}
9939
9940static void diagnoseRetainCycle(Sema &S, Expr *capturer,
9941 RetainCycleOwner &owner) {
9942 assert(capturer);
9943 assert(owner.Variable && owner.Loc.isValid());
9944
9945 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
9946 << owner.Variable << capturer->getSourceRange();
9947 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
9948 << owner.Indirect << owner.Range;
9949}
9950
9951/// Check for a keyword selector that starts with the word 'add' or
9952/// 'set'.
9953static bool isSetterLikeSelector(Selector sel) {
9954 if (sel.isUnarySelector()) return false;
9955
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009956 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00009957 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00009958 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00009959 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00009960 else if (str.startswith("add")) {
9961 // Specially whitelist 'addOperationWithBlock:'.
9962 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
9963 return false;
9964 str = str.substr(3);
9965 }
John McCall31168b02011-06-15 23:02:42 +00009966 else
9967 return false;
9968
9969 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00009970 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00009971}
9972
Benjamin Kramer3a743452015-03-09 15:03:32 +00009973static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
9974 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009975 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
9976 Message->getReceiverInterface(),
9977 NSAPI::ClassId_NSMutableArray);
9978 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009979 return None;
9980 }
9981
9982 Selector Sel = Message->getSelector();
9983
9984 Optional<NSAPI::NSArrayMethodKind> MKOpt =
9985 S.NSAPIObj->getNSArrayMethodKind(Sel);
9986 if (!MKOpt) {
9987 return None;
9988 }
9989
9990 NSAPI::NSArrayMethodKind MK = *MKOpt;
9991
9992 switch (MK) {
9993 case NSAPI::NSMutableArr_addObject:
9994 case NSAPI::NSMutableArr_insertObjectAtIndex:
9995 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
9996 return 0;
9997 case NSAPI::NSMutableArr_replaceObjectAtIndex:
9998 return 1;
9999
10000 default:
10001 return None;
10002 }
10003
10004 return None;
10005}
10006
10007static
10008Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
10009 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010010 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
10011 Message->getReceiverInterface(),
10012 NSAPI::ClassId_NSMutableDictionary);
10013 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010014 return None;
10015 }
10016
10017 Selector Sel = Message->getSelector();
10018
10019 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
10020 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
10021 if (!MKOpt) {
10022 return None;
10023 }
10024
10025 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
10026
10027 switch (MK) {
10028 case NSAPI::NSMutableDict_setObjectForKey:
10029 case NSAPI::NSMutableDict_setValueForKey:
10030 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
10031 return 0;
10032
10033 default:
10034 return None;
10035 }
10036
10037 return None;
10038}
10039
10040static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010041 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
10042 Message->getReceiverInterface(),
10043 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +000010044
Alex Denisov5dfac812015-08-06 04:51:14 +000010045 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
10046 Message->getReceiverInterface(),
10047 NSAPI::ClassId_NSMutableOrderedSet);
10048 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010049 return None;
10050 }
10051
10052 Selector Sel = Message->getSelector();
10053
10054 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
10055 if (!MKOpt) {
10056 return None;
10057 }
10058
10059 NSAPI::NSSetMethodKind MK = *MKOpt;
10060
10061 switch (MK) {
10062 case NSAPI::NSMutableSet_addObject:
10063 case NSAPI::NSOrderedSet_setObjectAtIndex:
10064 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
10065 case NSAPI::NSOrderedSet_insertObjectAtIndex:
10066 return 0;
10067 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
10068 return 1;
10069 }
10070
10071 return None;
10072}
10073
10074void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
10075 if (!Message->isInstanceMessage()) {
10076 return;
10077 }
10078
10079 Optional<int> ArgOpt;
10080
10081 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
10082 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
10083 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
10084 return;
10085 }
10086
10087 int ArgIndex = *ArgOpt;
10088
Alex Denisove1d882c2015-03-04 17:55:52 +000010089 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
10090 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
10091 Arg = OE->getSourceExpr()->IgnoreImpCasts();
10092 }
10093
Alex Denisov5dfac812015-08-06 04:51:14 +000010094 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010095 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010096 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010097 Diag(Message->getSourceRange().getBegin(),
10098 diag::warn_objc_circular_container)
Alex Denisov5dfac812015-08-06 04:51:14 +000010099 << ArgRE->getDecl()->getName() << StringRef("super");
Alex Denisove1d882c2015-03-04 17:55:52 +000010100 }
10101 }
Alex Denisov5dfac812015-08-06 04:51:14 +000010102 } else {
10103 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
10104
10105 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
10106 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
10107 }
10108
10109 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
10110 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
10111 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
10112 ValueDecl *Decl = ReceiverRE->getDecl();
10113 Diag(Message->getSourceRange().getBegin(),
10114 diag::warn_objc_circular_container)
10115 << Decl->getName() << Decl->getName();
10116 if (!ArgRE->isObjCSelfExpr()) {
10117 Diag(Decl->getLocation(),
10118 diag::note_objc_circular_container_declared_here)
10119 << Decl->getName();
10120 }
10121 }
10122 }
10123 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
10124 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
10125 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
10126 ObjCIvarDecl *Decl = IvarRE->getDecl();
10127 Diag(Message->getSourceRange().getBegin(),
10128 diag::warn_objc_circular_container)
10129 << Decl->getName() << Decl->getName();
10130 Diag(Decl->getLocation(),
10131 diag::note_objc_circular_container_declared_here)
10132 << Decl->getName();
10133 }
Alex Denisove1d882c2015-03-04 17:55:52 +000010134 }
10135 }
10136 }
Alex Denisove1d882c2015-03-04 17:55:52 +000010137}
10138
John McCall31168b02011-06-15 23:02:42 +000010139/// Check a message send to see if it's likely to cause a retain cycle.
10140void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
10141 // Only check instance methods whose selector looks like a setter.
10142 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
10143 return;
10144
10145 // Try to find a variable that the receiver is strongly owned by.
10146 RetainCycleOwner owner;
10147 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010148 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +000010149 return;
10150 } else {
10151 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
10152 owner.Variable = getCurMethodDecl()->getSelfDecl();
10153 owner.Loc = msg->getSuperLoc();
10154 owner.Range = msg->getSuperLoc();
10155 }
10156
10157 // Check whether the receiver is captured by any of the arguments.
10158 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
10159 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
10160 return diagnoseRetainCycle(*this, capturer, owner);
10161}
10162
10163/// Check a property assign to see if it's likely to cause a retain cycle.
10164void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
10165 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010166 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +000010167 return;
10168
10169 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
10170 diagnoseRetainCycle(*this, capturer, owner);
10171}
10172
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000010173void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
10174 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +000010175 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000010176 return;
10177
10178 // Because we don't have an expression for the variable, we have to set the
10179 // location explicitly here.
10180 Owner.Loc = Var->getLocation();
10181 Owner.Range = Var->getSourceRange();
10182
10183 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
10184 diagnoseRetainCycle(*this, Capturer, Owner);
10185}
10186
Ted Kremenek9304da92012-12-21 08:04:28 +000010187static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
10188 Expr *RHS, bool isProperty) {
10189 // Check if RHS is an Objective-C object literal, which also can get
10190 // immediately zapped in a weak reference. Note that we explicitly
10191 // allow ObjCStringLiterals, since those are designed to never really die.
10192 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000010193
Ted Kremenek64873352012-12-21 22:46:35 +000010194 // This enum needs to match with the 'select' in
10195 // warn_objc_arc_literal_assign (off-by-1).
10196 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
10197 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
10198 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000010199
10200 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +000010201 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +000010202 << (isProperty ? 0 : 1)
10203 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000010204
10205 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +000010206}
10207
Ted Kremenekc1f014a2012-12-21 19:45:30 +000010208static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
10209 Qualifiers::ObjCLifetime LT,
10210 Expr *RHS, bool isProperty) {
10211 // Strip off any implicit cast added to get to the one ARC-specific.
10212 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
10213 if (cast->getCastKind() == CK_ARCConsumeObject) {
10214 S.Diag(Loc, diag::warn_arc_retained_assign)
10215 << (LT == Qualifiers::OCL_ExplicitNone)
10216 << (isProperty ? 0 : 1)
10217 << RHS->getSourceRange();
10218 return true;
10219 }
10220 RHS = cast->getSubExpr();
10221 }
10222
10223 if (LT == Qualifiers::OCL_Weak &&
10224 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
10225 return true;
10226
10227 return false;
10228}
10229
Ted Kremenekb36234d2012-12-21 08:04:20 +000010230bool Sema::checkUnsafeAssigns(SourceLocation Loc,
10231 QualType LHS, Expr *RHS) {
10232 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
10233
10234 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
10235 return false;
10236
10237 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
10238 return true;
10239
10240 return false;
10241}
10242
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010243void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
10244 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010245 QualType LHSType;
10246 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +000010247 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010248 ObjCPropertyRefExpr *PRE
10249 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
10250 if (PRE && !PRE->isImplicitProperty()) {
10251 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
10252 if (PD)
10253 LHSType = PD->getType();
10254 }
10255
10256 if (LHSType.isNull())
10257 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +000010258
10259 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
10260
10261 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010262 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +000010263 getCurFunction()->markSafeWeakUse(LHS);
10264 }
10265
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010266 if (checkUnsafeAssigns(Loc, LHSType, RHS))
10267 return;
Jordan Rose657b5f42012-09-28 22:21:35 +000010268
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010269 // FIXME. Check for other life times.
10270 if (LT != Qualifiers::OCL_None)
10271 return;
10272
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010273 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010274 if (PRE->isImplicitProperty())
10275 return;
10276 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
10277 if (!PD)
10278 return;
10279
Bill Wendling44426052012-12-20 19:22:21 +000010280 unsigned Attributes = PD->getPropertyAttributes();
10281 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010282 // when 'assign' attribute was not explicitly specified
10283 // by user, ignore it and rely on property type itself
10284 // for lifetime info.
10285 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
10286 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
10287 LHSType->isObjCRetainableType())
10288 return;
10289
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010290 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +000010291 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010292 Diag(Loc, diag::warn_arc_retained_property_assign)
10293 << RHS->getSourceRange();
10294 return;
10295 }
10296 RHS = cast->getSubExpr();
10297 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010298 }
Bill Wendling44426052012-12-20 19:22:21 +000010299 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +000010300 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
10301 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +000010302 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010303 }
10304}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010305
10306//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
10307
10308namespace {
10309bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
10310 SourceLocation StmtLoc,
10311 const NullStmt *Body) {
10312 // Do not warn if the body is a macro that expands to nothing, e.g:
10313 //
10314 // #define CALL(x)
10315 // if (condition)
10316 // CALL(0);
10317 //
10318 if (Body->hasLeadingEmptyMacro())
10319 return false;
10320
10321 // Get line numbers of statement and body.
10322 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +000010323 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010324 &StmtLineInvalid);
10325 if (StmtLineInvalid)
10326 return false;
10327
10328 bool BodyLineInvalid;
10329 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
10330 &BodyLineInvalid);
10331 if (BodyLineInvalid)
10332 return false;
10333
10334 // Warn if null statement and body are on the same line.
10335 if (StmtLine != BodyLine)
10336 return false;
10337
10338 return true;
10339}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010340} // end anonymous namespace
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010341
10342void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
10343 const Stmt *Body,
10344 unsigned DiagID) {
10345 // Since this is a syntactic check, don't emit diagnostic for template
10346 // instantiations, this just adds noise.
10347 if (CurrentInstantiationScope)
10348 return;
10349
10350 // The body should be a null statement.
10351 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
10352 if (!NBody)
10353 return;
10354
10355 // Do the usual checks.
10356 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
10357 return;
10358
10359 Diag(NBody->getSemiLoc(), DiagID);
10360 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
10361}
10362
10363void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
10364 const Stmt *PossibleBody) {
10365 assert(!CurrentInstantiationScope); // Ensured by caller
10366
10367 SourceLocation StmtLoc;
10368 const Stmt *Body;
10369 unsigned DiagID;
10370 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
10371 StmtLoc = FS->getRParenLoc();
10372 Body = FS->getBody();
10373 DiagID = diag::warn_empty_for_body;
10374 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
10375 StmtLoc = WS->getCond()->getSourceRange().getEnd();
10376 Body = WS->getBody();
10377 DiagID = diag::warn_empty_while_body;
10378 } else
10379 return; // Neither `for' nor `while'.
10380
10381 // The body should be a null statement.
10382 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
10383 if (!NBody)
10384 return;
10385
10386 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010387 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010388 return;
10389
10390 // Do the usual checks.
10391 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
10392 return;
10393
10394 // `for(...);' and `while(...);' are popular idioms, so in order to keep
10395 // noise level low, emit diagnostics only if for/while is followed by a
10396 // CompoundStmt, e.g.:
10397 // for (int i = 0; i < n; i++);
10398 // {
10399 // a(i);
10400 // }
10401 // or if for/while is followed by a statement with more indentation
10402 // than for/while itself:
10403 // for (int i = 0; i < n; i++);
10404 // a(i);
10405 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
10406 if (!ProbableTypo) {
10407 bool BodyColInvalid;
10408 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
10409 PossibleBody->getLocStart(),
10410 &BodyColInvalid);
10411 if (BodyColInvalid)
10412 return;
10413
10414 bool StmtColInvalid;
10415 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
10416 S->getLocStart(),
10417 &StmtColInvalid);
10418 if (StmtColInvalid)
10419 return;
10420
10421 if (BodyCol > StmtCol)
10422 ProbableTypo = true;
10423 }
10424
10425 if (ProbableTypo) {
10426 Diag(NBody->getSemiLoc(), DiagID);
10427 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
10428 }
10429}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010430
Richard Trieu36d0b2b2015-01-13 02:32:02 +000010431//===--- CHECK: Warn on self move with std::move. -------------------------===//
10432
10433/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
10434void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
10435 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +000010436 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
10437 return;
10438
10439 if (!ActiveTemplateInstantiations.empty())
10440 return;
10441
10442 // Strip parens and casts away.
10443 LHSExpr = LHSExpr->IgnoreParenImpCasts();
10444 RHSExpr = RHSExpr->IgnoreParenImpCasts();
10445
10446 // Check for a call expression
10447 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
10448 if (!CE || CE->getNumArgs() != 1)
10449 return;
10450
10451 // Check for a call to std::move
10452 const FunctionDecl *FD = CE->getDirectCallee();
10453 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
10454 !FD->getIdentifier()->isStr("move"))
10455 return;
10456
10457 // Get argument from std::move
10458 RHSExpr = CE->getArg(0);
10459
10460 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
10461 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
10462
10463 // Two DeclRefExpr's, check that the decls are the same.
10464 if (LHSDeclRef && RHSDeclRef) {
10465 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
10466 return;
10467 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
10468 RHSDeclRef->getDecl()->getCanonicalDecl())
10469 return;
10470
10471 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10472 << LHSExpr->getSourceRange()
10473 << RHSExpr->getSourceRange();
10474 return;
10475 }
10476
10477 // Member variables require a different approach to check for self moves.
10478 // MemberExpr's are the same if every nested MemberExpr refers to the same
10479 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
10480 // the base Expr's are CXXThisExpr's.
10481 const Expr *LHSBase = LHSExpr;
10482 const Expr *RHSBase = RHSExpr;
10483 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
10484 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
10485 if (!LHSME || !RHSME)
10486 return;
10487
10488 while (LHSME && RHSME) {
10489 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
10490 RHSME->getMemberDecl()->getCanonicalDecl())
10491 return;
10492
10493 LHSBase = LHSME->getBase();
10494 RHSBase = RHSME->getBase();
10495 LHSME = dyn_cast<MemberExpr>(LHSBase);
10496 RHSME = dyn_cast<MemberExpr>(RHSBase);
10497 }
10498
10499 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
10500 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
10501 if (LHSDeclRef && RHSDeclRef) {
10502 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
10503 return;
10504 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
10505 RHSDeclRef->getDecl()->getCanonicalDecl())
10506 return;
10507
10508 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10509 << LHSExpr->getSourceRange()
10510 << RHSExpr->getSourceRange();
10511 return;
10512 }
10513
10514 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
10515 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10516 << LHSExpr->getSourceRange()
10517 << RHSExpr->getSourceRange();
10518}
10519
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010520//===--- Layout compatibility ----------------------------------------------//
10521
10522namespace {
10523
10524bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
10525
10526/// \brief Check if two enumeration types are layout-compatible.
10527bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
10528 // C++11 [dcl.enum] p8:
10529 // Two enumeration types are layout-compatible if they have the same
10530 // underlying type.
10531 return ED1->isComplete() && ED2->isComplete() &&
10532 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
10533}
10534
10535/// \brief Check if two fields are layout-compatible.
10536bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
10537 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
10538 return false;
10539
10540 if (Field1->isBitField() != Field2->isBitField())
10541 return false;
10542
10543 if (Field1->isBitField()) {
10544 // Make sure that the bit-fields are the same length.
10545 unsigned Bits1 = Field1->getBitWidthValue(C);
10546 unsigned Bits2 = Field2->getBitWidthValue(C);
10547
10548 if (Bits1 != Bits2)
10549 return false;
10550 }
10551
10552 return true;
10553}
10554
10555/// \brief Check if two standard-layout structs are layout-compatible.
10556/// (C++11 [class.mem] p17)
10557bool isLayoutCompatibleStruct(ASTContext &C,
10558 RecordDecl *RD1,
10559 RecordDecl *RD2) {
10560 // If both records are C++ classes, check that base classes match.
10561 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
10562 // If one of records is a CXXRecordDecl we are in C++ mode,
10563 // thus the other one is a CXXRecordDecl, too.
10564 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
10565 // Check number of base classes.
10566 if (D1CXX->getNumBases() != D2CXX->getNumBases())
10567 return false;
10568
10569 // Check the base classes.
10570 for (CXXRecordDecl::base_class_const_iterator
10571 Base1 = D1CXX->bases_begin(),
10572 BaseEnd1 = D1CXX->bases_end(),
10573 Base2 = D2CXX->bases_begin();
10574 Base1 != BaseEnd1;
10575 ++Base1, ++Base2) {
10576 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
10577 return false;
10578 }
10579 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
10580 // If only RD2 is a C++ class, it should have zero base classes.
10581 if (D2CXX->getNumBases() > 0)
10582 return false;
10583 }
10584
10585 // Check the fields.
10586 RecordDecl::field_iterator Field2 = RD2->field_begin(),
10587 Field2End = RD2->field_end(),
10588 Field1 = RD1->field_begin(),
10589 Field1End = RD1->field_end();
10590 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
10591 if (!isLayoutCompatible(C, *Field1, *Field2))
10592 return false;
10593 }
10594 if (Field1 != Field1End || Field2 != Field2End)
10595 return false;
10596
10597 return true;
10598}
10599
10600/// \brief Check if two standard-layout unions are layout-compatible.
10601/// (C++11 [class.mem] p18)
10602bool isLayoutCompatibleUnion(ASTContext &C,
10603 RecordDecl *RD1,
10604 RecordDecl *RD2) {
10605 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010606 for (auto *Field2 : RD2->fields())
10607 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010608
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010609 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010610 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
10611 I = UnmatchedFields.begin(),
10612 E = UnmatchedFields.end();
10613
10614 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010615 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010616 bool Result = UnmatchedFields.erase(*I);
10617 (void) Result;
10618 assert(Result);
10619 break;
10620 }
10621 }
10622 if (I == E)
10623 return false;
10624 }
10625
10626 return UnmatchedFields.empty();
10627}
10628
10629bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
10630 if (RD1->isUnion() != RD2->isUnion())
10631 return false;
10632
10633 if (RD1->isUnion())
10634 return isLayoutCompatibleUnion(C, RD1, RD2);
10635 else
10636 return isLayoutCompatibleStruct(C, RD1, RD2);
10637}
10638
10639/// \brief Check if two types are layout-compatible in C++11 sense.
10640bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
10641 if (T1.isNull() || T2.isNull())
10642 return false;
10643
10644 // C++11 [basic.types] p11:
10645 // If two types T1 and T2 are the same type, then T1 and T2 are
10646 // layout-compatible types.
10647 if (C.hasSameType(T1, T2))
10648 return true;
10649
10650 T1 = T1.getCanonicalType().getUnqualifiedType();
10651 T2 = T2.getCanonicalType().getUnqualifiedType();
10652
10653 const Type::TypeClass TC1 = T1->getTypeClass();
10654 const Type::TypeClass TC2 = T2->getTypeClass();
10655
10656 if (TC1 != TC2)
10657 return false;
10658
10659 if (TC1 == Type::Enum) {
10660 return isLayoutCompatible(C,
10661 cast<EnumType>(T1)->getDecl(),
10662 cast<EnumType>(T2)->getDecl());
10663 } else if (TC1 == Type::Record) {
10664 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
10665 return false;
10666
10667 return isLayoutCompatible(C,
10668 cast<RecordType>(T1)->getDecl(),
10669 cast<RecordType>(T2)->getDecl());
10670 }
10671
10672 return false;
10673}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010674} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010675
10676//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
10677
10678namespace {
10679/// \brief Given a type tag expression find the type tag itself.
10680///
10681/// \param TypeExpr Type tag expression, as it appears in user's code.
10682///
10683/// \param VD Declaration of an identifier that appears in a type tag.
10684///
10685/// \param MagicValue Type tag magic value.
10686bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
10687 const ValueDecl **VD, uint64_t *MagicValue) {
10688 while(true) {
10689 if (!TypeExpr)
10690 return false;
10691
10692 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
10693
10694 switch (TypeExpr->getStmtClass()) {
10695 case Stmt::UnaryOperatorClass: {
10696 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
10697 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
10698 TypeExpr = UO->getSubExpr();
10699 continue;
10700 }
10701 return false;
10702 }
10703
10704 case Stmt::DeclRefExprClass: {
10705 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
10706 *VD = DRE->getDecl();
10707 return true;
10708 }
10709
10710 case Stmt::IntegerLiteralClass: {
10711 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
10712 llvm::APInt MagicValueAPInt = IL->getValue();
10713 if (MagicValueAPInt.getActiveBits() <= 64) {
10714 *MagicValue = MagicValueAPInt.getZExtValue();
10715 return true;
10716 } else
10717 return false;
10718 }
10719
10720 case Stmt::BinaryConditionalOperatorClass:
10721 case Stmt::ConditionalOperatorClass: {
10722 const AbstractConditionalOperator *ACO =
10723 cast<AbstractConditionalOperator>(TypeExpr);
10724 bool Result;
10725 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
10726 if (Result)
10727 TypeExpr = ACO->getTrueExpr();
10728 else
10729 TypeExpr = ACO->getFalseExpr();
10730 continue;
10731 }
10732 return false;
10733 }
10734
10735 case Stmt::BinaryOperatorClass: {
10736 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
10737 if (BO->getOpcode() == BO_Comma) {
10738 TypeExpr = BO->getRHS();
10739 continue;
10740 }
10741 return false;
10742 }
10743
10744 default:
10745 return false;
10746 }
10747 }
10748}
10749
10750/// \brief Retrieve the C type corresponding to type tag TypeExpr.
10751///
10752/// \param TypeExpr Expression that specifies a type tag.
10753///
10754/// \param MagicValues Registered magic values.
10755///
10756/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
10757/// kind.
10758///
10759/// \param TypeInfo Information about the corresponding C type.
10760///
10761/// \returns true if the corresponding C type was found.
10762bool GetMatchingCType(
10763 const IdentifierInfo *ArgumentKind,
10764 const Expr *TypeExpr, const ASTContext &Ctx,
10765 const llvm::DenseMap<Sema::TypeTagMagicValue,
10766 Sema::TypeTagData> *MagicValues,
10767 bool &FoundWrongKind,
10768 Sema::TypeTagData &TypeInfo) {
10769 FoundWrongKind = false;
10770
10771 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000010772 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010773
10774 uint64_t MagicValue;
10775
10776 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
10777 return false;
10778
10779 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000010780 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010781 if (I->getArgumentKind() != ArgumentKind) {
10782 FoundWrongKind = true;
10783 return false;
10784 }
10785 TypeInfo.Type = I->getMatchingCType();
10786 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
10787 TypeInfo.MustBeNull = I->getMustBeNull();
10788 return true;
10789 }
10790 return false;
10791 }
10792
10793 if (!MagicValues)
10794 return false;
10795
10796 llvm::DenseMap<Sema::TypeTagMagicValue,
10797 Sema::TypeTagData>::const_iterator I =
10798 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
10799 if (I == MagicValues->end())
10800 return false;
10801
10802 TypeInfo = I->second;
10803 return true;
10804}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010805} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010806
10807void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
10808 uint64_t MagicValue, QualType Type,
10809 bool LayoutCompatible,
10810 bool MustBeNull) {
10811 if (!TypeTagForDatatypeMagicValues)
10812 TypeTagForDatatypeMagicValues.reset(
10813 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
10814
10815 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
10816 (*TypeTagForDatatypeMagicValues)[Magic] =
10817 TypeTagData(Type, LayoutCompatible, MustBeNull);
10818}
10819
10820namespace {
10821bool IsSameCharType(QualType T1, QualType T2) {
10822 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
10823 if (!BT1)
10824 return false;
10825
10826 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
10827 if (!BT2)
10828 return false;
10829
10830 BuiltinType::Kind T1Kind = BT1->getKind();
10831 BuiltinType::Kind T2Kind = BT2->getKind();
10832
10833 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
10834 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
10835 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
10836 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
10837}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010838} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010839
10840void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
10841 const Expr * const *ExprArgs) {
10842 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
10843 bool IsPointerAttr = Attr->getIsPointer();
10844
10845 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
10846 bool FoundWrongKind;
10847 TypeTagData TypeInfo;
10848 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
10849 TypeTagForDatatypeMagicValues.get(),
10850 FoundWrongKind, TypeInfo)) {
10851 if (FoundWrongKind)
10852 Diag(TypeTagExpr->getExprLoc(),
10853 diag::warn_type_tag_for_datatype_wrong_kind)
10854 << TypeTagExpr->getSourceRange();
10855 return;
10856 }
10857
10858 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
10859 if (IsPointerAttr) {
10860 // Skip implicit cast of pointer to `void *' (as a function argument).
10861 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000010862 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000010863 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010864 ArgumentExpr = ICE->getSubExpr();
10865 }
10866 QualType ArgumentType = ArgumentExpr->getType();
10867
10868 // Passing a `void*' pointer shouldn't trigger a warning.
10869 if (IsPointerAttr && ArgumentType->isVoidPointerType())
10870 return;
10871
10872 if (TypeInfo.MustBeNull) {
10873 // Type tag with matching void type requires a null pointer.
10874 if (!ArgumentExpr->isNullPointerConstant(Context,
10875 Expr::NPC_ValueDependentIsNotNull)) {
10876 Diag(ArgumentExpr->getExprLoc(),
10877 diag::warn_type_safety_null_pointer_required)
10878 << ArgumentKind->getName()
10879 << ArgumentExpr->getSourceRange()
10880 << TypeTagExpr->getSourceRange();
10881 }
10882 return;
10883 }
10884
10885 QualType RequiredType = TypeInfo.Type;
10886 if (IsPointerAttr)
10887 RequiredType = Context.getPointerType(RequiredType);
10888
10889 bool mismatch = false;
10890 if (!TypeInfo.LayoutCompatible) {
10891 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
10892
10893 // C++11 [basic.fundamental] p1:
10894 // Plain char, signed char, and unsigned char are three distinct types.
10895 //
10896 // But we treat plain `char' as equivalent to `signed char' or `unsigned
10897 // char' depending on the current char signedness mode.
10898 if (mismatch)
10899 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
10900 RequiredType->getPointeeType())) ||
10901 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
10902 mismatch = false;
10903 } else
10904 if (IsPointerAttr)
10905 mismatch = !isLayoutCompatible(Context,
10906 ArgumentType->getPointeeType(),
10907 RequiredType->getPointeeType());
10908 else
10909 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
10910
10911 if (mismatch)
10912 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000010913 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010914 << TypeInfo.LayoutCompatible << RequiredType
10915 << ArgumentExpr->getSourceRange()
10916 << TypeTagExpr->getSourceRange();
10917}