blob: 14a1e5b86a9235d3d698e0465437bd79a249ec02 [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();
Alexey Baderaf17c792016-09-07 10:32:03 +00001023 TheCall->setType(Context.IntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001024 break;
1025 case Builtin::BIreserve_read_pipe:
1026 case Builtin::BIreserve_write_pipe:
1027 case Builtin::BIwork_group_reserve_read_pipe:
1028 case Builtin::BIwork_group_reserve_write_pipe:
1029 case Builtin::BIsub_group_reserve_read_pipe:
1030 case Builtin::BIsub_group_reserve_write_pipe:
1031 if (SemaBuiltinReserveRWPipe(*this, TheCall))
1032 return ExprError();
1033 // Since return type of reserve_read/write_pipe built-in function is
1034 // reserve_id_t, which is not defined in the builtin def file , we used int
1035 // as return type and need to override the return type of these functions.
1036 TheCall->setType(Context.OCLReserveIDTy);
1037 break;
1038 case Builtin::BIcommit_read_pipe:
1039 case Builtin::BIcommit_write_pipe:
1040 case Builtin::BIwork_group_commit_read_pipe:
1041 case Builtin::BIwork_group_commit_write_pipe:
1042 case Builtin::BIsub_group_commit_read_pipe:
1043 case Builtin::BIsub_group_commit_write_pipe:
1044 if (SemaBuiltinCommitRWPipe(*this, TheCall))
1045 return ExprError();
1046 break;
1047 case Builtin::BIget_pipe_num_packets:
1048 case Builtin::BIget_pipe_max_packets:
1049 if (SemaBuiltinPipePackets(*this, TheCall))
1050 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001051 TheCall->setType(Context.UnsignedIntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001052 break;
Yaxun Liuf7449a12016-05-20 19:54:38 +00001053 case Builtin::BIto_global:
1054 case Builtin::BIto_local:
1055 case Builtin::BIto_private:
1056 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1057 return ExprError();
1058 break;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00001059 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1060 case Builtin::BIenqueue_kernel:
1061 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1062 return ExprError();
1063 break;
1064 case Builtin::BIget_kernel_work_group_size:
1065 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1066 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1067 return ExprError();
Nate Begeman4904e322010-06-08 02:47:44 +00001068 }
Richard Smith760520b2014-06-03 23:27:44 +00001069
Nate Begeman4904e322010-06-08 02:47:44 +00001070 // Since the target specific builtins for each arch overlap, only check those
1071 // of the arch we are compiling for.
Artem Belevich9674a642015-09-22 17:23:05 +00001072 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001073 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +00001074 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001075 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001076 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001077 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001078 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1079 return ExprError();
1080 break;
Tim Northover25e8a672014-05-24 12:51:25 +00001081 case llvm::Triple::aarch64:
1082 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +00001083 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +00001084 return ExprError();
1085 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001086 case llvm::Triple::mips:
1087 case llvm::Triple::mipsel:
1088 case llvm::Triple::mips64:
1089 case llvm::Triple::mips64el:
1090 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1091 return ExprError();
1092 break;
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001093 case llvm::Triple::systemz:
1094 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1095 return ExprError();
1096 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001097 case llvm::Triple::x86:
1098 case llvm::Triple::x86_64:
1099 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1100 return ExprError();
1101 break;
Kit Bartone50adcb2015-03-30 19:40:59 +00001102 case llvm::Triple::ppc:
1103 case llvm::Triple::ppc64:
1104 case llvm::Triple::ppc64le:
1105 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1106 return ExprError();
1107 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001108 default:
1109 break;
1110 }
1111 }
1112
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001113 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +00001114}
1115
Nate Begeman91e1fea2010-06-14 05:21:25 +00001116// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +00001117static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +00001118 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +00001119 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +00001120 switch (Type.getEltType()) {
1121 case NeonTypeFlags::Int8:
1122 case NeonTypeFlags::Poly8:
1123 return shift ? 7 : (8 << IsQuad) - 1;
1124 case NeonTypeFlags::Int16:
1125 case NeonTypeFlags::Poly16:
1126 return shift ? 15 : (4 << IsQuad) - 1;
1127 case NeonTypeFlags::Int32:
1128 return shift ? 31 : (2 << IsQuad) - 1;
1129 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +00001130 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +00001131 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001132 case NeonTypeFlags::Poly128:
1133 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +00001134 case NeonTypeFlags::Float16:
1135 assert(!shift && "cannot shift float types!");
1136 return (4 << IsQuad) - 1;
1137 case NeonTypeFlags::Float32:
1138 assert(!shift && "cannot shift float types!");
1139 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001140 case NeonTypeFlags::Float64:
1141 assert(!shift && "cannot shift float types!");
1142 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +00001143 }
David Blaikie8a40f702012-01-17 06:56:22 +00001144 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +00001145}
1146
Bob Wilsone4d77232011-11-08 05:04:11 +00001147/// getNeonEltType - Return the QualType corresponding to the elements of
1148/// the vector type specified by the NeonTypeFlags. This is used to check
1149/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +00001150static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +00001151 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +00001152 switch (Flags.getEltType()) {
1153 case NeonTypeFlags::Int8:
1154 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1155 case NeonTypeFlags::Int16:
1156 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1157 case NeonTypeFlags::Int32:
1158 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1159 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +00001160 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +00001161 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1162 else
1163 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1164 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001165 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +00001166 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001167 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +00001168 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +00001169 case NeonTypeFlags::Poly64:
Kevin Qin78b86532015-05-14 08:18:05 +00001170 if (IsInt64Long)
1171 return Context.UnsignedLongTy;
1172 else
1173 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001174 case NeonTypeFlags::Poly128:
1175 break;
Bob Wilsone4d77232011-11-08 05:04:11 +00001176 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +00001177 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001178 case NeonTypeFlags::Float32:
1179 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +00001180 case NeonTypeFlags::Float64:
1181 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001182 }
David Blaikie8a40f702012-01-17 06:56:22 +00001183 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +00001184}
1185
Tim Northover12670412014-02-19 10:37:05 +00001186bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +00001187 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +00001188 uint64_t mask = 0;
1189 unsigned TV = 0;
1190 int PtrArgNum = -1;
1191 bool HasConstPtr = false;
1192 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +00001193#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001194#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +00001195#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001196 }
1197
1198 // For NEON intrinsics which are overloaded on vector element type, validate
1199 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +00001200 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001201 if (mask) {
1202 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1203 return true;
1204
1205 TV = Result.getLimitedValue(64);
1206 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1207 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +00001208 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +00001209 }
1210
1211 if (PtrArgNum >= 0) {
1212 // Check that pointer arguments have the specified type.
1213 Expr *Arg = TheCall->getArg(PtrArgNum);
1214 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1215 Arg = ICE->getSubExpr();
1216 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1217 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +00001218
Tim Northovera2ee4332014-03-29 15:09:45 +00001219 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Tim Northover40956e62014-07-23 12:32:58 +00001220 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
Tim Northovera2ee4332014-03-29 15:09:45 +00001221 bool IsInt64Long =
1222 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1223 QualType EltTy =
1224 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +00001225 if (HasConstPtr)
1226 EltTy = EltTy.withConst();
1227 QualType LHSTy = Context.getPointerType(EltTy);
1228 AssignConvertType ConvTy;
1229 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1230 if (RHS.isInvalid())
1231 return true;
1232 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1233 RHS.get(), AA_Assigning))
1234 return true;
1235 }
1236
1237 // For NEON intrinsics which take an immediate value as part of the
1238 // instruction, range check them here.
1239 unsigned i = 0, l = 0, u = 0;
1240 switch (BuiltinID) {
1241 default:
1242 return false;
Tim Northover12670412014-02-19 10:37:05 +00001243#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001244#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +00001245#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001246 }
Tim Northover2fe823a2013-08-01 09:23:19 +00001247
Richard Sandiford28940af2014-04-16 08:47:51 +00001248 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +00001249}
1250
Tim Northovera2ee4332014-03-29 15:09:45 +00001251bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1252 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +00001253 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001254 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +00001255 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001256 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +00001257 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001258 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1259 BuiltinID == AArch64::BI__builtin_arm_strex ||
1260 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +00001261 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +00001262 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001263 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1264 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1265 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +00001266
1267 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1268
1269 // Ensure that we have the proper number of arguments.
1270 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1271 return true;
1272
1273 // Inspect the pointer argument of the atomic builtin. This should always be
1274 // a pointer type, whose element is an integral scalar or pointer type.
1275 // Because it is a pointer type, we don't have to worry about any implicit
1276 // casts here.
1277 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1278 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1279 if (PointerArgRes.isInvalid())
1280 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001281 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001282
1283 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1284 if (!pointerType) {
1285 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1286 << PointerArg->getType() << PointerArg->getSourceRange();
1287 return true;
1288 }
1289
1290 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1291 // task is to insert the appropriate casts into the AST. First work out just
1292 // what the appropriate type is.
1293 QualType ValType = pointerType->getPointeeType();
1294 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1295 if (IsLdrex)
1296 AddrType.addConst();
1297
1298 // Issue a warning if the cast is dodgy.
1299 CastKind CastNeeded = CK_NoOp;
1300 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1301 CastNeeded = CK_BitCast;
1302 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1303 << PointerArg->getType()
1304 << Context.getPointerType(AddrType)
1305 << AA_Passing << PointerArg->getSourceRange();
1306 }
1307
1308 // Finally, do the cast and replace the argument with the corrected version.
1309 AddrType = Context.getPointerType(AddrType);
1310 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1311 if (PointerArgRes.isInvalid())
1312 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001313 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001314
1315 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1316
1317 // In general, we allow ints, floats and pointers to be loaded and stored.
1318 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1319 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1320 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1321 << PointerArg->getType() << PointerArg->getSourceRange();
1322 return true;
1323 }
1324
1325 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +00001326 if (Context.getTypeSize(ValType) > MaxWidth) {
1327 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +00001328 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1329 << PointerArg->getType() << PointerArg->getSourceRange();
1330 return true;
1331 }
1332
1333 switch (ValType.getObjCLifetime()) {
1334 case Qualifiers::OCL_None:
1335 case Qualifiers::OCL_ExplicitNone:
1336 // okay
1337 break;
1338
1339 case Qualifiers::OCL_Weak:
1340 case Qualifiers::OCL_Strong:
1341 case Qualifiers::OCL_Autoreleasing:
1342 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1343 << ValType << PointerArg->getSourceRange();
1344 return true;
1345 }
1346
Tim Northover6aacd492013-07-16 09:47:53 +00001347 if (IsLdrex) {
1348 TheCall->setType(ValType);
1349 return false;
1350 }
1351
1352 // Initialize the argument to be stored.
1353 ExprResult ValArg = TheCall->getArg(0);
1354 InitializedEntity Entity = InitializedEntity::InitializeParameter(
1355 Context, ValType, /*consume*/ false);
1356 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1357 if (ValArg.isInvalid())
1358 return true;
Tim Northover6aacd492013-07-16 09:47:53 +00001359 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +00001360
1361 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1362 // but the custom checker bypasses all default analysis.
1363 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +00001364 return false;
1365}
1366
Nate Begeman4904e322010-06-08 02:47:44 +00001367bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +00001368 llvm::APSInt Result;
1369
Tim Northover6aacd492013-07-16 09:47:53 +00001370 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001371 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1372 BuiltinID == ARM::BI__builtin_arm_strex ||
1373 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001374 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +00001375 }
1376
Yi Kong26d104a2014-08-13 19:18:14 +00001377 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1378 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1379 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1380 }
1381
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001382 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1383 BuiltinID == ARM::BI__builtin_arm_wsr64)
1384 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1385
1386 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1387 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1388 BuiltinID == ARM::BI__builtin_arm_wsr ||
1389 BuiltinID == ARM::BI__builtin_arm_wsrp)
1390 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1391
Tim Northover12670412014-02-19 10:37:05 +00001392 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1393 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +00001394
Yi Kong4efadfb2014-07-03 16:01:25 +00001395 // For intrinsics which take an immediate value as part of the instruction,
1396 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +00001397 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +00001398 switch (BuiltinID) {
1399 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +00001400 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
1401 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +00001402 case ARM::BI__builtin_arm_vcvtr_f:
1403 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +00001404 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +00001405 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +00001406 case ARM::BI__builtin_arm_isb:
1407 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001408 }
Nate Begemand773fe62010-06-13 04:47:52 +00001409
Nate Begemanf568b072010-08-03 21:32:34 +00001410 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +00001411 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001412}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001413
Tim Northover573cbee2014-05-24 12:52:07 +00001414bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +00001415 CallExpr *TheCall) {
1416 llvm::APSInt Result;
1417
Tim Northover573cbee2014-05-24 12:52:07 +00001418 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001419 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1420 BuiltinID == AArch64::BI__builtin_arm_strex ||
1421 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001422 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1423 }
1424
Yi Konga5548432014-08-13 19:18:20 +00001425 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1426 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1427 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1428 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1429 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1430 }
1431
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001432 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1433 BuiltinID == AArch64::BI__builtin_arm_wsr64)
Tim Northover54e50002016-04-13 17:08:55 +00001434 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001435
1436 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1437 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1438 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1439 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1440 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1441
Tim Northovera2ee4332014-03-29 15:09:45 +00001442 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1443 return true;
1444
Yi Kong19a29ac2014-07-17 10:52:06 +00001445 // For intrinsics which take an immediate value as part of the instruction,
1446 // range check them here.
1447 unsigned i = 0, l = 0, u = 0;
1448 switch (BuiltinID) {
1449 default: return false;
1450 case AArch64::BI__builtin_arm_dmb:
1451 case AArch64::BI__builtin_arm_dsb:
1452 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1453 }
1454
Yi Kong19a29ac2014-07-17 10:52:06 +00001455 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +00001456}
1457
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001458bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1459 unsigned i = 0, l = 0, u = 0;
1460 switch (BuiltinID) {
1461 default: return false;
1462 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1463 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +00001464 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1465 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1466 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1467 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1468 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001469 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001470
Richard Sandiford28940af2014-04-16 08:47:51 +00001471 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001472}
1473
Kit Bartone50adcb2015-03-30 19:40:59 +00001474bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1475 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00001476 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1477 BuiltinID == PPC::BI__builtin_divdeu ||
1478 BuiltinID == PPC::BI__builtin_bpermd;
1479 bool IsTarget64Bit = Context.getTargetInfo()
1480 .getTypeWidth(Context
1481 .getTargetInfo()
1482 .getIntPtrType()) == 64;
1483 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1484 BuiltinID == PPC::BI__builtin_divweu ||
1485 BuiltinID == PPC::BI__builtin_divde ||
1486 BuiltinID == PPC::BI__builtin_divdeu;
1487
1488 if (Is64BitBltin && !IsTarget64Bit)
1489 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1490 << TheCall->getSourceRange();
1491
1492 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1493 (BuiltinID == PPC::BI__builtin_bpermd &&
1494 !Context.getTargetInfo().hasFeature("bpermd")))
1495 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1496 << TheCall->getSourceRange();
1497
Kit Bartone50adcb2015-03-30 19:40:59 +00001498 switch (BuiltinID) {
1499 default: return false;
1500 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1501 case PPC::BI__builtin_altivec_crypto_vshasigmad:
1502 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1503 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1504 case PPC::BI__builtin_tbegin:
1505 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1506 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1507 case PPC::BI__builtin_tabortwc:
1508 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1509 case PPC::BI__builtin_tabortwci:
1510 case PPC::BI__builtin_tabortdci:
1511 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1512 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1513 }
1514 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1515}
1516
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001517bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1518 CallExpr *TheCall) {
1519 if (BuiltinID == SystemZ::BI__builtin_tabort) {
1520 Expr *Arg = TheCall->getArg(0);
1521 llvm::APSInt AbortCode(32);
1522 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1523 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1524 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1525 << Arg->getSourceRange();
1526 }
1527
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001528 // For intrinsics which take an immediate value as part of the instruction,
1529 // range check them here.
1530 unsigned i = 0, l = 0, u = 0;
1531 switch (BuiltinID) {
1532 default: return false;
1533 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1534 case SystemZ::BI__builtin_s390_verimb:
1535 case SystemZ::BI__builtin_s390_verimh:
1536 case SystemZ::BI__builtin_s390_verimf:
1537 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1538 case SystemZ::BI__builtin_s390_vfaeb:
1539 case SystemZ::BI__builtin_s390_vfaeh:
1540 case SystemZ::BI__builtin_s390_vfaef:
1541 case SystemZ::BI__builtin_s390_vfaebs:
1542 case SystemZ::BI__builtin_s390_vfaehs:
1543 case SystemZ::BI__builtin_s390_vfaefs:
1544 case SystemZ::BI__builtin_s390_vfaezb:
1545 case SystemZ::BI__builtin_s390_vfaezh:
1546 case SystemZ::BI__builtin_s390_vfaezf:
1547 case SystemZ::BI__builtin_s390_vfaezbs:
1548 case SystemZ::BI__builtin_s390_vfaezhs:
1549 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1550 case SystemZ::BI__builtin_s390_vfidb:
1551 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1552 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1553 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1554 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1555 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1556 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1557 case SystemZ::BI__builtin_s390_vstrcb:
1558 case SystemZ::BI__builtin_s390_vstrch:
1559 case SystemZ::BI__builtin_s390_vstrcf:
1560 case SystemZ::BI__builtin_s390_vstrczb:
1561 case SystemZ::BI__builtin_s390_vstrczh:
1562 case SystemZ::BI__builtin_s390_vstrczf:
1563 case SystemZ::BI__builtin_s390_vstrcbs:
1564 case SystemZ::BI__builtin_s390_vstrchs:
1565 case SystemZ::BI__builtin_s390_vstrcfs:
1566 case SystemZ::BI__builtin_s390_vstrczbs:
1567 case SystemZ::BI__builtin_s390_vstrczhs:
1568 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1569 }
1570 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001571}
1572
Craig Topper5ba2c502015-11-07 08:08:31 +00001573/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1574/// This checks that the target supports __builtin_cpu_supports and
1575/// that the string argument is constant and valid.
1576static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1577 Expr *Arg = TheCall->getArg(0);
1578
1579 // Check if the argument is a string literal.
1580 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1581 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1582 << Arg->getSourceRange();
1583
1584 // Check the contents of the string.
1585 StringRef Feature =
1586 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1587 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1588 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1589 << Arg->getSourceRange();
1590 return false;
1591}
1592
Craig Topperf0ddc892016-09-23 04:48:27 +00001593static bool isX86_64Builtin(unsigned BuiltinID) {
1594 // These builtins only work on x86-64 targets.
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001595 switch (BuiltinID) {
Craig Topperfe22d592016-07-21 07:38:43 +00001596 case X86::BI__builtin_ia32_addcarryx_u64:
1597 case X86::BI__builtin_ia32_addcarry_u64:
1598 case X86::BI__builtin_ia32_subborrow_u64:
1599 case X86::BI__builtin_ia32_readeflags_u64:
1600 case X86::BI__builtin_ia32_writeeflags_u64:
1601 case X86::BI__builtin_ia32_bextr_u64:
1602 case X86::BI__builtin_ia32_bextri_u64:
1603 case X86::BI__builtin_ia32_bzhi_di:
1604 case X86::BI__builtin_ia32_pdep_di:
1605 case X86::BI__builtin_ia32_pext_di:
1606 case X86::BI__builtin_ia32_crc32di:
1607 case X86::BI__builtin_ia32_fxsave64:
1608 case X86::BI__builtin_ia32_fxrstor64:
1609 case X86::BI__builtin_ia32_xsave64:
1610 case X86::BI__builtin_ia32_xrstor64:
1611 case X86::BI__builtin_ia32_xsaveopt64:
1612 case X86::BI__builtin_ia32_xrstors64:
1613 case X86::BI__builtin_ia32_xsavec64:
1614 case X86::BI__builtin_ia32_xsaves64:
1615 case X86::BI__builtin_ia32_rdfsbase64:
1616 case X86::BI__builtin_ia32_rdgsbase64:
1617 case X86::BI__builtin_ia32_wrfsbase64:
1618 case X86::BI__builtin_ia32_wrgsbase64:
Craig Topper351ed422016-07-24 14:58:06 +00001619 case X86::BI__builtin_ia32_pbroadcastq512_gpr_mask:
1620 case X86::BI__builtin_ia32_pbroadcastq256_gpr_mask:
1621 case X86::BI__builtin_ia32_pbroadcastq128_gpr_mask:
Craig Topperfe22d592016-07-21 07:38:43 +00001622 case X86::BI__builtin_ia32_vcvtsd2si64:
1623 case X86::BI__builtin_ia32_vcvtsd2usi64:
1624 case X86::BI__builtin_ia32_vcvtss2si64:
1625 case X86::BI__builtin_ia32_vcvtss2usi64:
1626 case X86::BI__builtin_ia32_vcvttsd2si64:
1627 case X86::BI__builtin_ia32_vcvttsd2usi64:
1628 case X86::BI__builtin_ia32_vcvttss2si64:
1629 case X86::BI__builtin_ia32_vcvttss2usi64:
1630 case X86::BI__builtin_ia32_cvtss2si64:
1631 case X86::BI__builtin_ia32_cvttss2si64:
1632 case X86::BI__builtin_ia32_cvtsd2si64:
1633 case X86::BI__builtin_ia32_cvttsd2si64:
1634 case X86::BI__builtin_ia32_cvtsi2sd64:
1635 case X86::BI__builtin_ia32_cvtsi2ss64:
1636 case X86::BI__builtin_ia32_cvtusi2sd64:
1637 case X86::BI__builtin_ia32_cvtusi2ss64:
Craig Topperf0ddc892016-09-23 04:48:27 +00001638 case X86::BI__builtin_ia32_rdseed64_step:
1639 return true;
Craig Topperfe22d592016-07-21 07:38:43 +00001640 }
Craig Topperf0ddc892016-09-23 04:48:27 +00001641
1642 return false;
1643}
1644
Craig Toppera7e253e2016-09-23 04:48:31 +00001645// Check if the rounding mode is legal.
1646bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
1647 // Indicates if this instruction has rounding control or just SAE.
1648 bool HasRC = false;
1649
1650 unsigned ArgNum = 0;
1651 switch (BuiltinID) {
1652 default:
1653 return false;
1654 case X86::BI__builtin_ia32_vcvttsd2si32:
1655 case X86::BI__builtin_ia32_vcvttsd2si64:
1656 case X86::BI__builtin_ia32_vcvttsd2usi32:
1657 case X86::BI__builtin_ia32_vcvttsd2usi64:
1658 case X86::BI__builtin_ia32_vcvttss2si32:
1659 case X86::BI__builtin_ia32_vcvttss2si64:
1660 case X86::BI__builtin_ia32_vcvttss2usi32:
1661 case X86::BI__builtin_ia32_vcvttss2usi64:
1662 ArgNum = 1;
1663 break;
1664 case X86::BI__builtin_ia32_cvtps2pd512_mask:
1665 case X86::BI__builtin_ia32_cvttpd2dq512_mask:
1666 case X86::BI__builtin_ia32_cvttpd2qq512_mask:
1667 case X86::BI__builtin_ia32_cvttpd2udq512_mask:
1668 case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
1669 case X86::BI__builtin_ia32_cvttps2dq512_mask:
1670 case X86::BI__builtin_ia32_cvttps2qq512_mask:
1671 case X86::BI__builtin_ia32_cvttps2udq512_mask:
1672 case X86::BI__builtin_ia32_cvttps2uqq512_mask:
1673 case X86::BI__builtin_ia32_exp2pd_mask:
1674 case X86::BI__builtin_ia32_exp2ps_mask:
1675 case X86::BI__builtin_ia32_getexppd512_mask:
1676 case X86::BI__builtin_ia32_getexpps512_mask:
1677 case X86::BI__builtin_ia32_rcp28pd_mask:
1678 case X86::BI__builtin_ia32_rcp28ps_mask:
1679 case X86::BI__builtin_ia32_rsqrt28pd_mask:
1680 case X86::BI__builtin_ia32_rsqrt28ps_mask:
1681 case X86::BI__builtin_ia32_vcomisd:
1682 case X86::BI__builtin_ia32_vcomiss:
1683 case X86::BI__builtin_ia32_vcvtph2ps512_mask:
1684 ArgNum = 3;
1685 break;
1686 case X86::BI__builtin_ia32_cmppd512_mask:
1687 case X86::BI__builtin_ia32_cmpps512_mask:
1688 case X86::BI__builtin_ia32_cmpsd_mask:
1689 case X86::BI__builtin_ia32_cmpss_mask:
1690 case X86::BI__builtin_ia32_getexpsd128_round_mask:
1691 case X86::BI__builtin_ia32_getexpss128_round_mask:
1692 case X86::BI__builtin_ia32_rcp28sd_round_mask:
1693 case X86::BI__builtin_ia32_rcp28ss_round_mask:
1694 case X86::BI__builtin_ia32_reducepd512_mask:
1695 case X86::BI__builtin_ia32_reduceps512_mask:
1696 case X86::BI__builtin_ia32_rndscalepd_mask:
1697 case X86::BI__builtin_ia32_rndscaleps_mask:
1698 case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
1699 case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
1700 ArgNum = 4;
1701 break;
1702 case X86::BI__builtin_ia32_fixupimmpd512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001703 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001704 case X86::BI__builtin_ia32_fixupimmps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001705 case X86::BI__builtin_ia32_fixupimmps512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001706 case X86::BI__builtin_ia32_fixupimmsd_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001707 case X86::BI__builtin_ia32_fixupimmsd_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001708 case X86::BI__builtin_ia32_fixupimmss_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001709 case X86::BI__builtin_ia32_fixupimmss_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001710 case X86::BI__builtin_ia32_rangepd512_mask:
1711 case X86::BI__builtin_ia32_rangeps512_mask:
1712 case X86::BI__builtin_ia32_rangesd128_round_mask:
1713 case X86::BI__builtin_ia32_rangess128_round_mask:
1714 case X86::BI__builtin_ia32_reducesd_mask:
1715 case X86::BI__builtin_ia32_reducess_mask:
1716 case X86::BI__builtin_ia32_rndscalesd_round_mask:
1717 case X86::BI__builtin_ia32_rndscaless_round_mask:
1718 ArgNum = 5;
1719 break;
Craig Topper7609f1c2016-10-01 21:03:50 +00001720 case X86::BI__builtin_ia32_vcvtsd2si64:
1721 case X86::BI__builtin_ia32_vcvtsd2si32:
1722 case X86::BI__builtin_ia32_vcvtsd2usi32:
1723 case X86::BI__builtin_ia32_vcvtsd2usi64:
1724 case X86::BI__builtin_ia32_vcvtss2si32:
1725 case X86::BI__builtin_ia32_vcvtss2si64:
1726 case X86::BI__builtin_ia32_vcvtss2usi32:
1727 case X86::BI__builtin_ia32_vcvtss2usi64:
1728 ArgNum = 1;
1729 HasRC = true;
1730 break;
1731 case X86::BI__builtin_ia32_cvtusi2sd64:
1732 case X86::BI__builtin_ia32_cvtusi2ss32:
1733 case X86::BI__builtin_ia32_cvtusi2ss64:
1734 ArgNum = 2;
1735 HasRC = true;
1736 break;
1737 case X86::BI__builtin_ia32_cvtdq2ps512_mask:
1738 case X86::BI__builtin_ia32_cvtudq2ps512_mask:
1739 case X86::BI__builtin_ia32_cvtpd2ps512_mask:
1740 case X86::BI__builtin_ia32_cvtpd2qq512_mask:
1741 case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
1742 case X86::BI__builtin_ia32_cvtps2qq512_mask:
1743 case X86::BI__builtin_ia32_cvtps2uqq512_mask:
1744 case X86::BI__builtin_ia32_cvtqq2pd512_mask:
1745 case X86::BI__builtin_ia32_cvtqq2ps512_mask:
1746 case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
1747 case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
1748 ArgNum = 3;
1749 HasRC = true;
1750 break;
1751 case X86::BI__builtin_ia32_addpd512_mask:
1752 case X86::BI__builtin_ia32_addps512_mask:
1753 case X86::BI__builtin_ia32_divpd512_mask:
1754 case X86::BI__builtin_ia32_divps512_mask:
1755 case X86::BI__builtin_ia32_mulpd512_mask:
1756 case X86::BI__builtin_ia32_mulps512_mask:
1757 case X86::BI__builtin_ia32_subpd512_mask:
1758 case X86::BI__builtin_ia32_subps512_mask:
1759 case X86::BI__builtin_ia32_addss_round_mask:
1760 case X86::BI__builtin_ia32_addsd_round_mask:
1761 case X86::BI__builtin_ia32_divss_round_mask:
1762 case X86::BI__builtin_ia32_divsd_round_mask:
1763 case X86::BI__builtin_ia32_mulss_round_mask:
1764 case X86::BI__builtin_ia32_mulsd_round_mask:
1765 case X86::BI__builtin_ia32_subss_round_mask:
1766 case X86::BI__builtin_ia32_subsd_round_mask:
1767 case X86::BI__builtin_ia32_scalefpd512_mask:
1768 case X86::BI__builtin_ia32_scalefps512_mask:
1769 case X86::BI__builtin_ia32_scalefsd_round_mask:
1770 case X86::BI__builtin_ia32_scalefss_round_mask:
1771 case X86::BI__builtin_ia32_getmantpd512_mask:
1772 case X86::BI__builtin_ia32_getmantps512_mask:
1773 case X86::BI__builtin_ia32_vfmaddpd512_mask:
1774 case X86::BI__builtin_ia32_vfmaddpd512_mask3:
1775 case X86::BI__builtin_ia32_vfmaddpd512_maskz:
1776 case X86::BI__builtin_ia32_vfmaddps512_mask:
1777 case X86::BI__builtin_ia32_vfmaddps512_mask3:
1778 case X86::BI__builtin_ia32_vfmaddps512_maskz:
1779 case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
1780 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
1781 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
1782 case X86::BI__builtin_ia32_vfmaddsubps512_mask:
1783 case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
1784 case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
1785 case X86::BI__builtin_ia32_vfmsubpd512_mask3:
1786 case X86::BI__builtin_ia32_vfmsubps512_mask3:
1787 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
1788 case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
1789 case X86::BI__builtin_ia32_vfnmaddpd512_mask:
1790 case X86::BI__builtin_ia32_vfnmaddps512_mask:
1791 case X86::BI__builtin_ia32_vfnmsubpd512_mask:
1792 case X86::BI__builtin_ia32_vfnmsubpd512_mask3:
1793 case X86::BI__builtin_ia32_vfnmsubps512_mask:
1794 case X86::BI__builtin_ia32_vfnmsubps512_mask3:
1795 case X86::BI__builtin_ia32_vfmaddsd3_mask:
1796 case X86::BI__builtin_ia32_vfmaddsd3_maskz:
1797 case X86::BI__builtin_ia32_vfmaddsd3_mask3:
1798 case X86::BI__builtin_ia32_vfmaddss3_mask:
1799 case X86::BI__builtin_ia32_vfmaddss3_maskz:
1800 case X86::BI__builtin_ia32_vfmaddss3_mask3:
1801 ArgNum = 4;
1802 HasRC = true;
1803 break;
1804 case X86::BI__builtin_ia32_getmantsd_round_mask:
1805 case X86::BI__builtin_ia32_getmantss_round_mask:
1806 ArgNum = 5;
1807 HasRC = true;
1808 break;
Craig Toppera7e253e2016-09-23 04:48:31 +00001809 }
1810
1811 llvm::APSInt Result;
1812
1813 // We can't check the value of a dependent argument.
1814 Expr *Arg = TheCall->getArg(ArgNum);
1815 if (Arg->isTypeDependent() || Arg->isValueDependent())
1816 return false;
1817
1818 // Check constant-ness first.
1819 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
1820 return true;
1821
1822 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
1823 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
1824 // combined with ROUND_NO_EXC.
1825 if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
1826 Result == 8/*ROUND_NO_EXC*/ ||
1827 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
1828 return false;
1829
1830 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
1831 << Arg->getSourceRange();
1832}
1833
Craig Topperf0ddc892016-09-23 04:48:27 +00001834bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1835 if (BuiltinID == X86::BI__builtin_cpu_supports)
1836 return SemaBuiltinCpuSupports(*this, TheCall);
1837
1838 if (BuiltinID == X86::BI__builtin_ms_va_start)
1839 return SemaBuiltinMSVAStart(TheCall);
1840
1841 // Check for 64-bit only builtins on a 32-bit target.
1842 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
1843 if (TT.getArch() != llvm::Triple::x86_64 && isX86_64Builtin(BuiltinID))
1844 return Diag(TheCall->getCallee()->getLocStart(),
1845 diag::err_x86_builtin_32_bit_tgt);
1846
Craig Toppera7e253e2016-09-23 04:48:31 +00001847 // If the intrinsic has rounding or SAE make sure its valid.
1848 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
1849 return true;
1850
Craig Topperf0ddc892016-09-23 04:48:27 +00001851 // For intrinsics which take an immediate value as part of the instruction,
1852 // range check them here.
1853 int i = 0, l = 0, u = 0;
1854 switch (BuiltinID) {
1855 default:
1856 return false;
Craig Topper39c87102016-05-18 03:18:12 +00001857 case X86::BI__builtin_ia32_extractf64x4_mask:
1858 case X86::BI__builtin_ia32_extracti64x4_mask:
1859 case X86::BI__builtin_ia32_extractf32x8_mask:
1860 case X86::BI__builtin_ia32_extracti32x8_mask:
1861 case X86::BI__builtin_ia32_extractf64x2_256_mask:
1862 case X86::BI__builtin_ia32_extracti64x2_256_mask:
1863 case X86::BI__builtin_ia32_extractf32x4_256_mask:
1864 case X86::BI__builtin_ia32_extracti32x4_256_mask:
1865 i = 1; l = 0; u = 1;
1866 break;
Richard Trieucc3949d2016-02-18 22:34:54 +00001867 case X86::BI_mm_prefetch:
Craig Topper39c87102016-05-18 03:18:12 +00001868 case X86::BI__builtin_ia32_extractf32x4_mask:
1869 case X86::BI__builtin_ia32_extracti32x4_mask:
Craig Topper39c87102016-05-18 03:18:12 +00001870 case X86::BI__builtin_ia32_extractf64x2_512_mask:
1871 case X86::BI__builtin_ia32_extracti64x2_512_mask:
1872 i = 1; l = 0; u = 3;
1873 break;
1874 case X86::BI__builtin_ia32_insertf32x8_mask:
1875 case X86::BI__builtin_ia32_inserti32x8_mask:
1876 case X86::BI__builtin_ia32_insertf64x4_mask:
1877 case X86::BI__builtin_ia32_inserti64x4_mask:
1878 case X86::BI__builtin_ia32_insertf64x2_256_mask:
1879 case X86::BI__builtin_ia32_inserti64x2_256_mask:
1880 case X86::BI__builtin_ia32_insertf32x4_256_mask:
1881 case X86::BI__builtin_ia32_inserti32x4_256_mask:
1882 i = 2; l = 0; u = 1;
Richard Trieucc3949d2016-02-18 22:34:54 +00001883 break;
1884 case X86::BI__builtin_ia32_sha1rnds4:
Craig Topper39c87102016-05-18 03:18:12 +00001885 case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
1886 case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
1887 case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
1888 case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00001889 case X86::BI__builtin_ia32_insertf64x2_512_mask:
1890 case X86::BI__builtin_ia32_inserti64x2_512_mask:
1891 case X86::BI__builtin_ia32_insertf32x4_mask:
1892 case X86::BI__builtin_ia32_inserti32x4_mask:
1893 i = 2; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00001894 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00001895 case X86::BI__builtin_ia32_vpermil2pd:
1896 case X86::BI__builtin_ia32_vpermil2pd256:
1897 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00001898 case X86::BI__builtin_ia32_vpermil2ps256:
Craig Topper39c87102016-05-18 03:18:12 +00001899 i = 3; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00001900 break;
Craig Topper95b0d732015-01-25 23:30:05 +00001901 case X86::BI__builtin_ia32_cmpb128_mask:
1902 case X86::BI__builtin_ia32_cmpw128_mask:
1903 case X86::BI__builtin_ia32_cmpd128_mask:
1904 case X86::BI__builtin_ia32_cmpq128_mask:
1905 case X86::BI__builtin_ia32_cmpb256_mask:
1906 case X86::BI__builtin_ia32_cmpw256_mask:
1907 case X86::BI__builtin_ia32_cmpd256_mask:
1908 case X86::BI__builtin_ia32_cmpq256_mask:
1909 case X86::BI__builtin_ia32_cmpb512_mask:
1910 case X86::BI__builtin_ia32_cmpw512_mask:
1911 case X86::BI__builtin_ia32_cmpd512_mask:
1912 case X86::BI__builtin_ia32_cmpq512_mask:
1913 case X86::BI__builtin_ia32_ucmpb128_mask:
1914 case X86::BI__builtin_ia32_ucmpw128_mask:
1915 case X86::BI__builtin_ia32_ucmpd128_mask:
1916 case X86::BI__builtin_ia32_ucmpq128_mask:
1917 case X86::BI__builtin_ia32_ucmpb256_mask:
1918 case X86::BI__builtin_ia32_ucmpw256_mask:
1919 case X86::BI__builtin_ia32_ucmpd256_mask:
1920 case X86::BI__builtin_ia32_ucmpq256_mask:
1921 case X86::BI__builtin_ia32_ucmpb512_mask:
1922 case X86::BI__builtin_ia32_ucmpw512_mask:
1923 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00001924 case X86::BI__builtin_ia32_ucmpq512_mask:
Craig Topper8dd7d0d2015-02-13 06:04:48 +00001925 case X86::BI__builtin_ia32_vpcomub:
1926 case X86::BI__builtin_ia32_vpcomuw:
1927 case X86::BI__builtin_ia32_vpcomud:
1928 case X86::BI__builtin_ia32_vpcomuq:
1929 case X86::BI__builtin_ia32_vpcomb:
1930 case X86::BI__builtin_ia32_vpcomw:
1931 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00001932 case X86::BI__builtin_ia32_vpcomq:
Craig Topper39c87102016-05-18 03:18:12 +00001933 i = 2; l = 0; u = 7;
1934 break;
1935 case X86::BI__builtin_ia32_roundps:
1936 case X86::BI__builtin_ia32_roundpd:
1937 case X86::BI__builtin_ia32_roundps256:
1938 case X86::BI__builtin_ia32_roundpd256:
Craig Topper39c87102016-05-18 03:18:12 +00001939 i = 1; l = 0; u = 15;
1940 break;
1941 case X86::BI__builtin_ia32_roundss:
1942 case X86::BI__builtin_ia32_roundsd:
1943 case X86::BI__builtin_ia32_rangepd128_mask:
1944 case X86::BI__builtin_ia32_rangepd256_mask:
1945 case X86::BI__builtin_ia32_rangepd512_mask:
1946 case X86::BI__builtin_ia32_rangeps128_mask:
1947 case X86::BI__builtin_ia32_rangeps256_mask:
1948 case X86::BI__builtin_ia32_rangeps512_mask:
1949 case X86::BI__builtin_ia32_getmantsd_round_mask:
1950 case X86::BI__builtin_ia32_getmantss_round_mask:
Craig Topper39c87102016-05-18 03:18:12 +00001951 i = 2; l = 0; u = 15;
1952 break;
1953 case X86::BI__builtin_ia32_cmpps:
1954 case X86::BI__builtin_ia32_cmpss:
1955 case X86::BI__builtin_ia32_cmppd:
1956 case X86::BI__builtin_ia32_cmpsd:
1957 case X86::BI__builtin_ia32_cmpps256:
1958 case X86::BI__builtin_ia32_cmppd256:
1959 case X86::BI__builtin_ia32_cmpps128_mask:
1960 case X86::BI__builtin_ia32_cmppd128_mask:
1961 case X86::BI__builtin_ia32_cmpps256_mask:
1962 case X86::BI__builtin_ia32_cmppd256_mask:
1963 case X86::BI__builtin_ia32_cmpps512_mask:
1964 case X86::BI__builtin_ia32_cmppd512_mask:
1965 case X86::BI__builtin_ia32_cmpsd_mask:
1966 case X86::BI__builtin_ia32_cmpss_mask:
1967 i = 2; l = 0; u = 31;
1968 break;
1969 case X86::BI__builtin_ia32_xabort:
1970 i = 0; l = -128; u = 255;
1971 break;
1972 case X86::BI__builtin_ia32_pshufw:
1973 case X86::BI__builtin_ia32_aeskeygenassist128:
1974 i = 1; l = -128; u = 255;
1975 break;
1976 case X86::BI__builtin_ia32_vcvtps2ph:
1977 case X86::BI__builtin_ia32_vcvtps2ph256:
Craig Topper39c87102016-05-18 03:18:12 +00001978 case X86::BI__builtin_ia32_rndscaleps_128_mask:
1979 case X86::BI__builtin_ia32_rndscalepd_128_mask:
1980 case X86::BI__builtin_ia32_rndscaleps_256_mask:
1981 case X86::BI__builtin_ia32_rndscalepd_256_mask:
1982 case X86::BI__builtin_ia32_rndscaleps_mask:
1983 case X86::BI__builtin_ia32_rndscalepd_mask:
1984 case X86::BI__builtin_ia32_reducepd128_mask:
1985 case X86::BI__builtin_ia32_reducepd256_mask:
1986 case X86::BI__builtin_ia32_reducepd512_mask:
1987 case X86::BI__builtin_ia32_reduceps128_mask:
1988 case X86::BI__builtin_ia32_reduceps256_mask:
1989 case X86::BI__builtin_ia32_reduceps512_mask:
1990 case X86::BI__builtin_ia32_prold512_mask:
1991 case X86::BI__builtin_ia32_prolq512_mask:
1992 case X86::BI__builtin_ia32_prold128_mask:
1993 case X86::BI__builtin_ia32_prold256_mask:
1994 case X86::BI__builtin_ia32_prolq128_mask:
1995 case X86::BI__builtin_ia32_prolq256_mask:
1996 case X86::BI__builtin_ia32_prord128_mask:
1997 case X86::BI__builtin_ia32_prord256_mask:
1998 case X86::BI__builtin_ia32_prorq128_mask:
1999 case X86::BI__builtin_ia32_prorq256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002000 case X86::BI__builtin_ia32_psllwi512_mask:
2001 case X86::BI__builtin_ia32_psllwi128_mask:
2002 case X86::BI__builtin_ia32_psllwi256_mask:
2003 case X86::BI__builtin_ia32_psrldi128_mask:
2004 case X86::BI__builtin_ia32_psrldi256_mask:
2005 case X86::BI__builtin_ia32_psrldi512_mask:
2006 case X86::BI__builtin_ia32_psrlqi128_mask:
2007 case X86::BI__builtin_ia32_psrlqi256_mask:
2008 case X86::BI__builtin_ia32_psrlqi512_mask:
2009 case X86::BI__builtin_ia32_psrawi512_mask:
2010 case X86::BI__builtin_ia32_psrawi128_mask:
2011 case X86::BI__builtin_ia32_psrawi256_mask:
2012 case X86::BI__builtin_ia32_psrlwi512_mask:
2013 case X86::BI__builtin_ia32_psrlwi128_mask:
2014 case X86::BI__builtin_ia32_psrlwi256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002015 case X86::BI__builtin_ia32_psradi128_mask:
2016 case X86::BI__builtin_ia32_psradi256_mask:
2017 case X86::BI__builtin_ia32_psradi512_mask:
2018 case X86::BI__builtin_ia32_psraqi128_mask:
2019 case X86::BI__builtin_ia32_psraqi256_mask:
2020 case X86::BI__builtin_ia32_psraqi512_mask:
2021 case X86::BI__builtin_ia32_pslldi128_mask:
2022 case X86::BI__builtin_ia32_pslldi256_mask:
2023 case X86::BI__builtin_ia32_pslldi512_mask:
2024 case X86::BI__builtin_ia32_psllqi128_mask:
2025 case X86::BI__builtin_ia32_psllqi256_mask:
2026 case X86::BI__builtin_ia32_psllqi512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002027 case X86::BI__builtin_ia32_fpclasspd128_mask:
2028 case X86::BI__builtin_ia32_fpclasspd256_mask:
2029 case X86::BI__builtin_ia32_fpclassps128_mask:
2030 case X86::BI__builtin_ia32_fpclassps256_mask:
2031 case X86::BI__builtin_ia32_fpclassps512_mask:
2032 case X86::BI__builtin_ia32_fpclasspd512_mask:
2033 case X86::BI__builtin_ia32_fpclasssd_mask:
2034 case X86::BI__builtin_ia32_fpclassss_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002035 i = 1; l = 0; u = 255;
2036 break;
2037 case X86::BI__builtin_ia32_palignr:
2038 case X86::BI__builtin_ia32_insertps128:
2039 case X86::BI__builtin_ia32_dpps:
2040 case X86::BI__builtin_ia32_dppd:
2041 case X86::BI__builtin_ia32_dpps256:
2042 case X86::BI__builtin_ia32_mpsadbw128:
2043 case X86::BI__builtin_ia32_mpsadbw256:
2044 case X86::BI__builtin_ia32_pcmpistrm128:
2045 case X86::BI__builtin_ia32_pcmpistri128:
2046 case X86::BI__builtin_ia32_pcmpistria128:
2047 case X86::BI__builtin_ia32_pcmpistric128:
2048 case X86::BI__builtin_ia32_pcmpistrio128:
2049 case X86::BI__builtin_ia32_pcmpistris128:
2050 case X86::BI__builtin_ia32_pcmpistriz128:
2051 case X86::BI__builtin_ia32_pclmulqdq128:
2052 case X86::BI__builtin_ia32_vperm2f128_pd256:
2053 case X86::BI__builtin_ia32_vperm2f128_ps256:
2054 case X86::BI__builtin_ia32_vperm2f128_si256:
2055 case X86::BI__builtin_ia32_permti256:
2056 i = 2; l = -128; u = 255;
2057 break;
2058 case X86::BI__builtin_ia32_palignr128:
2059 case X86::BI__builtin_ia32_palignr256:
2060 case X86::BI__builtin_ia32_palignr128_mask:
2061 case X86::BI__builtin_ia32_palignr256_mask:
2062 case X86::BI__builtin_ia32_palignr512_mask:
2063 case X86::BI__builtin_ia32_alignq512_mask:
2064 case X86::BI__builtin_ia32_alignd512_mask:
2065 case X86::BI__builtin_ia32_alignd128_mask:
2066 case X86::BI__builtin_ia32_alignd256_mask:
2067 case X86::BI__builtin_ia32_alignq128_mask:
2068 case X86::BI__builtin_ia32_alignq256_mask:
2069 case X86::BI__builtin_ia32_vcomisd:
2070 case X86::BI__builtin_ia32_vcomiss:
2071 case X86::BI__builtin_ia32_shuf_f32x4_mask:
2072 case X86::BI__builtin_ia32_shuf_f64x2_mask:
2073 case X86::BI__builtin_ia32_shuf_i32x4_mask:
2074 case X86::BI__builtin_ia32_shuf_i64x2_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002075 case X86::BI__builtin_ia32_dbpsadbw128_mask:
2076 case X86::BI__builtin_ia32_dbpsadbw256_mask:
2077 case X86::BI__builtin_ia32_dbpsadbw512_mask:
2078 i = 2; l = 0; u = 255;
2079 break;
2080 case X86::BI__builtin_ia32_fixupimmpd512_mask:
2081 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2082 case X86::BI__builtin_ia32_fixupimmps512_mask:
2083 case X86::BI__builtin_ia32_fixupimmps512_maskz:
2084 case X86::BI__builtin_ia32_fixupimmsd_mask:
2085 case X86::BI__builtin_ia32_fixupimmsd_maskz:
2086 case X86::BI__builtin_ia32_fixupimmss_mask:
2087 case X86::BI__builtin_ia32_fixupimmss_maskz:
2088 case X86::BI__builtin_ia32_fixupimmpd128_mask:
2089 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2090 case X86::BI__builtin_ia32_fixupimmpd256_mask:
2091 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2092 case X86::BI__builtin_ia32_fixupimmps128_mask:
2093 case X86::BI__builtin_ia32_fixupimmps128_maskz:
2094 case X86::BI__builtin_ia32_fixupimmps256_mask:
2095 case X86::BI__builtin_ia32_fixupimmps256_maskz:
2096 case X86::BI__builtin_ia32_pternlogd512_mask:
2097 case X86::BI__builtin_ia32_pternlogd512_maskz:
2098 case X86::BI__builtin_ia32_pternlogq512_mask:
2099 case X86::BI__builtin_ia32_pternlogq512_maskz:
2100 case X86::BI__builtin_ia32_pternlogd128_mask:
2101 case X86::BI__builtin_ia32_pternlogd128_maskz:
2102 case X86::BI__builtin_ia32_pternlogd256_mask:
2103 case X86::BI__builtin_ia32_pternlogd256_maskz:
2104 case X86::BI__builtin_ia32_pternlogq128_mask:
2105 case X86::BI__builtin_ia32_pternlogq128_maskz:
2106 case X86::BI__builtin_ia32_pternlogq256_mask:
2107 case X86::BI__builtin_ia32_pternlogq256_maskz:
2108 i = 3; l = 0; u = 255;
2109 break;
2110 case X86::BI__builtin_ia32_pcmpestrm128:
2111 case X86::BI__builtin_ia32_pcmpestri128:
2112 case X86::BI__builtin_ia32_pcmpestria128:
2113 case X86::BI__builtin_ia32_pcmpestric128:
2114 case X86::BI__builtin_ia32_pcmpestrio128:
2115 case X86::BI__builtin_ia32_pcmpestris128:
2116 case X86::BI__builtin_ia32_pcmpestriz128:
2117 i = 4; l = -128; u = 255;
2118 break;
2119 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2120 case X86::BI__builtin_ia32_rndscaless_round_mask:
2121 i = 4; l = 0; u = 255;
Richard Trieucc3949d2016-02-18 22:34:54 +00002122 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002123 }
Craig Topperdd84ec52014-12-27 07:00:08 +00002124 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002125}
2126
Richard Smith55ce3522012-06-25 20:30:08 +00002127/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2128/// parameter with the FormatAttr's correct format_idx and firstDataArg.
2129/// Returns true when the format fits the function and the FormatStringInfo has
2130/// been populated.
2131bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2132 FormatStringInfo *FSI) {
2133 FSI->HasVAListArg = Format->getFirstArg() == 0;
2134 FSI->FormatIdx = Format->getFormatIdx() - 1;
2135 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002136
Richard Smith55ce3522012-06-25 20:30:08 +00002137 // The way the format attribute works in GCC, the implicit this argument
2138 // of member functions is counted. However, it doesn't appear in our own
2139 // lists, so decrement format_idx in that case.
2140 if (IsCXXMember) {
2141 if(FSI->FormatIdx == 0)
2142 return false;
2143 --FSI->FormatIdx;
2144 if (FSI->FirstDataArg != 0)
2145 --FSI->FirstDataArg;
2146 }
2147 return true;
2148}
Mike Stump11289f42009-09-09 15:08:12 +00002149
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002150/// Checks if a the given expression evaluates to null.
2151///
2152/// \brief Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00002153static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002154 // If the expression has non-null type, it doesn't evaluate to null.
2155 if (auto nullability
2156 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2157 if (*nullability == NullabilityKind::NonNull)
2158 return false;
2159 }
2160
Ted Kremeneka146db32014-01-17 06:24:47 +00002161 // As a special case, transparent unions initialized with zero are
2162 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002163 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00002164 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2165 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002166 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00002167 if (const InitListExpr *ILE =
2168 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002169 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00002170 }
2171
2172 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00002173 return (!Expr->isValueDependent() &&
2174 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2175 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002176}
2177
2178static void CheckNonNullArgument(Sema &S,
2179 const Expr *ArgExpr,
2180 SourceLocation CallSiteLoc) {
2181 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00002182 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2183 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00002184}
2185
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002186bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2187 FormatStringInfo FSI;
2188 if ((GetFormatStringType(Format) == FST_NSString) &&
2189 getFormatStringInfo(Format, false, &FSI)) {
2190 Idx = FSI.FormatIdx;
2191 return true;
2192 }
2193 return false;
2194}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002195/// \brief Diagnose use of %s directive in an NSString which is being passed
2196/// as formatting string to formatting method.
2197static void
2198DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2199 const NamedDecl *FDecl,
2200 Expr **Args,
2201 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002202 unsigned Idx = 0;
2203 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002204 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2205 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002206 Idx = 2;
2207 Format = true;
2208 }
2209 else
2210 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2211 if (S.GetFormatNSStringIdx(I, Idx)) {
2212 Format = true;
2213 break;
2214 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002215 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002216 if (!Format || NumArgs <= Idx)
2217 return;
2218 const Expr *FormatExpr = Args[Idx];
2219 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2220 FormatExpr = CSCE->getSubExpr();
2221 const StringLiteral *FormatString;
2222 if (const ObjCStringLiteral *OSL =
2223 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2224 FormatString = OSL->getString();
2225 else
2226 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2227 if (!FormatString)
2228 return;
2229 if (S.FormatStringHasSArg(FormatString)) {
2230 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2231 << "%s" << 1 << 1;
2232 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2233 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002234 }
2235}
2236
Douglas Gregorb4866e82015-06-19 18:13:19 +00002237/// Determine whether the given type has a non-null nullability annotation.
2238static bool isNonNullType(ASTContext &ctx, QualType type) {
2239 if (auto nullability = type->getNullability(ctx))
2240 return *nullability == NullabilityKind::NonNull;
2241
2242 return false;
2243}
2244
Ted Kremenek2bc73332014-01-17 06:24:43 +00002245static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00002246 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00002247 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00002248 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00002249 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002250 assert((FDecl || Proto) && "Need a function declaration or prototype");
2251
Ted Kremenek9aedc152014-01-17 06:24:56 +00002252 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00002253 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00002254 if (FDecl) {
2255 // Handle the nonnull attribute on the function/method declaration itself.
2256 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2257 if (!NonNull->args_size()) {
2258 // Easy case: all pointer arguments are nonnull.
2259 for (const auto *Arg : Args)
2260 if (S.isValidPointerAttrType(Arg->getType()))
2261 CheckNonNullArgument(S, Arg, CallSiteLoc);
2262 return;
2263 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002264
Douglas Gregorb4866e82015-06-19 18:13:19 +00002265 for (unsigned Val : NonNull->args()) {
2266 if (Val >= Args.size())
2267 continue;
2268 if (NonNullArgs.empty())
2269 NonNullArgs.resize(Args.size());
2270 NonNullArgs.set(Val);
2271 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002272 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002273 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002274
Douglas Gregorb4866e82015-06-19 18:13:19 +00002275 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2276 // Handle the nonnull attribute on the parameters of the
2277 // function/method.
2278 ArrayRef<ParmVarDecl*> parms;
2279 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2280 parms = FD->parameters();
2281 else
2282 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2283
2284 unsigned ParamIndex = 0;
2285 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2286 I != E; ++I, ++ParamIndex) {
2287 const ParmVarDecl *PVD = *I;
2288 if (PVD->hasAttr<NonNullAttr>() ||
2289 isNonNullType(S.Context, PVD->getType())) {
2290 if (NonNullArgs.empty())
2291 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00002292
Douglas Gregorb4866e82015-06-19 18:13:19 +00002293 NonNullArgs.set(ParamIndex);
2294 }
2295 }
2296 } else {
2297 // If we have a non-function, non-method declaration but no
2298 // function prototype, try to dig out the function prototype.
2299 if (!Proto) {
2300 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2301 QualType type = VD->getType().getNonReferenceType();
2302 if (auto pointerType = type->getAs<PointerType>())
2303 type = pointerType->getPointeeType();
2304 else if (auto blockType = type->getAs<BlockPointerType>())
2305 type = blockType->getPointeeType();
2306 // FIXME: data member pointers?
2307
2308 // Dig out the function prototype, if there is one.
2309 Proto = type->getAs<FunctionProtoType>();
2310 }
2311 }
2312
2313 // Fill in non-null argument information from the nullability
2314 // information on the parameter types (if we have them).
2315 if (Proto) {
2316 unsigned Index = 0;
2317 for (auto paramType : Proto->getParamTypes()) {
2318 if (isNonNullType(S.Context, paramType)) {
2319 if (NonNullArgs.empty())
2320 NonNullArgs.resize(Args.size());
2321
2322 NonNullArgs.set(Index);
2323 }
2324
2325 ++Index;
2326 }
2327 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002328 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002329
Douglas Gregorb4866e82015-06-19 18:13:19 +00002330 // Check for non-null arguments.
2331 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2332 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00002333 if (NonNullArgs[ArgIndex])
2334 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00002335 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002336}
2337
Richard Smith55ce3522012-06-25 20:30:08 +00002338/// Handles the checks for format strings, non-POD arguments to vararg
2339/// functions, and NULL arguments passed to non-NULL parameters.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002340void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2341 ArrayRef<const Expr *> Args, bool IsMemberFunction,
Alp Toker9cacbab2014-01-20 20:26:09 +00002342 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +00002343 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00002344 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00002345 if (CurContext->isDependentContext())
2346 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00002347
Ted Kremenekb8176da2010-09-09 04:33:05 +00002348 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00002349 llvm::SmallBitVector CheckedVarArgs;
2350 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002351 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002352 // Only create vector if there are format attributes.
2353 CheckedVarArgs.resize(Args.size());
2354
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002355 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00002356 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002357 }
Richard Smithd7293d72013-08-05 18:49:43 +00002358 }
Richard Smith55ce3522012-06-25 20:30:08 +00002359
2360 // Refuse POD arguments that weren't caught by the format string
2361 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +00002362 if (CallType != VariadicDoesNotApply) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002363 unsigned NumParams = Proto ? Proto->getNumParams()
2364 : FDecl && isa<FunctionDecl>(FDecl)
2365 ? cast<FunctionDecl>(FDecl)->getNumParams()
2366 : FDecl && isa<ObjCMethodDecl>(FDecl)
2367 ? cast<ObjCMethodDecl>(FDecl)->param_size()
2368 : 0;
2369
Alp Toker9cacbab2014-01-20 20:26:09 +00002370 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002371 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00002372 if (const Expr *Arg = Args[ArgIdx]) {
2373 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2374 checkVariadicArgument(Arg, CallType);
2375 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002376 }
Richard Smithd7293d72013-08-05 18:49:43 +00002377 }
Mike Stump11289f42009-09-09 15:08:12 +00002378
Douglas Gregorb4866e82015-06-19 18:13:19 +00002379 if (FDecl || Proto) {
2380 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002381
Richard Trieu41bc0992013-06-22 00:20:41 +00002382 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002383 if (FDecl) {
2384 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
2385 CheckArgumentWithTypeTag(I, Args.data());
2386 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002387 }
Richard Smith55ce3522012-06-25 20:30:08 +00002388}
2389
2390/// CheckConstructorCall - Check a constructor call for correctness and safety
2391/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002392void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2393 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002394 const FunctionProtoType *Proto,
2395 SourceLocation Loc) {
2396 VariadicCallType CallType =
2397 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Douglas Gregorb4866e82015-06-19 18:13:19 +00002398 checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(),
2399 CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00002400}
2401
2402/// CheckFunctionCall - Check a direct function call for various correctness
2403/// and safety properties not strictly enforced by the C type system.
2404bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2405 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002406 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2407 isa<CXXMethodDecl>(FDecl);
2408 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2409 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00002410 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2411 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00002412 Expr** Args = TheCall->getArgs();
2413 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +00002414 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002415 // If this is a call to a member operator, hide the first argument
2416 // from checkCall.
2417 // FIXME: Our choice of AST representation here is less than ideal.
2418 ++Args;
2419 --NumArgs;
2420 }
Douglas Gregorb4866e82015-06-19 18:13:19 +00002421 checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00002422 IsMemberFunction, TheCall->getRParenLoc(),
2423 TheCall->getCallee()->getSourceRange(), CallType);
2424
2425 IdentifierInfo *FnInfo = FDecl->getIdentifier();
2426 // None of the checks below are needed for functions that don't have
2427 // simple names (e.g., C++ conversion functions).
2428 if (!FnInfo)
2429 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002430
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00002431 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002432 if (getLangOpts().ObjC1)
2433 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00002434
Anna Zaks22122702012-01-17 00:37:07 +00002435 unsigned CMId = FDecl->getMemoryFunctionKind();
2436 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00002437 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00002438
Anna Zaks201d4892012-01-13 21:52:01 +00002439 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00002440 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00002441 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00002442 else if (CMId == Builtin::BIstrncat)
2443 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00002444 else
Anna Zaks22122702012-01-17 00:37:07 +00002445 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00002446
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002447 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00002448}
2449
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002450bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00002451 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00002452 VariadicCallType CallType =
2453 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002454
Douglas Gregorb4866e82015-06-19 18:13:19 +00002455 checkCall(Method, nullptr, Args,
2456 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
2457 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002458
2459 return false;
2460}
2461
Richard Trieu664c4c62013-06-20 21:03:13 +00002462bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2463 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00002464 QualType Ty;
2465 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002466 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002467 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002468 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002469 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002470 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002471
Douglas Gregorb4866e82015-06-19 18:13:19 +00002472 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2473 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002474 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002475
Richard Trieu664c4c62013-06-20 21:03:13 +00002476 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00002477 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00002478 CallType = VariadicDoesNotApply;
2479 } else if (Ty->isBlockPointerType()) {
2480 CallType = VariadicBlock;
2481 } else { // Ty->isFunctionPointerType()
2482 CallType = VariadicFunction;
2483 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002484
Douglas Gregorb4866e82015-06-19 18:13:19 +00002485 checkCall(NDecl, Proto,
2486 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2487 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00002488 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00002489
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002490 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00002491}
2492
Richard Trieu41bc0992013-06-22 00:20:41 +00002493/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2494/// such as function pointers returned from functions.
2495bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002496 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00002497 TheCall->getCallee());
Douglas Gregorb4866e82015-06-19 18:13:19 +00002498 checkCall(/*FDecl=*/nullptr, Proto,
Craig Topper8c2a2a02014-08-30 16:55:39 +00002499 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00002500 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00002501 TheCall->getCallee()->getSourceRange(), CallType);
2502
2503 return false;
2504}
2505
Tim Northovere94a34c2014-03-11 10:49:14 +00002506static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
JF Bastiendda2cb12016-04-18 18:01:49 +00002507 if (!llvm::isValidAtomicOrderingCABI(Ordering))
Tim Northovere94a34c2014-03-11 10:49:14 +00002508 return false;
2509
JF Bastiendda2cb12016-04-18 18:01:49 +00002510 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
Tim Northovere94a34c2014-03-11 10:49:14 +00002511 switch (Op) {
2512 case AtomicExpr::AO__c11_atomic_init:
2513 llvm_unreachable("There is no ordering argument for an init");
2514
2515 case AtomicExpr::AO__c11_atomic_load:
2516 case AtomicExpr::AO__atomic_load_n:
2517 case AtomicExpr::AO__atomic_load:
JF Bastiendda2cb12016-04-18 18:01:49 +00002518 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2519 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002520
2521 case AtomicExpr::AO__c11_atomic_store:
2522 case AtomicExpr::AO__atomic_store:
2523 case AtomicExpr::AO__atomic_store_n:
JF Bastiendda2cb12016-04-18 18:01:49 +00002524 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2525 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2526 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002527
2528 default:
2529 return true;
2530 }
2531}
2532
Richard Smithfeea8832012-04-12 05:08:17 +00002533ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2534 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002535 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2536 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002537
Richard Smithfeea8832012-04-12 05:08:17 +00002538 // All these operations take one of the following forms:
2539 enum {
2540 // C __c11_atomic_init(A *, C)
2541 Init,
2542 // C __c11_atomic_load(A *, int)
2543 Load,
2544 // void __atomic_load(A *, CP, int)
Eric Fiselier8d662442016-03-30 23:39:56 +00002545 LoadCopy,
2546 // void __atomic_store(A *, CP, int)
Richard Smithfeea8832012-04-12 05:08:17 +00002547 Copy,
2548 // C __c11_atomic_add(A *, M, int)
2549 Arithmetic,
2550 // C __atomic_exchange_n(A *, CP, int)
2551 Xchg,
2552 // void __atomic_exchange(A *, C *, CP, int)
2553 GNUXchg,
2554 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2555 C11CmpXchg,
2556 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2557 GNUCmpXchg
2558 } Form = Init;
Eric Fiselier8d662442016-03-30 23:39:56 +00002559 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2560 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
Richard Smithfeea8832012-04-12 05:08:17 +00002561 // where:
2562 // C is an appropriate type,
2563 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2564 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2565 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2566 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002567
Gabor Horvath98bd0982015-03-16 09:59:54 +00002568 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2569 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2570 AtomicExpr::AO__atomic_load,
2571 "need to update code for modified C11 atomics");
Richard Smithfeea8832012-04-12 05:08:17 +00002572 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
2573 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
2574 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2575 Op == AtomicExpr::AO__atomic_store_n ||
2576 Op == AtomicExpr::AO__atomic_exchange_n ||
2577 Op == AtomicExpr::AO__atomic_compare_exchange_n;
2578 bool IsAddSub = false;
2579
2580 switch (Op) {
2581 case AtomicExpr::AO__c11_atomic_init:
2582 Form = Init;
2583 break;
2584
2585 case AtomicExpr::AO__c11_atomic_load:
2586 case AtomicExpr::AO__atomic_load_n:
2587 Form = Load;
2588 break;
2589
Richard Smithfeea8832012-04-12 05:08:17 +00002590 case AtomicExpr::AO__atomic_load:
Eric Fiselier8d662442016-03-30 23:39:56 +00002591 Form = LoadCopy;
2592 break;
2593
2594 case AtomicExpr::AO__c11_atomic_store:
Richard Smithfeea8832012-04-12 05:08:17 +00002595 case AtomicExpr::AO__atomic_store:
2596 case AtomicExpr::AO__atomic_store_n:
2597 Form = Copy;
2598 break;
2599
2600 case AtomicExpr::AO__c11_atomic_fetch_add:
2601 case AtomicExpr::AO__c11_atomic_fetch_sub:
2602 case AtomicExpr::AO__atomic_fetch_add:
2603 case AtomicExpr::AO__atomic_fetch_sub:
2604 case AtomicExpr::AO__atomic_add_fetch:
2605 case AtomicExpr::AO__atomic_sub_fetch:
2606 IsAddSub = true;
2607 // Fall through.
2608 case AtomicExpr::AO__c11_atomic_fetch_and:
2609 case AtomicExpr::AO__c11_atomic_fetch_or:
2610 case AtomicExpr::AO__c11_atomic_fetch_xor:
2611 case AtomicExpr::AO__atomic_fetch_and:
2612 case AtomicExpr::AO__atomic_fetch_or:
2613 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00002614 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00002615 case AtomicExpr::AO__atomic_and_fetch:
2616 case AtomicExpr::AO__atomic_or_fetch:
2617 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00002618 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00002619 Form = Arithmetic;
2620 break;
2621
2622 case AtomicExpr::AO__c11_atomic_exchange:
2623 case AtomicExpr::AO__atomic_exchange_n:
2624 Form = Xchg;
2625 break;
2626
2627 case AtomicExpr::AO__atomic_exchange:
2628 Form = GNUXchg;
2629 break;
2630
2631 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
2632 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
2633 Form = C11CmpXchg;
2634 break;
2635
2636 case AtomicExpr::AO__atomic_compare_exchange:
2637 case AtomicExpr::AO__atomic_compare_exchange_n:
2638 Form = GNUCmpXchg;
2639 break;
2640 }
2641
2642 // Check we have the right number of arguments.
2643 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002644 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00002645 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002646 << TheCall->getCallee()->getSourceRange();
2647 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00002648 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
2649 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002650 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00002651 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002652 << TheCall->getCallee()->getSourceRange();
2653 return ExprError();
2654 }
2655
Richard Smithfeea8832012-04-12 05:08:17 +00002656 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002657 Expr *Ptr = TheCall->getArg(0);
George Burgess IV92b43a42016-07-21 03:28:13 +00002658 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
2659 if (ConvertedPtr.isInvalid())
2660 return ExprError();
2661
2662 Ptr = ConvertedPtr.get();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002663 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
2664 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00002665 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002666 << Ptr->getType() << Ptr->getSourceRange();
2667 return ExprError();
2668 }
2669
Richard Smithfeea8832012-04-12 05:08:17 +00002670 // For a __c11 builtin, this should be a pointer to an _Atomic type.
2671 QualType AtomTy = pointerType->getPointeeType(); // 'A'
2672 QualType ValType = AtomTy; // 'C'
2673 if (IsC11) {
2674 if (!AtomTy->isAtomicType()) {
2675 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
2676 << Ptr->getType() << Ptr->getSourceRange();
2677 return ExprError();
2678 }
Richard Smithe00921a2012-09-15 06:09:58 +00002679 if (AtomTy.isConstQualified()) {
2680 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
2681 << Ptr->getType() << Ptr->getSourceRange();
2682 return ExprError();
2683 }
Richard Smithfeea8832012-04-12 05:08:17 +00002684 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiselier8d662442016-03-30 23:39:56 +00002685 } else if (Form != Load && Form != LoadCopy) {
Eric Fiseliera3a7c562015-10-04 00:11:02 +00002686 if (ValType.isConstQualified()) {
2687 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
2688 << Ptr->getType() << Ptr->getSourceRange();
2689 return ExprError();
2690 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002691 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002692
Richard Smithfeea8832012-04-12 05:08:17 +00002693 // For an arithmetic operation, the implied arithmetic must be well-formed.
2694 if (Form == Arithmetic) {
2695 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
2696 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
2697 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2698 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2699 return ExprError();
2700 }
2701 if (!IsAddSub && !ValType->isIntegerType()) {
2702 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
2703 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2704 return ExprError();
2705 }
David Majnemere85cff82015-01-28 05:48:06 +00002706 if (IsC11 && ValType->isPointerType() &&
2707 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
2708 diag::err_incomplete_type)) {
2709 return ExprError();
2710 }
Richard Smithfeea8832012-04-12 05:08:17 +00002711 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
2712 // For __atomic_*_n operations, the value type must be a scalar integral or
2713 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002714 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00002715 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2716 return ExprError();
2717 }
2718
Eli Friedmanaa769812013-09-11 03:49:34 +00002719 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
2720 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00002721 // For GNU atomics, require a trivially-copyable type. This is not part of
2722 // the GNU atomics specification, but we enforce it for sanity.
2723 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002724 << Ptr->getType() << Ptr->getSourceRange();
2725 return ExprError();
2726 }
2727
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002728 switch (ValType.getObjCLifetime()) {
2729 case Qualifiers::OCL_None:
2730 case Qualifiers::OCL_ExplicitNone:
2731 // okay
2732 break;
2733
2734 case Qualifiers::OCL_Weak:
2735 case Qualifiers::OCL_Strong:
2736 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00002737 // FIXME: Can this happen? By this point, ValType should be known
2738 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002739 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
2740 << ValType << Ptr->getSourceRange();
2741 return ExprError();
2742 }
2743
David Majnemerc6eb6502015-06-03 00:26:35 +00002744 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
2745 // volatile-ness of the pointee-type inject itself into the result or the
Eric Fiselier8d662442016-03-30 23:39:56 +00002746 // other operands. Similarly atomic_load can take a pointer to a const 'A'.
David Majnemerc6eb6502015-06-03 00:26:35 +00002747 ValType.removeLocalVolatile();
Eric Fiselier8d662442016-03-30 23:39:56 +00002748 ValType.removeLocalConst();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002749 QualType ResultType = ValType;
Eric Fiselier8d662442016-03-30 23:39:56 +00002750 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002751 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00002752 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002753 ResultType = Context.BoolTy;
2754
Richard Smithfeea8832012-04-12 05:08:17 +00002755 // The type of a parameter passed 'by value'. In the GNU atomics, such
2756 // arguments are actually passed as pointers.
2757 QualType ByValType = ValType; // 'CP'
2758 if (!IsC11 && !IsN)
2759 ByValType = Ptr->getType();
2760
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002761 // The first argument --- the pointer --- has a fixed type; we
2762 // deduce the types of the rest of the arguments accordingly. Walk
2763 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00002764 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002765 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00002766 if (i < NumVals[Form] + 1) {
2767 switch (i) {
2768 case 1:
2769 // The second argument is the non-atomic operand. For arithmetic, this
2770 // is always passed by value, and for a compare_exchange it is always
2771 // passed by address. For the rest, GNU uses by-address and C11 uses
2772 // by-value.
2773 assert(Form != Load);
2774 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
2775 Ty = ValType;
2776 else if (Form == Copy || Form == Xchg)
2777 Ty = ByValType;
2778 else if (Form == Arithmetic)
2779 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00002780 else {
2781 Expr *ValArg = TheCall->getArg(i);
2782 unsigned AS = 0;
2783 // Keep address space of non-atomic pointer type.
2784 if (const PointerType *PtrTy =
2785 ValArg->getType()->getAs<PointerType>()) {
2786 AS = PtrTy->getPointeeType().getAddressSpace();
2787 }
2788 Ty = Context.getPointerType(
2789 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
2790 }
Richard Smithfeea8832012-04-12 05:08:17 +00002791 break;
2792 case 2:
2793 // The third argument to compare_exchange / GNU exchange is a
2794 // (pointer to a) desired value.
2795 Ty = ByValType;
2796 break;
2797 case 3:
2798 // The fourth argument to GNU compare_exchange is a 'weak' flag.
2799 Ty = Context.BoolTy;
2800 break;
2801 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002802 } else {
2803 // The order(s) are always converted to int.
2804 Ty = Context.IntTy;
2805 }
Richard Smithfeea8832012-04-12 05:08:17 +00002806
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002807 InitializedEntity Entity =
2808 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00002809 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002810 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2811 if (Arg.isInvalid())
2812 return true;
2813 TheCall->setArg(i, Arg.get());
2814 }
2815
Richard Smithfeea8832012-04-12 05:08:17 +00002816 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002817 SmallVector<Expr*, 5> SubExprs;
2818 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00002819 switch (Form) {
2820 case Init:
2821 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00002822 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00002823 break;
2824 case Load:
2825 SubExprs.push_back(TheCall->getArg(1)); // Order
2826 break;
Eric Fiselier8d662442016-03-30 23:39:56 +00002827 case LoadCopy:
Richard Smithfeea8832012-04-12 05:08:17 +00002828 case Copy:
2829 case Arithmetic:
2830 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002831 SubExprs.push_back(TheCall->getArg(2)); // Order
2832 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00002833 break;
2834 case GNUXchg:
2835 // Note, AtomicExpr::getVal2() has a special case for this atomic.
2836 SubExprs.push_back(TheCall->getArg(3)); // Order
2837 SubExprs.push_back(TheCall->getArg(1)); // Val1
2838 SubExprs.push_back(TheCall->getArg(2)); // Val2
2839 break;
2840 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002841 SubExprs.push_back(TheCall->getArg(3)); // Order
2842 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002843 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00002844 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00002845 break;
2846 case GNUCmpXchg:
2847 SubExprs.push_back(TheCall->getArg(4)); // Order
2848 SubExprs.push_back(TheCall->getArg(1)); // Val1
2849 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
2850 SubExprs.push_back(TheCall->getArg(2)); // Val2
2851 SubExprs.push_back(TheCall->getArg(3)); // Weak
2852 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002853 }
Tim Northovere94a34c2014-03-11 10:49:14 +00002854
2855 if (SubExprs.size() >= 2 && Form != Init) {
2856 llvm::APSInt Result(32);
2857 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
2858 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00002859 Diag(SubExprs[1]->getLocStart(),
2860 diag::warn_atomic_op_has_invalid_memory_order)
2861 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00002862 }
2863
Fariborz Jahanian615de762013-05-28 17:37:39 +00002864 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
2865 SubExprs, ResultType, Op,
2866 TheCall->getRParenLoc());
2867
2868 if ((Op == AtomicExpr::AO__c11_atomic_load ||
2869 (Op == AtomicExpr::AO__c11_atomic_store)) &&
2870 Context.AtomicUsesUnsupportedLibcall(AE))
2871 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
2872 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002873
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002874 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002875}
2876
John McCall29ad95b2011-08-27 01:09:30 +00002877/// checkBuiltinArgument - Given a call to a builtin function, perform
2878/// normal type-checking on the given argument, updating the call in
2879/// place. This is useful when a builtin function requires custom
2880/// type-checking for some of its arguments but not necessarily all of
2881/// them.
2882///
2883/// Returns true on error.
2884static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
2885 FunctionDecl *Fn = E->getDirectCallee();
2886 assert(Fn && "builtin call without direct callee!");
2887
2888 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
2889 InitializedEntity Entity =
2890 InitializedEntity::InitializeParameter(S.Context, Param);
2891
2892 ExprResult Arg = E->getArg(0);
2893 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
2894 if (Arg.isInvalid())
2895 return true;
2896
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002897 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00002898 return false;
2899}
2900
Chris Lattnerdc046542009-05-08 06:58:22 +00002901/// SemaBuiltinAtomicOverloaded - We have a call to a function like
2902/// __sync_fetch_and_add, which is an overloaded function based on the pointer
2903/// type of its first argument. The main ActOnCallExpr routines have already
2904/// promoted the types of arguments because all of these calls are prototyped as
2905/// void(...).
2906///
2907/// This function goes through and does final semantic checking for these
2908/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00002909ExprResult
2910Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002911 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00002912 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2913 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2914
2915 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002916 if (TheCall->getNumArgs() < 1) {
2917 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2918 << 0 << 1 << TheCall->getNumArgs()
2919 << TheCall->getCallee()->getSourceRange();
2920 return ExprError();
2921 }
Mike Stump11289f42009-09-09 15:08:12 +00002922
Chris Lattnerdc046542009-05-08 06:58:22 +00002923 // Inspect the first argument of the atomic builtin. This should always be
2924 // a pointer type, whose element is an integral scalar or pointer type.
2925 // Because it is a pointer type, we don't have to worry about any implicit
2926 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002927 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00002928 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00002929 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
2930 if (FirstArgResult.isInvalid())
2931 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002932 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00002933 TheCall->setArg(0, FirstArg);
2934
John McCall31168b02011-06-15 23:02:42 +00002935 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
2936 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002937 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
2938 << FirstArg->getType() << FirstArg->getSourceRange();
2939 return ExprError();
2940 }
Mike Stump11289f42009-09-09 15:08:12 +00002941
John McCall31168b02011-06-15 23:02:42 +00002942 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00002943 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002944 !ValType->isBlockPointerType()) {
2945 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
2946 << FirstArg->getType() << FirstArg->getSourceRange();
2947 return ExprError();
2948 }
Chris Lattnerdc046542009-05-08 06:58:22 +00002949
John McCall31168b02011-06-15 23:02:42 +00002950 switch (ValType.getObjCLifetime()) {
2951 case Qualifiers::OCL_None:
2952 case Qualifiers::OCL_ExplicitNone:
2953 // okay
2954 break;
2955
2956 case Qualifiers::OCL_Weak:
2957 case Qualifiers::OCL_Strong:
2958 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00002959 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00002960 << ValType << FirstArg->getSourceRange();
2961 return ExprError();
2962 }
2963
John McCallb50451a2011-10-05 07:41:44 +00002964 // Strip any qualifiers off ValType.
2965 ValType = ValType.getUnqualifiedType();
2966
Chandler Carruth3973af72010-07-18 20:54:12 +00002967 // The majority of builtins return a value, but a few have special return
2968 // types, so allow them to override appropriately below.
2969 QualType ResultType = ValType;
2970
Chris Lattnerdc046542009-05-08 06:58:22 +00002971 // We need to figure out which concrete builtin this maps onto. For example,
2972 // __sync_fetch_and_add with a 2 byte object turns into
2973 // __sync_fetch_and_add_2.
2974#define BUILTIN_ROW(x) \
2975 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
2976 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00002977
Chris Lattnerdc046542009-05-08 06:58:22 +00002978 static const unsigned BuiltinIndices[][5] = {
2979 BUILTIN_ROW(__sync_fetch_and_add),
2980 BUILTIN_ROW(__sync_fetch_and_sub),
2981 BUILTIN_ROW(__sync_fetch_and_or),
2982 BUILTIN_ROW(__sync_fetch_and_and),
2983 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00002984 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00002985
Chris Lattnerdc046542009-05-08 06:58:22 +00002986 BUILTIN_ROW(__sync_add_and_fetch),
2987 BUILTIN_ROW(__sync_sub_and_fetch),
2988 BUILTIN_ROW(__sync_and_and_fetch),
2989 BUILTIN_ROW(__sync_or_and_fetch),
2990 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00002991 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00002992
Chris Lattnerdc046542009-05-08 06:58:22 +00002993 BUILTIN_ROW(__sync_val_compare_and_swap),
2994 BUILTIN_ROW(__sync_bool_compare_and_swap),
2995 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00002996 BUILTIN_ROW(__sync_lock_release),
2997 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00002998 };
Mike Stump11289f42009-09-09 15:08:12 +00002999#undef BUILTIN_ROW
3000
Chris Lattnerdc046542009-05-08 06:58:22 +00003001 // Determine the index of the size.
3002 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00003003 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00003004 case 1: SizeIndex = 0; break;
3005 case 2: SizeIndex = 1; break;
3006 case 4: SizeIndex = 2; break;
3007 case 8: SizeIndex = 3; break;
3008 case 16: SizeIndex = 4; break;
3009 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003010 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3011 << FirstArg->getType() << FirstArg->getSourceRange();
3012 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00003013 }
Mike Stump11289f42009-09-09 15:08:12 +00003014
Chris Lattnerdc046542009-05-08 06:58:22 +00003015 // Each of these builtins has one pointer argument, followed by some number of
3016 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3017 // that we ignore. Find out which row of BuiltinIndices to read from as well
3018 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00003019 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00003020 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00003021 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00003022 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00003023 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00003024 case Builtin::BI__sync_fetch_and_add:
3025 case Builtin::BI__sync_fetch_and_add_1:
3026 case Builtin::BI__sync_fetch_and_add_2:
3027 case Builtin::BI__sync_fetch_and_add_4:
3028 case Builtin::BI__sync_fetch_and_add_8:
3029 case Builtin::BI__sync_fetch_and_add_16:
3030 BuiltinIndex = 0;
3031 break;
3032
3033 case Builtin::BI__sync_fetch_and_sub:
3034 case Builtin::BI__sync_fetch_and_sub_1:
3035 case Builtin::BI__sync_fetch_and_sub_2:
3036 case Builtin::BI__sync_fetch_and_sub_4:
3037 case Builtin::BI__sync_fetch_and_sub_8:
3038 case Builtin::BI__sync_fetch_and_sub_16:
3039 BuiltinIndex = 1;
3040 break;
3041
3042 case Builtin::BI__sync_fetch_and_or:
3043 case Builtin::BI__sync_fetch_and_or_1:
3044 case Builtin::BI__sync_fetch_and_or_2:
3045 case Builtin::BI__sync_fetch_and_or_4:
3046 case Builtin::BI__sync_fetch_and_or_8:
3047 case Builtin::BI__sync_fetch_and_or_16:
3048 BuiltinIndex = 2;
3049 break;
3050
3051 case Builtin::BI__sync_fetch_and_and:
3052 case Builtin::BI__sync_fetch_and_and_1:
3053 case Builtin::BI__sync_fetch_and_and_2:
3054 case Builtin::BI__sync_fetch_and_and_4:
3055 case Builtin::BI__sync_fetch_and_and_8:
3056 case Builtin::BI__sync_fetch_and_and_16:
3057 BuiltinIndex = 3;
3058 break;
Mike Stump11289f42009-09-09 15:08:12 +00003059
Douglas Gregor73722482011-11-28 16:30:08 +00003060 case Builtin::BI__sync_fetch_and_xor:
3061 case Builtin::BI__sync_fetch_and_xor_1:
3062 case Builtin::BI__sync_fetch_and_xor_2:
3063 case Builtin::BI__sync_fetch_and_xor_4:
3064 case Builtin::BI__sync_fetch_and_xor_8:
3065 case Builtin::BI__sync_fetch_and_xor_16:
3066 BuiltinIndex = 4;
3067 break;
3068
Hal Finkeld2208b52014-10-02 20:53:50 +00003069 case Builtin::BI__sync_fetch_and_nand:
3070 case Builtin::BI__sync_fetch_and_nand_1:
3071 case Builtin::BI__sync_fetch_and_nand_2:
3072 case Builtin::BI__sync_fetch_and_nand_4:
3073 case Builtin::BI__sync_fetch_and_nand_8:
3074 case Builtin::BI__sync_fetch_and_nand_16:
3075 BuiltinIndex = 5;
3076 WarnAboutSemanticsChange = true;
3077 break;
3078
Douglas Gregor73722482011-11-28 16:30:08 +00003079 case Builtin::BI__sync_add_and_fetch:
3080 case Builtin::BI__sync_add_and_fetch_1:
3081 case Builtin::BI__sync_add_and_fetch_2:
3082 case Builtin::BI__sync_add_and_fetch_4:
3083 case Builtin::BI__sync_add_and_fetch_8:
3084 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003085 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00003086 break;
3087
3088 case Builtin::BI__sync_sub_and_fetch:
3089 case Builtin::BI__sync_sub_and_fetch_1:
3090 case Builtin::BI__sync_sub_and_fetch_2:
3091 case Builtin::BI__sync_sub_and_fetch_4:
3092 case Builtin::BI__sync_sub_and_fetch_8:
3093 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003094 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00003095 break;
3096
3097 case Builtin::BI__sync_and_and_fetch:
3098 case Builtin::BI__sync_and_and_fetch_1:
3099 case Builtin::BI__sync_and_and_fetch_2:
3100 case Builtin::BI__sync_and_and_fetch_4:
3101 case Builtin::BI__sync_and_and_fetch_8:
3102 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003103 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00003104 break;
3105
3106 case Builtin::BI__sync_or_and_fetch:
3107 case Builtin::BI__sync_or_and_fetch_1:
3108 case Builtin::BI__sync_or_and_fetch_2:
3109 case Builtin::BI__sync_or_and_fetch_4:
3110 case Builtin::BI__sync_or_and_fetch_8:
3111 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003112 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00003113 break;
3114
3115 case Builtin::BI__sync_xor_and_fetch:
3116 case Builtin::BI__sync_xor_and_fetch_1:
3117 case Builtin::BI__sync_xor_and_fetch_2:
3118 case Builtin::BI__sync_xor_and_fetch_4:
3119 case Builtin::BI__sync_xor_and_fetch_8:
3120 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003121 BuiltinIndex = 10;
3122 break;
3123
3124 case Builtin::BI__sync_nand_and_fetch:
3125 case Builtin::BI__sync_nand_and_fetch_1:
3126 case Builtin::BI__sync_nand_and_fetch_2:
3127 case Builtin::BI__sync_nand_and_fetch_4:
3128 case Builtin::BI__sync_nand_and_fetch_8:
3129 case Builtin::BI__sync_nand_and_fetch_16:
3130 BuiltinIndex = 11;
3131 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00003132 break;
Mike Stump11289f42009-09-09 15:08:12 +00003133
Chris Lattnerdc046542009-05-08 06:58:22 +00003134 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003135 case Builtin::BI__sync_val_compare_and_swap_1:
3136 case Builtin::BI__sync_val_compare_and_swap_2:
3137 case Builtin::BI__sync_val_compare_and_swap_4:
3138 case Builtin::BI__sync_val_compare_and_swap_8:
3139 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003140 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00003141 NumFixed = 2;
3142 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003143
Chris Lattnerdc046542009-05-08 06:58:22 +00003144 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003145 case Builtin::BI__sync_bool_compare_and_swap_1:
3146 case Builtin::BI__sync_bool_compare_and_swap_2:
3147 case Builtin::BI__sync_bool_compare_and_swap_4:
3148 case Builtin::BI__sync_bool_compare_and_swap_8:
3149 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003150 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00003151 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00003152 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003153 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003154
3155 case Builtin::BI__sync_lock_test_and_set:
3156 case Builtin::BI__sync_lock_test_and_set_1:
3157 case Builtin::BI__sync_lock_test_and_set_2:
3158 case Builtin::BI__sync_lock_test_and_set_4:
3159 case Builtin::BI__sync_lock_test_and_set_8:
3160 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003161 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00003162 break;
3163
Chris Lattnerdc046542009-05-08 06:58:22 +00003164 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00003165 case Builtin::BI__sync_lock_release_1:
3166 case Builtin::BI__sync_lock_release_2:
3167 case Builtin::BI__sync_lock_release_4:
3168 case Builtin::BI__sync_lock_release_8:
3169 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003170 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00003171 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00003172 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003173 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003174
3175 case Builtin::BI__sync_swap:
3176 case Builtin::BI__sync_swap_1:
3177 case Builtin::BI__sync_swap_2:
3178 case Builtin::BI__sync_swap_4:
3179 case Builtin::BI__sync_swap_8:
3180 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003181 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00003182 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00003183 }
Mike Stump11289f42009-09-09 15:08:12 +00003184
Chris Lattnerdc046542009-05-08 06:58:22 +00003185 // Now that we know how many fixed arguments we expect, first check that we
3186 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003187 if (TheCall->getNumArgs() < 1+NumFixed) {
3188 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3189 << 0 << 1+NumFixed << TheCall->getNumArgs()
3190 << TheCall->getCallee()->getSourceRange();
3191 return ExprError();
3192 }
Mike Stump11289f42009-09-09 15:08:12 +00003193
Hal Finkeld2208b52014-10-02 20:53:50 +00003194 if (WarnAboutSemanticsChange) {
3195 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3196 << TheCall->getCallee()->getSourceRange();
3197 }
3198
Chris Lattner5b9241b2009-05-08 15:36:58 +00003199 // Get the decl for the concrete builtin from this, we can tell what the
3200 // concrete integer type we should convert to is.
3201 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003202 FunctionDecl *NewBuiltinDecl;
3203 if (NewBuiltinID == BuiltinID)
3204 NewBuiltinDecl = FDecl;
3205 else {
3206 // Perform builtin lookup to avoid redeclaring it.
Mehdi Aminib1bdc472016-10-10 21:34:29 +00003207 StringRef NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003208 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3209 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3210 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3211 assert(Res.getFoundDecl());
3212 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00003213 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003214 return ExprError();
3215 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003216
John McCallcf142162010-08-07 06:22:56 +00003217 // The first argument --- the pointer --- has a fixed type; we
3218 // deduce the types of the rest of the arguments accordingly. Walk
3219 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00003220 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00003221 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00003222
Chris Lattnerdc046542009-05-08 06:58:22 +00003223 // GCC does an implicit conversion to the pointer or integer ValType. This
3224 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00003225 // Initialize the argument.
3226 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3227 ValType, /*consume*/ false);
3228 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00003229 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003230 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003231
Chris Lattnerdc046542009-05-08 06:58:22 +00003232 // Okay, we have something that *can* be converted to the right type. Check
3233 // to see if there is a potentially weird extension going on here. This can
3234 // happen when you do an atomic operation on something like an char* and
3235 // pass in 42. The 42 gets converted to char. This is even more strange
3236 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00003237 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003238 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00003239 }
Mike Stump11289f42009-09-09 15:08:12 +00003240
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003241 ASTContext& Context = this->getASTContext();
3242
3243 // Create a new DeclRefExpr to refer to the new decl.
3244 DeclRefExpr* NewDRE = DeclRefExpr::Create(
3245 Context,
3246 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00003247 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003248 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00003249 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003250 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00003251 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003252 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00003253
Chris Lattnerdc046542009-05-08 06:58:22 +00003254 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00003255 // FIXME: This loses syntactic information.
3256 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
3257 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3258 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003259 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00003260
Chandler Carruthbc8cab12010-07-18 07:23:17 +00003261 // Change the result type of the call to match the original value type. This
3262 // is arbitrary, but the codegen for these builtins ins design to handle it
3263 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00003264 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003265
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003266 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00003267}
3268
Michael Zolotukhin84df1232015-09-08 23:52:33 +00003269/// SemaBuiltinNontemporalOverloaded - We have a call to
3270/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3271/// overloaded function based on the pointer type of its last argument.
3272///
3273/// This function goes through and does final semantic checking for these
3274/// builtins.
3275ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3276 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3277 DeclRefExpr *DRE =
3278 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3279 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3280 unsigned BuiltinID = FDecl->getBuiltinID();
3281 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3282 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3283 "Unexpected nontemporal load/store builtin!");
3284 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3285 unsigned numArgs = isStore ? 2 : 1;
3286
3287 // Ensure that we have the proper number of arguments.
3288 if (checkArgCount(*this, TheCall, numArgs))
3289 return ExprError();
3290
3291 // Inspect the last argument of the nontemporal builtin. This should always
3292 // be a pointer type, from which we imply the type of the memory access.
3293 // Because it is a pointer type, we don't have to worry about any implicit
3294 // casts here.
3295 Expr *PointerArg = TheCall->getArg(numArgs - 1);
3296 ExprResult PointerArgResult =
3297 DefaultFunctionArrayLvalueConversion(PointerArg);
3298
3299 if (PointerArgResult.isInvalid())
3300 return ExprError();
3301 PointerArg = PointerArgResult.get();
3302 TheCall->setArg(numArgs - 1, PointerArg);
3303
3304 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3305 if (!pointerType) {
3306 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3307 << PointerArg->getType() << PointerArg->getSourceRange();
3308 return ExprError();
3309 }
3310
3311 QualType ValType = pointerType->getPointeeType();
3312
3313 // Strip any qualifiers off ValType.
3314 ValType = ValType.getUnqualifiedType();
3315 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3316 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3317 !ValType->isVectorType()) {
3318 Diag(DRE->getLocStart(),
3319 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3320 << PointerArg->getType() << PointerArg->getSourceRange();
3321 return ExprError();
3322 }
3323
3324 if (!isStore) {
3325 TheCall->setType(ValType);
3326 return TheCallResult;
3327 }
3328
3329 ExprResult ValArg = TheCall->getArg(0);
3330 InitializedEntity Entity = InitializedEntity::InitializeParameter(
3331 Context, ValType, /*consume*/ false);
3332 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3333 if (ValArg.isInvalid())
3334 return ExprError();
3335
3336 TheCall->setArg(0, ValArg.get());
3337 TheCall->setType(Context.VoidTy);
3338 return TheCallResult;
3339}
3340
Chris Lattner6436fb62009-02-18 06:01:06 +00003341/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00003342/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00003343/// Note: It might also make sense to do the UTF-16 conversion here (would
3344/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00003345bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00003346 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00003347 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3348
Douglas Gregorfb65e592011-07-27 05:40:30 +00003349 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003350 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3351 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00003352 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00003353 }
Mike Stump11289f42009-09-09 15:08:12 +00003354
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003355 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003356 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003357 unsigned NumBytes = String.size();
Justin Lebar90910552016-09-30 00:38:45 +00003358 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
3359 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3360 llvm::UTF16 *ToPtr = &ToBuf[0];
3361
3362 llvm::ConversionResult Result =
3363 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3364 ToPtr + NumBytes, llvm::strictConversion);
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003365 // Check for conversion failure.
Justin Lebar90910552016-09-30 00:38:45 +00003366 if (Result != llvm::conversionOK)
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003367 Diag(Arg->getLocStart(),
3368 diag::warn_cfstring_truncated) << Arg->getSourceRange();
3369 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00003370 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003371}
3372
Charles Davisc7d5c942015-09-17 20:55:33 +00003373/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3374/// for validity. Emit an error and return true on failure; return false
3375/// on success.
3376bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00003377 Expr *Fn = TheCall->getCallee();
3378 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00003379 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003380 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003381 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3382 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00003383 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003384 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00003385 return true;
3386 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003387
3388 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00003389 return Diag(TheCall->getLocEnd(),
3390 diag::err_typecheck_call_too_few_args_at_least)
3391 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003392 }
3393
John McCall29ad95b2011-08-27 01:09:30 +00003394 // Type-check the first argument normally.
3395 if (checkBuiltinArgument(*this, TheCall, 0))
3396 return true;
3397
Chris Lattnere202e6a2007-12-20 00:05:45 +00003398 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00003399 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00003400 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00003401 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00003402 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00003403 else if (FunctionDecl *FD = getCurFunctionDecl())
3404 isVariadic = FD->isVariadic();
3405 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00003406 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00003407
Chris Lattnere202e6a2007-12-20 00:05:45 +00003408 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00003409 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3410 return true;
3411 }
Mike Stump11289f42009-09-09 15:08:12 +00003412
Chris Lattner43be2e62007-12-19 23:59:04 +00003413 // Verify that the second argument to the builtin is the last argument of the
3414 // current function or method.
3415 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00003416 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00003417
Nico Weber9eea7642013-05-24 23:31:57 +00003418 // These are valid if SecondArgIsLastNamedArgument is false after the next
3419 // block.
3420 QualType Type;
3421 SourceLocation ParamLoc;
Aaron Ballman1de59c52016-04-24 13:30:21 +00003422 bool IsCRegister = false;
Nico Weber9eea7642013-05-24 23:31:57 +00003423
Anders Carlsson6a8350b2008-02-11 04:20:54 +00003424 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3425 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00003426 // FIXME: This isn't correct for methods (results in bogus warning).
3427 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00003428 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00003429 if (CurBlock)
David Majnemera3debed2016-06-24 05:33:44 +00003430 LastArg = CurBlock->TheDecl->parameters().back();
Steve Naroff439a3e42009-04-15 19:33:47 +00003431 else if (FunctionDecl *FD = getCurFunctionDecl())
David Majnemera3debed2016-06-24 05:33:44 +00003432 LastArg = FD->parameters().back();
Chris Lattner43be2e62007-12-19 23:59:04 +00003433 else
David Majnemera3debed2016-06-24 05:33:44 +00003434 LastArg = getCurMethodDecl()->parameters().back();
Chris Lattner43be2e62007-12-19 23:59:04 +00003435 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00003436
3437 Type = PV->getType();
3438 ParamLoc = PV->getLocation();
Aaron Ballman1de59c52016-04-24 13:30:21 +00003439 IsCRegister =
3440 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
Chris Lattner43be2e62007-12-19 23:59:04 +00003441 }
3442 }
Mike Stump11289f42009-09-09 15:08:12 +00003443
Chris Lattner43be2e62007-12-19 23:59:04 +00003444 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00003445 Diag(TheCall->getArg(1)->getLocStart(),
Aaron Ballman05164812016-04-18 18:10:53 +00003446 diag::warn_second_arg_of_va_start_not_last_named_param);
Aaron Ballman1de59c52016-04-24 13:30:21 +00003447 else if (IsCRegister || Type->isReferenceType() ||
Aaron Ballmana4f597f2016-09-15 18:07:51 +00003448 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
3449 // Promotable integers are UB, but enumerations need a bit of
3450 // extra checking to see what their promotable type actually is.
3451 if (!Type->isPromotableIntegerType())
3452 return false;
3453 if (!Type->isEnumeralType())
3454 return true;
3455 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3456 return !(ED &&
3457 Context.typesAreCompatible(ED->getPromotionType(), Type));
3458 }()) {
Aaron Ballman1de59c52016-04-24 13:30:21 +00003459 unsigned Reason = 0;
3460 if (Type->isReferenceType()) Reason = 1;
3461 else if (IsCRegister) Reason = 2;
3462 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
Nico Weber9eea7642013-05-24 23:31:57 +00003463 Diag(ParamLoc, diag::note_parameter_type) << Type;
3464 }
3465
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00003466 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00003467 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00003468}
Chris Lattner43be2e62007-12-19 23:59:04 +00003469
Charles Davisc7d5c942015-09-17 20:55:33 +00003470/// Check the arguments to '__builtin_va_start' for validity, and that
3471/// it was called from a function of the native ABI.
3472/// Emit an error and return true on failure; return false on success.
3473bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
3474 // On x86-64 Unix, don't allow this in Win64 ABI functions.
3475 // On x64 Windows, don't allow this in System V ABI functions.
3476 // (Yes, that means there's no corresponding way to support variadic
3477 // System V ABI functions on Windows.)
3478 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) {
3479 unsigned OS = Context.getTargetInfo().getTriple().getOS();
3480 clang::CallingConv CC = CC_C;
3481 if (const FunctionDecl *FD = getCurFunctionDecl())
3482 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3483 if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) ||
3484 (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64))
3485 return Diag(TheCall->getCallee()->getLocStart(),
3486 diag::err_va_start_used_in_wrong_abi_function)
3487 << (OS != llvm::Triple::Win32);
3488 }
3489 return SemaBuiltinVAStartImpl(TheCall);
3490}
3491
3492/// Check the arguments to '__builtin_ms_va_start' for validity, and that
3493/// it was called from a Win64 ABI function.
3494/// Emit an error and return true on failure; return false on success.
3495bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) {
3496 // This only makes sense for x86-64.
3497 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3498 Expr *Callee = TheCall->getCallee();
3499 if (TT.getArch() != llvm::Triple::x86_64)
3500 return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt);
3501 // Don't allow this in System V ABI functions.
3502 clang::CallingConv CC = CC_C;
3503 if (const FunctionDecl *FD = getCurFunctionDecl())
3504 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3505 if (CC == CC_X86_64SysV ||
3506 (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64))
3507 return Diag(Callee->getLocStart(),
3508 diag::err_ms_va_start_used_in_sysv_function);
3509 return SemaBuiltinVAStartImpl(TheCall);
3510}
3511
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003512bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
3513 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
3514 // const char *named_addr);
3515
3516 Expr *Func = Call->getCallee();
3517
3518 if (Call->getNumArgs() < 3)
3519 return Diag(Call->getLocEnd(),
3520 diag::err_typecheck_call_too_few_args_at_least)
3521 << 0 /*function call*/ << 3 << Call->getNumArgs();
3522
3523 // Determine whether the current function is variadic or not.
3524 bool IsVariadic;
3525 if (BlockScopeInfo *CurBlock = getCurBlock())
3526 IsVariadic = CurBlock->TheDecl->isVariadic();
3527 else if (FunctionDecl *FD = getCurFunctionDecl())
3528 IsVariadic = FD->isVariadic();
3529 else if (ObjCMethodDecl *MD = getCurMethodDecl())
3530 IsVariadic = MD->isVariadic();
3531 else
3532 llvm_unreachable("unexpected statement type");
3533
3534 if (!IsVariadic) {
3535 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3536 return true;
3537 }
3538
3539 // Type-check the first argument normally.
3540 if (checkBuiltinArgument(*this, Call, 0))
3541 return true;
3542
Benjamin Kramere0ca6e12015-03-01 18:09:50 +00003543 const struct {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003544 unsigned ArgNo;
3545 QualType Type;
3546 } ArgumentTypes[] = {
3547 { 1, Context.getPointerType(Context.CharTy.withConst()) },
3548 { 2, Context.getSizeType() },
3549 };
3550
3551 for (const auto &AT : ArgumentTypes) {
3552 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
3553 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
3554 continue;
3555 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
3556 << Arg->getType() << AT.Type << 1 /* different class */
3557 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
3558 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
3559 }
3560
3561 return false;
3562}
3563
Chris Lattner2da14fb2007-12-20 00:26:33 +00003564/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
3565/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00003566bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
3567 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00003568 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00003569 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00003570 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00003571 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003572 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003573 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00003574 << SourceRange(TheCall->getArg(2)->getLocStart(),
3575 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003576
John Wiegley01296292011-04-08 18:41:53 +00003577 ExprResult OrigArg0 = TheCall->getArg(0);
3578 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00003579
Chris Lattner2da14fb2007-12-20 00:26:33 +00003580 // Do standard promotions between the two arguments, returning their common
3581 // type.
Chris Lattner08464942007-12-28 05:29:59 +00003582 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00003583 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
3584 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00003585
3586 // Make sure any conversions are pushed back into the call; this is
3587 // type safe since unordered compare builtins are declared as "_Bool
3588 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00003589 TheCall->setArg(0, OrigArg0.get());
3590 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00003591
John Wiegley01296292011-04-08 18:41:53 +00003592 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00003593 return false;
3594
Chris Lattner2da14fb2007-12-20 00:26:33 +00003595 // If the common type isn't a real floating type, then the arguments were
3596 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00003597 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00003598 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003599 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00003600 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
3601 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003602
Chris Lattner2da14fb2007-12-20 00:26:33 +00003603 return false;
3604}
3605
Benjamin Kramer634fc102010-02-15 22:42:31 +00003606/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
3607/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00003608/// to check everything. We expect the last argument to be a floating point
3609/// value.
3610bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
3611 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00003612 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00003613 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00003614 if (TheCall->getNumArgs() > NumArgs)
3615 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003616 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003617 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00003618 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003619 (*(TheCall->arg_end()-1))->getLocEnd());
3620
Benjamin Kramer64aae502010-02-16 10:07:31 +00003621 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00003622
Eli Friedman7e4faac2009-08-31 20:06:00 +00003623 if (OrigArg->isTypeDependent())
3624 return false;
3625
Chris Lattner68784ef2010-05-06 05:50:07 +00003626 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00003627 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00003628 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003629 diag::err_typecheck_call_invalid_unary_fp)
3630 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003631
Chris Lattner68784ef2010-05-06 05:50:07 +00003632 // If this is an implicit conversion from float -> double, remove it.
3633 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
3634 Expr *CastArg = Cast->getSubExpr();
3635 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
3636 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
3637 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00003638 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00003639 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00003640 }
3641 }
3642
Eli Friedman7e4faac2009-08-31 20:06:00 +00003643 return false;
3644}
3645
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003646/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
3647// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00003648ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00003649 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003650 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00003651 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00003652 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3653 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003654
Nate Begemana0110022010-06-08 00:16:34 +00003655 // Determine which of the following types of shufflevector we're checking:
3656 // 1) unary, vector mask: (lhs, mask)
Craig Topperb3174a82016-05-18 04:11:25 +00003657 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
Nate Begemana0110022010-06-08 00:16:34 +00003658 QualType resType = TheCall->getArg(0)->getType();
3659 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00003660
Douglas Gregorc25f7662009-05-19 22:10:17 +00003661 if (!TheCall->getArg(0)->isTypeDependent() &&
3662 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00003663 QualType LHSType = TheCall->getArg(0)->getType();
3664 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00003665
Craig Topperbaca3892013-07-29 06:47:04 +00003666 if (!LHSType->isVectorType() || !RHSType->isVectorType())
3667 return ExprError(Diag(TheCall->getLocStart(),
3668 diag::err_shufflevector_non_vector)
3669 << SourceRange(TheCall->getArg(0)->getLocStart(),
3670 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00003671
Nate Begemana0110022010-06-08 00:16:34 +00003672 numElements = LHSType->getAs<VectorType>()->getNumElements();
3673 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00003674
Nate Begemana0110022010-06-08 00:16:34 +00003675 // Check to see if we have a call with 2 vector arguments, the unary shuffle
3676 // with mask. If so, verify that RHS is an integer vector type with the
3677 // same number of elts as lhs.
3678 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00003679 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00003680 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00003681 return ExprError(Diag(TheCall->getLocStart(),
3682 diag::err_shufflevector_incompatible_vector)
3683 << SourceRange(TheCall->getArg(1)->getLocStart(),
3684 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00003685 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00003686 return ExprError(Diag(TheCall->getLocStart(),
3687 diag::err_shufflevector_incompatible_vector)
3688 << SourceRange(TheCall->getArg(0)->getLocStart(),
3689 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00003690 } else if (numElements != numResElements) {
3691 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00003692 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00003693 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00003694 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003695 }
3696
3697 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00003698 if (TheCall->getArg(i)->isTypeDependent() ||
3699 TheCall->getArg(i)->isValueDependent())
3700 continue;
3701
Nate Begemana0110022010-06-08 00:16:34 +00003702 llvm::APSInt Result(32);
3703 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
3704 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00003705 diag::err_shufflevector_nonconstant_argument)
3706 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003707
Craig Topper50ad5b72013-08-03 17:40:38 +00003708 // Allow -1 which will be translated to undef in the IR.
3709 if (Result.isSigned() && Result.isAllOnesValue())
3710 continue;
3711
Chris Lattner7ab824e2008-08-10 02:05:13 +00003712 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003713 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00003714 diag::err_shufflevector_argument_too_large)
3715 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003716 }
3717
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003718 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003719
Chris Lattner7ab824e2008-08-10 02:05:13 +00003720 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003721 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00003722 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003723 }
3724
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003725 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
3726 TheCall->getCallee()->getLocStart(),
3727 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003728}
Chris Lattner43be2e62007-12-19 23:59:04 +00003729
Hal Finkelc4d7c822013-09-18 03:29:45 +00003730/// SemaConvertVectorExpr - Handle __builtin_convertvector
3731ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
3732 SourceLocation BuiltinLoc,
3733 SourceLocation RParenLoc) {
3734 ExprValueKind VK = VK_RValue;
3735 ExprObjectKind OK = OK_Ordinary;
3736 QualType DstTy = TInfo->getType();
3737 QualType SrcTy = E->getType();
3738
3739 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
3740 return ExprError(Diag(BuiltinLoc,
3741 diag::err_convertvector_non_vector)
3742 << E->getSourceRange());
3743 if (!DstTy->isVectorType() && !DstTy->isDependentType())
3744 return ExprError(Diag(BuiltinLoc,
3745 diag::err_convertvector_non_vector_type));
3746
3747 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
3748 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
3749 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
3750 if (SrcElts != DstElts)
3751 return ExprError(Diag(BuiltinLoc,
3752 diag::err_convertvector_incompatible_vector)
3753 << E->getSourceRange());
3754 }
3755
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003756 return new (Context)
3757 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00003758}
3759
Daniel Dunbarb7257262008-07-21 22:59:13 +00003760/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
3761// This is declared to take (const void*, ...) and can take two
3762// optional constant int args.
3763bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00003764 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003765
Chris Lattner3b054132008-11-19 05:08:23 +00003766 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003767 return Diag(TheCall->getLocEnd(),
3768 diag::err_typecheck_call_too_many_args_at_most)
3769 << 0 /*function call*/ << 3 << NumArgs
3770 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003771
3772 // Argument 0 is checked for us and the remaining arguments must be
3773 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00003774 for (unsigned i = 1; i != NumArgs; ++i)
3775 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00003776 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003777
Warren Hunt20e4a5d2014-02-21 23:08:53 +00003778 return false;
3779}
3780
Hal Finkelf0417332014-07-17 14:25:55 +00003781/// SemaBuiltinAssume - Handle __assume (MS Extension).
3782// __assume does not evaluate its arguments, and should warn if its argument
3783// has side effects.
3784bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
3785 Expr *Arg = TheCall->getArg(0);
3786 if (Arg->isInstantiationDependent()) return false;
3787
3788 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00003789 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00003790 << Arg->getSourceRange()
3791 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
3792
3793 return false;
3794}
3795
3796/// Handle __builtin_assume_aligned. This is declared
3797/// as (const void*, size_t, ...) and can take one optional constant int arg.
3798bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
3799 unsigned NumArgs = TheCall->getNumArgs();
3800
3801 if (NumArgs > 3)
3802 return Diag(TheCall->getLocEnd(),
3803 diag::err_typecheck_call_too_many_args_at_most)
3804 << 0 /*function call*/ << 3 << NumArgs
3805 << TheCall->getSourceRange();
3806
3807 // The alignment must be a constant integer.
3808 Expr *Arg = TheCall->getArg(1);
3809
3810 // We can't check the value of a dependent argument.
3811 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
3812 llvm::APSInt Result;
3813 if (SemaBuiltinConstantArg(TheCall, 1, Result))
3814 return true;
3815
3816 if (!Result.isPowerOf2())
3817 return Diag(TheCall->getLocStart(),
3818 diag::err_alignment_not_power_of_two)
3819 << Arg->getSourceRange();
3820 }
3821
3822 if (NumArgs > 2) {
3823 ExprResult Arg(TheCall->getArg(2));
3824 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3825 Context.getSizeType(), false);
3826 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3827 if (Arg.isInvalid()) return true;
3828 TheCall->setArg(2, Arg.get());
3829 }
Hal Finkelf0417332014-07-17 14:25:55 +00003830
3831 return false;
3832}
3833
Eric Christopher8d0c6212010-04-17 02:26:23 +00003834/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
3835/// TheCall is a constant expression.
3836bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
3837 llvm::APSInt &Result) {
3838 Expr *Arg = TheCall->getArg(ArgNum);
3839 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3840 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3841
3842 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
3843
3844 if (!Arg->isIntegerConstantExpr(Result, Context))
3845 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00003846 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00003847
Chris Lattnerd545ad12009-09-23 06:06:36 +00003848 return false;
3849}
3850
Richard Sandiford28940af2014-04-16 08:47:51 +00003851/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
3852/// TheCall is a constant expression in the range [Low, High].
3853bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
3854 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00003855 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00003856
3857 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00003858 Expr *Arg = TheCall->getArg(ArgNum);
3859 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00003860 return false;
3861
Eric Christopher8d0c6212010-04-17 02:26:23 +00003862 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00003863 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00003864 return true;
3865
Richard Sandiford28940af2014-04-16 08:47:51 +00003866 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00003867 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00003868 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00003869
3870 return false;
3871}
3872
Luke Cheeseman59b2d832015-06-15 17:51:01 +00003873/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
3874/// TheCall is an ARM/AArch64 special register string literal.
3875bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
3876 int ArgNum, unsigned ExpectedFieldNum,
3877 bool AllowName) {
3878 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
3879 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
3880 BuiltinID == ARM::BI__builtin_arm_rsr ||
3881 BuiltinID == ARM::BI__builtin_arm_rsrp ||
3882 BuiltinID == ARM::BI__builtin_arm_wsr ||
3883 BuiltinID == ARM::BI__builtin_arm_wsrp;
3884 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
3885 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
3886 BuiltinID == AArch64::BI__builtin_arm_rsr ||
3887 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
3888 BuiltinID == AArch64::BI__builtin_arm_wsr ||
3889 BuiltinID == AArch64::BI__builtin_arm_wsrp;
3890 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
3891
3892 // We can't check the value of a dependent argument.
3893 Expr *Arg = TheCall->getArg(ArgNum);
3894 if (Arg->isTypeDependent() || Arg->isValueDependent())
3895 return false;
3896
3897 // Check if the argument is a string literal.
3898 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3899 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
3900 << Arg->getSourceRange();
3901
3902 // Check the type of special register given.
3903 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3904 SmallVector<StringRef, 6> Fields;
3905 Reg.split(Fields, ":");
3906
3907 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
3908 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
3909 << Arg->getSourceRange();
3910
3911 // If the string is the name of a register then we cannot check that it is
3912 // valid here but if the string is of one the forms described in ACLE then we
3913 // can check that the supplied fields are integers and within the valid
3914 // ranges.
3915 if (Fields.size() > 1) {
3916 bool FiveFields = Fields.size() == 5;
3917
3918 bool ValidString = true;
3919 if (IsARMBuiltin) {
3920 ValidString &= Fields[0].startswith_lower("cp") ||
3921 Fields[0].startswith_lower("p");
3922 if (ValidString)
3923 Fields[0] =
3924 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
3925
3926 ValidString &= Fields[2].startswith_lower("c");
3927 if (ValidString)
3928 Fields[2] = Fields[2].drop_front(1);
3929
3930 if (FiveFields) {
3931 ValidString &= Fields[3].startswith_lower("c");
3932 if (ValidString)
3933 Fields[3] = Fields[3].drop_front(1);
3934 }
3935 }
3936
3937 SmallVector<int, 5> Ranges;
3938 if (FiveFields)
3939 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15});
3940 else
3941 Ranges.append({15, 7, 15});
3942
3943 for (unsigned i=0; i<Fields.size(); ++i) {
3944 int IntField;
3945 ValidString &= !Fields[i].getAsInteger(10, IntField);
3946 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
3947 }
3948
3949 if (!ValidString)
3950 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
3951 << Arg->getSourceRange();
3952
3953 } else if (IsAArch64Builtin && Fields.size() == 1) {
3954 // If the register name is one of those that appear in the condition below
3955 // and the special register builtin being used is one of the write builtins,
3956 // then we require that the argument provided for writing to the register
3957 // is an integer constant expression. This is because it will be lowered to
3958 // an MSR (immediate) instruction, so we need to know the immediate at
3959 // compile time.
3960 if (TheCall->getNumArgs() != 2)
3961 return false;
3962
3963 std::string RegLower = Reg.lower();
3964 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
3965 RegLower != "pan" && RegLower != "uao")
3966 return false;
3967
3968 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
3969 }
3970
3971 return false;
3972}
3973
Eli Friedmanc97d0142009-05-03 06:04:26 +00003974/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003975/// This checks that the target supports __builtin_longjmp and
3976/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003977bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003978 if (!Context.getTargetInfo().hasSjLjLowering())
3979 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
3980 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
3981
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003982 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00003983 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00003984
Eric Christopher8d0c6212010-04-17 02:26:23 +00003985 // TODO: This is less than ideal. Overload this to take a value.
3986 if (SemaBuiltinConstantArg(TheCall, 1, Result))
3987 return true;
3988
3989 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003990 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
3991 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
3992
3993 return false;
3994}
3995
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003996/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
3997/// This checks that the target supports __builtin_setjmp.
3998bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
3999 if (!Context.getTargetInfo().hasSjLjLowering())
4000 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
4001 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4002 return false;
4003}
4004
Richard Smithd7293d72013-08-05 18:49:43 +00004005namespace {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004006class UncoveredArgHandler {
4007 enum { Unknown = -1, AllCovered = -2 };
4008 signed FirstUncoveredArg;
4009 SmallVector<const Expr *, 4> DiagnosticExprs;
4010
4011public:
4012 UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
4013
4014 bool hasUncoveredArg() const {
4015 return (FirstUncoveredArg >= 0);
4016 }
4017
4018 unsigned getUncoveredArg() const {
4019 assert(hasUncoveredArg() && "no uncovered argument");
4020 return FirstUncoveredArg;
4021 }
4022
4023 void setAllCovered() {
4024 // A string has been found with all arguments covered, so clear out
4025 // the diagnostics.
4026 DiagnosticExprs.clear();
4027 FirstUncoveredArg = AllCovered;
4028 }
4029
4030 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
4031 assert(NewFirstUncoveredArg >= 0 && "Outside range");
4032
4033 // Don't update if a previous string covers all arguments.
4034 if (FirstUncoveredArg == AllCovered)
4035 return;
4036
4037 // UncoveredArgHandler tracks the highest uncovered argument index
4038 // and with it all the strings that match this index.
4039 if (NewFirstUncoveredArg == FirstUncoveredArg)
4040 DiagnosticExprs.push_back(StrExpr);
4041 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
4042 DiagnosticExprs.clear();
4043 DiagnosticExprs.push_back(StrExpr);
4044 FirstUncoveredArg = NewFirstUncoveredArg;
4045 }
4046 }
4047
4048 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
4049};
4050
Richard Smithd7293d72013-08-05 18:49:43 +00004051enum StringLiteralCheckType {
4052 SLCT_NotALiteral,
4053 SLCT_UncheckedLiteral,
4054 SLCT_CheckedLiteral
4055};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004056} // end anonymous namespace
Richard Smithd7293d72013-08-05 18:49:43 +00004057
Stephen Hines648c3692016-09-16 01:07:04 +00004058static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
4059 BinaryOperatorKind BinOpKind,
4060 bool AddendIsRight) {
4061 unsigned BitWidth = Offset.getBitWidth();
4062 unsigned AddendBitWidth = Addend.getBitWidth();
4063 // There might be negative interim results.
4064 if (Addend.isUnsigned()) {
4065 Addend = Addend.zext(++AddendBitWidth);
4066 Addend.setIsSigned(true);
4067 }
4068 // Adjust the bit width of the APSInts.
4069 if (AddendBitWidth > BitWidth) {
4070 Offset = Offset.sext(AddendBitWidth);
4071 BitWidth = AddendBitWidth;
4072 } else if (BitWidth > AddendBitWidth) {
4073 Addend = Addend.sext(BitWidth);
4074 }
4075
4076 bool Ov = false;
4077 llvm::APSInt ResOffset = Offset;
4078 if (BinOpKind == BO_Add)
4079 ResOffset = Offset.sadd_ov(Addend, Ov);
4080 else {
4081 assert(AddendIsRight && BinOpKind == BO_Sub &&
4082 "operator must be add or sub with addend on the right");
4083 ResOffset = Offset.ssub_ov(Addend, Ov);
4084 }
4085
4086 // We add an offset to a pointer here so we should support an offset as big as
4087 // possible.
4088 if (Ov) {
4089 assert(BitWidth <= UINT_MAX / 2 && "index (intermediate) result too big");
Stephen Hinesfec73ad2016-09-16 07:21:24 +00004090 Offset = Offset.sext(2 * BitWidth);
Stephen Hines648c3692016-09-16 01:07:04 +00004091 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
4092 return;
4093 }
4094
4095 Offset = ResOffset;
4096}
4097
4098namespace {
4099// This is a wrapper class around StringLiteral to support offsetted string
4100// literals as format strings. It takes the offset into account when returning
4101// the string and its length or the source locations to display notes correctly.
4102class FormatStringLiteral {
4103 const StringLiteral *FExpr;
4104 int64_t Offset;
4105
4106 public:
4107 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
4108 : FExpr(fexpr), Offset(Offset) {}
4109
4110 StringRef getString() const {
4111 return FExpr->getString().drop_front(Offset);
4112 }
4113
4114 unsigned getByteLength() const {
4115 return FExpr->getByteLength() - getCharByteWidth() * Offset;
4116 }
4117 unsigned getLength() const { return FExpr->getLength() - Offset; }
4118 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
4119
4120 StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
4121
4122 QualType getType() const { return FExpr->getType(); }
4123
4124 bool isAscii() const { return FExpr->isAscii(); }
4125 bool isWide() const { return FExpr->isWide(); }
4126 bool isUTF8() const { return FExpr->isUTF8(); }
4127 bool isUTF16() const { return FExpr->isUTF16(); }
4128 bool isUTF32() const { return FExpr->isUTF32(); }
4129 bool isPascal() const { return FExpr->isPascal(); }
4130
4131 SourceLocation getLocationOfByte(
4132 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
4133 const TargetInfo &Target, unsigned *StartToken = nullptr,
4134 unsigned *StartTokenByteOffset = nullptr) const {
4135 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
4136 StartToken, StartTokenByteOffset);
4137 }
4138
4139 SourceLocation getLocStart() const LLVM_READONLY {
4140 return FExpr->getLocStart().getLocWithOffset(Offset);
4141 }
4142 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
4143};
4144} // end anonymous namespace
4145
4146static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004147 const Expr *OrigFormatExpr,
4148 ArrayRef<const Expr *> Args,
4149 bool HasVAListArg, unsigned format_idx,
4150 unsigned firstDataArg,
4151 Sema::FormatStringType Type,
4152 bool inFunctionCall,
4153 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004154 llvm::SmallBitVector &CheckedVarArgs,
4155 UncoveredArgHandler &UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004156
Richard Smith55ce3522012-06-25 20:30:08 +00004157// Determine if an expression is a string literal or constant string.
4158// If this function returns false on the arguments to a function expecting a
4159// format string, we will usually need to emit a warning.
4160// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00004161static StringLiteralCheckType
4162checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
4163 bool HasVAListArg, unsigned format_idx,
4164 unsigned firstDataArg, Sema::FormatStringType Type,
4165 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004166 llvm::SmallBitVector &CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004167 UncoveredArgHandler &UncoveredArg,
4168 llvm::APSInt Offset) {
Ted Kremenek808829352010-09-09 03:51:39 +00004169 tryAgain:
Stephen Hines648c3692016-09-16 01:07:04 +00004170 assert(Offset.isSigned() && "invalid offset");
4171
Douglas Gregorc25f7662009-05-19 22:10:17 +00004172 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00004173 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004174
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004175 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00004176
Richard Smithd7293d72013-08-05 18:49:43 +00004177 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00004178 // Technically -Wformat-nonliteral does not warn about this case.
4179 // The behavior of printf and friends in this case is implementation
4180 // dependent. Ideally if the format string cannot be null then
4181 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00004182 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00004183
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004184 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00004185 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004186 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00004187 // The expression is a literal if both sub-expressions were, and it was
4188 // completely checked only if both sub-expressions were checked.
4189 const AbstractConditionalOperator *C =
4190 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004191
4192 // Determine whether it is necessary to check both sub-expressions, for
4193 // example, because the condition expression is a constant that can be
4194 // evaluated at compile time.
4195 bool CheckLeft = true, CheckRight = true;
4196
4197 bool Cond;
4198 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
4199 if (Cond)
4200 CheckRight = false;
4201 else
4202 CheckLeft = false;
4203 }
4204
Stephen Hines648c3692016-09-16 01:07:04 +00004205 // We need to maintain the offsets for the right and the left hand side
4206 // separately to check if every possible indexed expression is a valid
4207 // string literal. They might have different offsets for different string
4208 // literals in the end.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004209 StringLiteralCheckType Left;
4210 if (!CheckLeft)
4211 Left = SLCT_UncheckedLiteral;
4212 else {
4213 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
4214 HasVAListArg, format_idx, firstDataArg,
4215 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00004216 CheckedVarArgs, UncoveredArg, Offset);
4217 if (Left == SLCT_NotALiteral || !CheckRight) {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004218 return Left;
Stephen Hines648c3692016-09-16 01:07:04 +00004219 }
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004220 }
4221
Richard Smith55ce3522012-06-25 20:30:08 +00004222 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00004223 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004224 HasVAListArg, format_idx, firstDataArg,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004225 Type, CallType, InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004226 UncoveredArg, Offset);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004227
4228 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004229 }
4230
4231 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00004232 E = cast<ImplicitCastExpr>(E)->getSubExpr();
4233 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004234 }
4235
John McCallc07a0c72011-02-17 10:25:35 +00004236 case Stmt::OpaqueValueExprClass:
4237 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4238 E = src;
4239 goto tryAgain;
4240 }
Richard Smith55ce3522012-06-25 20:30:08 +00004241 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00004242
Ted Kremeneka8890832011-02-24 23:03:04 +00004243 case Stmt::PredefinedExprClass:
4244 // While __func__, etc., are technically not string literals, they
4245 // cannot contain format specifiers and thus are not a security
4246 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00004247 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00004248
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004249 case Stmt::DeclRefExprClass: {
4250 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004251
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004252 // As an exception, do not flag errors for variables binding to
4253 // const string literals.
4254 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
4255 bool isConstant = false;
4256 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004257
Richard Smithd7293d72013-08-05 18:49:43 +00004258 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
4259 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00004260 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00004261 isConstant = T.isConstant(S.Context) &&
4262 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00004263 } else if (T->isObjCObjectPointerType()) {
4264 // In ObjC, there is usually no "const ObjectPointer" type,
4265 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00004266 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004267 }
Mike Stump11289f42009-09-09 15:08:12 +00004268
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004269 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00004270 if (const Expr *Init = VD->getAnyInitializer()) {
4271 // Look through initializers like const char c[] = { "foo" }
4272 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4273 if (InitList->isStringLiteralInit())
4274 Init = InitList->getInit(0)->IgnoreParenImpCasts();
4275 }
Richard Smithd7293d72013-08-05 18:49:43 +00004276 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004277 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004278 firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00004279 /*InFunctionCall*/ false, CheckedVarArgs,
4280 UncoveredArg, Offset);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00004281 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004282 }
Mike Stump11289f42009-09-09 15:08:12 +00004283
Anders Carlssonb012ca92009-06-28 19:55:58 +00004284 // For vprintf* functions (i.e., HasVAListArg==true), we add a
4285 // special check to see if the format string is a function parameter
4286 // of the function calling the printf function. If the function
4287 // has an attribute indicating it is a printf-like function, then we
4288 // should suppress warnings concerning non-literals being used in a call
4289 // to a vprintf function. For example:
4290 //
4291 // void
4292 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
4293 // va_list ap;
4294 // va_start(ap, fmt);
4295 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
4296 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00004297 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004298 if (HasVAListArg) {
4299 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
4300 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
4301 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00004302 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004303 // adjust for implicit parameter
4304 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4305 if (MD->isInstance())
4306 ++PVIndex;
4307 // We also check if the formats are compatible.
4308 // We can't pass a 'scanf' string to a 'printf' function.
4309 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00004310 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00004311 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004312 }
4313 }
4314 }
4315 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004316 }
Mike Stump11289f42009-09-09 15:08:12 +00004317
Richard Smith55ce3522012-06-25 20:30:08 +00004318 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004319 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004320
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00004321 case Stmt::CallExprClass:
4322 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004323 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00004324 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
4325 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
4326 unsigned ArgIndex = FA->getFormatIdx();
4327 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4328 if (MD->isInstance())
4329 --ArgIndex;
4330 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00004331
Richard Smithd7293d72013-08-05 18:49:43 +00004332 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004333 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00004334 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00004335 CheckedVarArgs, UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004336 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4337 unsigned BuiltinID = FD->getBuiltinID();
4338 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
4339 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
4340 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00004341 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004342 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004343 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004344 InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004345 UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004346 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004347 }
4348 }
Mike Stump11289f42009-09-09 15:08:12 +00004349
Richard Smith55ce3522012-06-25 20:30:08 +00004350 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004351 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004352 case Stmt::ObjCStringLiteralClass:
4353 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00004354 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004355
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004356 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004357 StrE = ObjCFExpr->getString();
4358 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004359 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004360
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004361 if (StrE) {
Stephen Hines648c3692016-09-16 01:07:04 +00004362 if (Offset.isNegative() || Offset > StrE->getLength()) {
4363 // TODO: It would be better to have an explicit warning for out of
4364 // bounds literals.
4365 return SLCT_NotALiteral;
4366 }
4367 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
4368 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004369 firstDataArg, Type, InFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004370 CheckedVarArgs, UncoveredArg);
Richard Smith55ce3522012-06-25 20:30:08 +00004371 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004372 }
Mike Stump11289f42009-09-09 15:08:12 +00004373
Richard Smith55ce3522012-06-25 20:30:08 +00004374 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004375 }
Stephen Hines648c3692016-09-16 01:07:04 +00004376 case Stmt::BinaryOperatorClass: {
4377 llvm::APSInt LResult;
4378 llvm::APSInt RResult;
4379
4380 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
4381
4382 // A string literal + an int offset is still a string literal.
4383 if (BinOp->isAdditiveOp()) {
4384 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
4385 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
4386
4387 if (LIsInt != RIsInt) {
4388 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
4389
4390 if (LIsInt) {
4391 if (BinOpKind == BO_Add) {
4392 sumOffsets(Offset, LResult, BinOpKind, RIsInt);
4393 E = BinOp->getRHS();
4394 goto tryAgain;
4395 }
4396 } else {
4397 sumOffsets(Offset, RResult, BinOpKind, RIsInt);
4398 E = BinOp->getLHS();
4399 goto tryAgain;
4400 }
4401 }
Stephen Hines648c3692016-09-16 01:07:04 +00004402 }
George Burgess IVd273aab2016-09-22 00:00:26 +00004403
4404 return SLCT_NotALiteral;
Stephen Hines648c3692016-09-16 01:07:04 +00004405 }
4406 case Stmt::UnaryOperatorClass: {
4407 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
4408 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
4409 if (UnaOp->getOpcode() == clang::UO_AddrOf && ASE) {
4410 llvm::APSInt IndexResult;
4411 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
4412 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
4413 E = ASE->getBase();
4414 goto tryAgain;
4415 }
4416 }
4417
4418 return SLCT_NotALiteral;
4419 }
Mike Stump11289f42009-09-09 15:08:12 +00004420
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004421 default:
Richard Smith55ce3522012-06-25 20:30:08 +00004422 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004423 }
4424}
4425
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004426Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00004427 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004428 .Case("scanf", FST_Scanf)
4429 .Cases("printf", "printf0", FST_Printf)
4430 .Cases("NSString", "CFString", FST_NSString)
4431 .Case("strftime", FST_Strftime)
4432 .Case("strfmon", FST_Strfmon)
4433 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004434 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00004435 .Case("os_trace", FST_OSTrace)
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004436 .Default(FST_Unknown);
4437}
4438
Jordan Rose3e0ec582012-07-19 18:10:23 +00004439/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00004440/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00004441/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004442bool Sema::CheckFormatArguments(const FormatAttr *Format,
4443 ArrayRef<const Expr *> Args,
4444 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004445 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00004446 SourceLocation Loc, SourceRange Range,
4447 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00004448 FormatStringInfo FSI;
4449 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004450 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00004451 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00004452 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00004453 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004454}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00004455
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004456bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004457 bool HasVAListArg, unsigned format_idx,
4458 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004459 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00004460 SourceLocation Loc, SourceRange Range,
4461 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00004462 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004463 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004464 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00004465 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004466 }
Mike Stump11289f42009-09-09 15:08:12 +00004467
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004468 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00004469
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004470 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00004471 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004472 // Dynamically generated format strings are difficult to
4473 // automatically vet at compile time. Requiring that format strings
4474 // are string literals: (1) permits the checking of format strings by
4475 // the compiler and thereby (2) can practically remove the source of
4476 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00004477
Mike Stump11289f42009-09-09 15:08:12 +00004478 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00004479 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00004480 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00004481 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004482 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00004483 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00004484 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
4485 format_idx, firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00004486 /*IsFunctionCall*/ true, CheckedVarArgs,
4487 UncoveredArg,
4488 /*no string offset*/ llvm::APSInt(64, false) = 0);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004489
4490 // Generate a diagnostic where an uncovered argument is detected.
4491 if (UncoveredArg.hasUncoveredArg()) {
4492 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
4493 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
4494 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
4495 }
4496
Richard Smith55ce3522012-06-25 20:30:08 +00004497 if (CT != SLCT_NotALiteral)
4498 // Literal format string found, check done!
4499 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00004500
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00004501 // Strftime is particular as it always uses a single 'time' argument,
4502 // so it is safe to pass a non-literal string.
4503 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00004504 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00004505
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00004506 // Do not emit diag when the string param is a macro expansion and the
4507 // format is either NSString or CFString. This is a hack to prevent
4508 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
4509 // which are usually used in place of NS and CF string literals.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004510 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
4511 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
Richard Smith55ce3522012-06-25 20:30:08 +00004512 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00004513
Chris Lattnercc5d1c22009-04-29 04:59:47 +00004514 // If there are no arguments specified, warn with -Wformat-security, otherwise
4515 // warn only with -Wformat-nonliteral.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004516 if (Args.size() == firstDataArg) {
Bob Wilson57819fc2016-03-15 20:56:38 +00004517 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
4518 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004519 switch (Type) {
4520 default:
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004521 break;
4522 case FST_Kprintf:
4523 case FST_FreeBSDKPrintf:
4524 case FST_Printf:
Bob Wilson57819fc2016-03-15 20:56:38 +00004525 Diag(FormatLoc, diag::note_format_security_fixit)
4526 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004527 break;
4528 case FST_NSString:
Bob Wilson57819fc2016-03-15 20:56:38 +00004529 Diag(FormatLoc, diag::note_format_security_fixit)
4530 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004531 break;
4532 }
4533 } else {
4534 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00004535 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004536 }
Richard Smith55ce3522012-06-25 20:30:08 +00004537 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004538}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004539
Ted Kremenekab278de2010-01-28 23:39:18 +00004540namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00004541class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
4542protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00004543 Sema &S;
Stephen Hines648c3692016-09-16 01:07:04 +00004544 const FormatStringLiteral *FExpr;
Ted Kremenekab278de2010-01-28 23:39:18 +00004545 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00004546 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00004547 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00004548 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00004549 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004550 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00004551 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00004552 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00004553 bool usesPositionalArgs;
4554 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00004555 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00004556 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00004557 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004558 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004559
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004560public:
Stephen Hines648c3692016-09-16 01:07:04 +00004561 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00004562 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004563 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004564 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004565 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00004566 Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004567 llvm::SmallBitVector &CheckedVarArgs,
4568 UncoveredArgHandler &UncoveredArg)
Ted Kremenekab278de2010-01-28 23:39:18 +00004569 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004570 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
4571 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004572 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00004573 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00004574 inFunctionCall(inFunctionCall), CallType(callType),
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004575 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00004576 CoveredArgs.resize(numDataArgs);
4577 CoveredArgs.reset();
4578 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004579
Ted Kremenek019d2242010-01-29 01:50:07 +00004580 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004581
Ted Kremenek02087932010-07-16 02:11:22 +00004582 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004583 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004584
Jordan Rose92303592012-09-08 04:00:03 +00004585 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00004586 const analyze_format_string::FormatSpecifier &FS,
4587 const analyze_format_string::ConversionSpecifier &CS,
4588 const char *startSpecifier, unsigned specifierLen,
4589 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00004590
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004591 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00004592 const analyze_format_string::FormatSpecifier &FS,
4593 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004594
4595 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00004596 const analyze_format_string::ConversionSpecifier &CS,
4597 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004598
Craig Toppere14c0f82014-03-12 04:55:44 +00004599 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00004600
Craig Toppere14c0f82014-03-12 04:55:44 +00004601 void HandleInvalidPosition(const char *startSpecifier,
4602 unsigned specifierLen,
4603 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00004604
Craig Toppere14c0f82014-03-12 04:55:44 +00004605 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00004606
Craig Toppere14c0f82014-03-12 04:55:44 +00004607 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004608
Richard Trieu03cf7b72011-10-28 00:41:25 +00004609 template <typename Range>
Benjamin Kramer7320b992016-06-15 14:20:56 +00004610 static void
4611 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
4612 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
4613 bool IsStringLocation, Range StringRange,
4614 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00004615
Ted Kremenek02087932010-07-16 02:11:22 +00004616protected:
Ted Kremenekce815422010-07-19 21:25:57 +00004617 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
4618 const char *startSpec,
4619 unsigned specifierLen,
4620 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00004621
4622 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
4623 const char *startSpec,
4624 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00004625
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004626 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00004627 CharSourceRange getSpecifierRange(const char *startSpecifier,
4628 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00004629 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004630
Ted Kremenek5739de72010-01-29 01:06:55 +00004631 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004632
4633 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
4634 const analyze_format_string::ConversionSpecifier &CS,
4635 const char *startSpecifier, unsigned specifierLen,
4636 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00004637
4638 template <typename Range>
4639 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
4640 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00004641 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00004642};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004643} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00004644
Ted Kremenek02087932010-07-16 02:11:22 +00004645SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00004646 return OrigFormatExpr->getSourceRange();
4647}
4648
Ted Kremenek02087932010-07-16 02:11:22 +00004649CharSourceRange CheckFormatHandler::
4650getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00004651 SourceLocation Start = getLocationOfByte(startSpecifier);
4652 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
4653
4654 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00004655 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00004656
4657 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004658}
4659
Ted Kremenek02087932010-07-16 02:11:22 +00004660SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Stephen Hines648c3692016-09-16 01:07:04 +00004661 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
4662 S.getLangOpts(), S.Context.getTargetInfo());
Ted Kremenekab278de2010-01-28 23:39:18 +00004663}
4664
Ted Kremenek02087932010-07-16 02:11:22 +00004665void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
4666 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00004667 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
4668 getLocationOfByte(startSpecifier),
4669 /*IsStringLocation*/true,
4670 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00004671}
4672
Jordan Rose92303592012-09-08 04:00:03 +00004673void CheckFormatHandler::HandleInvalidLengthModifier(
4674 const analyze_format_string::FormatSpecifier &FS,
4675 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00004676 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00004677 using namespace analyze_format_string;
4678
4679 const LengthModifier &LM = FS.getLengthModifier();
4680 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4681
4682 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00004683 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00004684 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004685 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00004686 getLocationOfByte(LM.getStart()),
4687 /*IsStringLocation*/true,
4688 getSpecifierRange(startSpecifier, specifierLen));
4689
4690 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4691 << FixedLM->toString()
4692 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
4693
4694 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004695 FixItHint Hint;
4696 if (DiagID == diag::warn_format_nonsensical_length)
4697 Hint = FixItHint::CreateRemoval(LMRange);
4698
4699 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00004700 getLocationOfByte(LM.getStart()),
4701 /*IsStringLocation*/true,
4702 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00004703 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00004704 }
4705}
4706
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004707void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00004708 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004709 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004710 using namespace analyze_format_string;
4711
4712 const LengthModifier &LM = FS.getLengthModifier();
4713 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4714
4715 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00004716 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00004717 if (FixedLM) {
4718 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4719 << LM.toString() << 0,
4720 getLocationOfByte(LM.getStart()),
4721 /*IsStringLocation*/true,
4722 getSpecifierRange(startSpecifier, specifierLen));
4723
4724 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4725 << FixedLM->toString()
4726 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
4727
4728 } else {
4729 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4730 << LM.toString() << 0,
4731 getLocationOfByte(LM.getStart()),
4732 /*IsStringLocation*/true,
4733 getSpecifierRange(startSpecifier, specifierLen));
4734 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004735}
4736
4737void CheckFormatHandler::HandleNonStandardConversionSpecifier(
4738 const analyze_format_string::ConversionSpecifier &CS,
4739 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00004740 using namespace analyze_format_string;
4741
4742 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00004743 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00004744 if (FixedCS) {
4745 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4746 << CS.toString() << /*conversion specifier*/1,
4747 getLocationOfByte(CS.getStart()),
4748 /*IsStringLocation*/true,
4749 getSpecifierRange(startSpecifier, specifierLen));
4750
4751 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
4752 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
4753 << FixedCS->toString()
4754 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
4755 } else {
4756 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4757 << CS.toString() << /*conversion specifier*/1,
4758 getLocationOfByte(CS.getStart()),
4759 /*IsStringLocation*/true,
4760 getSpecifierRange(startSpecifier, specifierLen));
4761 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004762}
4763
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00004764void CheckFormatHandler::HandlePosition(const char *startPos,
4765 unsigned posLen) {
4766 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
4767 getLocationOfByte(startPos),
4768 /*IsStringLocation*/true,
4769 getSpecifierRange(startPos, posLen));
4770}
4771
Ted Kremenekd1668192010-02-27 01:41:03 +00004772void
Ted Kremenek02087932010-07-16 02:11:22 +00004773CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
4774 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004775 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
4776 << (unsigned) p,
4777 getLocationOfByte(startPos), /*IsStringLocation*/true,
4778 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00004779}
4780
Ted Kremenek02087932010-07-16 02:11:22 +00004781void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00004782 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004783 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
4784 getLocationOfByte(startPos),
4785 /*IsStringLocation*/true,
4786 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00004787}
4788
Ted Kremenek02087932010-07-16 02:11:22 +00004789void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004790 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00004791 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00004792 EmitFormatDiagnostic(
4793 S.PDiag(diag::warn_printf_format_string_contains_null_char),
4794 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
4795 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00004796 }
Ted Kremenek02087932010-07-16 02:11:22 +00004797}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004798
Jordan Rose58bbe422012-07-19 18:10:08 +00004799// Note that this may return NULL if there was an error parsing or building
4800// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00004801const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004802 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00004803}
4804
4805void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004806 // Does the number of data arguments exceed the number of
4807 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00004808 if (!HasVAListArg) {
4809 // Find any arguments that weren't covered.
4810 CoveredArgs.flip();
4811 signed notCoveredArg = CoveredArgs.find_first();
4812 if (notCoveredArg >= 0) {
4813 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004814 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
4815 } else {
4816 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00004817 }
4818 }
4819}
4820
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004821void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
4822 const Expr *ArgExpr) {
4823 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
4824 "Invalid state");
4825
4826 if (!ArgExpr)
4827 return;
4828
4829 SourceLocation Loc = ArgExpr->getLocStart();
4830
4831 if (S.getSourceManager().isInSystemMacro(Loc))
4832 return;
4833
4834 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
4835 for (auto E : DiagnosticExprs)
4836 PDiag << E->getSourceRange();
4837
4838 CheckFormatHandler::EmitFormatDiagnostic(
4839 S, IsFunctionCall, DiagnosticExprs[0],
4840 PDiag, Loc, /*IsStringLocation*/false,
4841 DiagnosticExprs[0]->getSourceRange());
4842}
4843
Ted Kremenekce815422010-07-19 21:25:57 +00004844bool
4845CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
4846 SourceLocation Loc,
4847 const char *startSpec,
4848 unsigned specifierLen,
4849 const char *csStart,
4850 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00004851 bool keepGoing = true;
4852 if (argIndex < NumDataArgs) {
4853 // Consider the argument coverered, even though the specifier doesn't
4854 // make sense.
4855 CoveredArgs.set(argIndex);
4856 }
4857 else {
4858 // If argIndex exceeds the number of data arguments we
4859 // don't issue a warning because that is just a cascade of warnings (and
4860 // they may have intended '%%' anyway). We don't want to continue processing
4861 // the format string after this point, however, as we will like just get
4862 // gibberish when trying to match arguments.
4863 keepGoing = false;
4864 }
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00004865
4866 StringRef Specifier(csStart, csLen);
4867
4868 // If the specifier in non-printable, it could be the first byte of a UTF-8
4869 // sequence. In that case, print the UTF-8 code point. If not, print the byte
4870 // hex value.
4871 std::string CodePointStr;
4872 if (!llvm::sys::locale::isPrint(*csStart)) {
Justin Lebar90910552016-09-30 00:38:45 +00004873 llvm::UTF32 CodePoint;
4874 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
4875 const llvm::UTF8 *E =
4876 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
4877 llvm::ConversionResult Result =
4878 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00004879
Justin Lebar90910552016-09-30 00:38:45 +00004880 if (Result != llvm::conversionOK) {
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00004881 unsigned char FirstChar = *csStart;
Justin Lebar90910552016-09-30 00:38:45 +00004882 CodePoint = (llvm::UTF32)FirstChar;
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00004883 }
4884
4885 llvm::raw_string_ostream OS(CodePointStr);
4886 if (CodePoint < 256)
4887 OS << "\\x" << llvm::format("%02x", CodePoint);
4888 else if (CodePoint <= 0xFFFF)
4889 OS << "\\u" << llvm::format("%04x", CodePoint);
4890 else
4891 OS << "\\U" << llvm::format("%08x", CodePoint);
4892 OS.flush();
4893 Specifier = CodePointStr;
4894 }
4895
4896 EmitFormatDiagnostic(
4897 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
4898 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
4899
Ted Kremenekce815422010-07-19 21:25:57 +00004900 return keepGoing;
4901}
4902
Richard Trieu03cf7b72011-10-28 00:41:25 +00004903void
4904CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
4905 const char *startSpec,
4906 unsigned specifierLen) {
4907 EmitFormatDiagnostic(
4908 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
4909 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
4910}
4911
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004912bool
4913CheckFormatHandler::CheckNumArgs(
4914 const analyze_format_string::FormatSpecifier &FS,
4915 const analyze_format_string::ConversionSpecifier &CS,
4916 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
4917
4918 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004919 PartialDiagnostic PDiag = FS.usesPositionalArg()
4920 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
4921 << (argIndex+1) << NumDataArgs)
4922 : S.PDiag(diag::warn_printf_insufficient_data_args);
4923 EmitFormatDiagnostic(
4924 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
4925 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004926
4927 // Since more arguments than conversion tokens are given, by extension
4928 // all arguments are covered, so mark this as so.
4929 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004930 return false;
4931 }
4932 return true;
4933}
4934
Richard Trieu03cf7b72011-10-28 00:41:25 +00004935template<typename Range>
4936void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
4937 SourceLocation Loc,
4938 bool IsStringLocation,
4939 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00004940 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004941 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00004942 Loc, IsStringLocation, StringRange, FixIt);
4943}
4944
4945/// \brief If the format string is not within the funcion call, emit a note
4946/// so that the function call and string are in diagnostic messages.
4947///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00004948/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00004949/// call and only one diagnostic message will be produced. Otherwise, an
4950/// extra note will be emitted pointing to location of the format string.
4951///
4952/// \param ArgumentExpr the expression that is passed as the format string
4953/// argument in the function call. Used for getting locations when two
4954/// diagnostics are emitted.
4955///
4956/// \param PDiag the callee should already have provided any strings for the
4957/// diagnostic message. This function only adds locations and fixits
4958/// to diagnostics.
4959///
4960/// \param Loc primary location for diagnostic. If two diagnostics are
4961/// required, one will be at Loc and a new SourceLocation will be created for
4962/// the other one.
4963///
4964/// \param IsStringLocation if true, Loc points to the format string should be
4965/// used for the note. Otherwise, Loc points to the argument list and will
4966/// be used with PDiag.
4967///
4968/// \param StringRange some or all of the string to highlight. This is
4969/// templated so it can accept either a CharSourceRange or a SourceRange.
4970///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00004971/// \param FixIt optional fix it hint for the format string.
Benjamin Kramer7320b992016-06-15 14:20:56 +00004972template <typename Range>
4973void CheckFormatHandler::EmitFormatDiagnostic(
4974 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
4975 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
4976 Range StringRange, ArrayRef<FixItHint> FixIt) {
Jordan Roseaee34382012-09-05 22:56:26 +00004977 if (InFunctionCall) {
4978 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
4979 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00004980 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00004981 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004982 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
4983 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00004984
4985 const Sema::SemaDiagnosticBuilder &Note =
4986 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
4987 diag::note_format_string_defined);
4988
4989 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00004990 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00004991 }
4992}
4993
Ted Kremenek02087932010-07-16 02:11:22 +00004994//===--- CHECK: Printf format string checking ------------------------------===//
4995
4996namespace {
4997class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004998 bool ObjCContext;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004999
Ted Kremenek02087932010-07-16 02:11:22 +00005000public:
Stephen Hines648c3692016-09-16 01:07:04 +00005001 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
Ted Kremenek02087932010-07-16 02:11:22 +00005002 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005003 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00005004 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005005 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005006 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00005007 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005008 llvm::SmallBitVector &CheckedVarArgs,
5009 UncoveredArgHandler &UncoveredArg)
Richard Smithd7293d72013-08-05 18:49:43 +00005010 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
5011 numDataArgs, beg, hasVAListArg, Args,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005012 formatIdx, inFunctionCall, CallType, CheckedVarArgs,
5013 UncoveredArg),
Richard Smithd7293d72013-08-05 18:49:43 +00005014 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00005015 {}
5016
Ted Kremenek02087932010-07-16 02:11:22 +00005017 bool HandleInvalidPrintfConversionSpecifier(
5018 const analyze_printf::PrintfSpecifier &FS,
5019 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005020 unsigned specifierLen) override;
5021
Ted Kremenek02087932010-07-16 02:11:22 +00005022 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
5023 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005024 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00005025 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5026 const char *StartSpecifier,
5027 unsigned SpecifierLen,
5028 const Expr *E);
5029
Ted Kremenek02087932010-07-16 02:11:22 +00005030 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
5031 const char *startSpecifier, unsigned specifierLen);
5032 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
5033 const analyze_printf::OptionalAmount &Amt,
5034 unsigned type,
5035 const char *startSpecifier, unsigned specifierLen);
5036 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5037 const analyze_printf::OptionalFlag &flag,
5038 const char *startSpecifier, unsigned specifierLen);
5039 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
5040 const analyze_printf::OptionalFlag &ignoredFlag,
5041 const analyze_printf::OptionalFlag &flag,
5042 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005043 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00005044 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00005045
5046 void HandleEmptyObjCModifierFlag(const char *startFlag,
5047 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00005048
Ted Kremenek2b417712015-07-02 05:39:16 +00005049 void HandleInvalidObjCModifierFlag(const char *startFlag,
5050 unsigned flagLen) override;
5051
5052 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
5053 const char *flagsEnd,
5054 const char *conversionPosition)
5055 override;
5056};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005057} // end anonymous namespace
Ted Kremenek02087932010-07-16 02:11:22 +00005058
5059bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
5060 const analyze_printf::PrintfSpecifier &FS,
5061 const char *startSpecifier,
5062 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005063 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00005064 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00005065
Ted Kremenekce815422010-07-19 21:25:57 +00005066 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5067 getLocationOfByte(CS.getStart()),
5068 startSpecifier, specifierLen,
5069 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00005070}
5071
Ted Kremenek02087932010-07-16 02:11:22 +00005072bool CheckPrintfHandler::HandleAmount(
5073 const analyze_format_string::OptionalAmount &Amt,
5074 unsigned k, const char *startSpecifier,
5075 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005076 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005077 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00005078 unsigned argIndex = Amt.getArgIndex();
5079 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005080 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
5081 << k,
5082 getLocationOfByte(Amt.getStart()),
5083 /*IsStringLocation*/true,
5084 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00005085 // Don't do any more checking. We will just emit
5086 // spurious errors.
5087 return false;
5088 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005089
Ted Kremenek5739de72010-01-29 01:06:55 +00005090 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00005091 // Although not in conformance with C99, we also allow the argument to be
5092 // an 'unsigned int' as that is a reasonably safe case. GCC also
5093 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00005094 CoveredArgs.set(argIndex);
5095 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00005096 if (!Arg)
5097 return false;
5098
Ted Kremenek5739de72010-01-29 01:06:55 +00005099 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005100
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005101 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
5102 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005103
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005104 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005105 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005106 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00005107 << T << Arg->getSourceRange(),
5108 getLocationOfByte(Amt.getStart()),
5109 /*IsStringLocation*/true,
5110 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00005111 // Don't do any more checking. We will just emit
5112 // spurious errors.
5113 return false;
5114 }
5115 }
5116 }
5117 return true;
5118}
Ted Kremenek5739de72010-01-29 01:06:55 +00005119
Tom Careb49ec692010-06-17 19:00:27 +00005120void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00005121 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005122 const analyze_printf::OptionalAmount &Amt,
5123 unsigned type,
5124 const char *startSpecifier,
5125 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005126 const analyze_printf::PrintfConversionSpecifier &CS =
5127 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00005128
Richard Trieu03cf7b72011-10-28 00:41:25 +00005129 FixItHint fixit =
5130 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
5131 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
5132 Amt.getConstantLength()))
5133 : FixItHint();
5134
5135 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
5136 << type << CS.toString(),
5137 getLocationOfByte(Amt.getStart()),
5138 /*IsStringLocation*/true,
5139 getSpecifierRange(startSpecifier, specifierLen),
5140 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00005141}
5142
Ted Kremenek02087932010-07-16 02:11:22 +00005143void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005144 const analyze_printf::OptionalFlag &flag,
5145 const char *startSpecifier,
5146 unsigned specifierLen) {
5147 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005148 const analyze_printf::PrintfConversionSpecifier &CS =
5149 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00005150 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
5151 << flag.toString() << CS.toString(),
5152 getLocationOfByte(flag.getPosition()),
5153 /*IsStringLocation*/true,
5154 getSpecifierRange(startSpecifier, specifierLen),
5155 FixItHint::CreateRemoval(
5156 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00005157}
5158
5159void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00005160 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005161 const analyze_printf::OptionalFlag &ignoredFlag,
5162 const analyze_printf::OptionalFlag &flag,
5163 const char *startSpecifier,
5164 unsigned specifierLen) {
5165 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005166 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
5167 << ignoredFlag.toString() << flag.toString(),
5168 getLocationOfByte(ignoredFlag.getPosition()),
5169 /*IsStringLocation*/true,
5170 getSpecifierRange(startSpecifier, specifierLen),
5171 FixItHint::CreateRemoval(
5172 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00005173}
5174
Ted Kremenek2b417712015-07-02 05:39:16 +00005175// void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5176// bool IsStringLocation, Range StringRange,
5177// ArrayRef<FixItHint> Fixit = None);
5178
5179void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
5180 unsigned flagLen) {
5181 // Warn about an empty flag.
5182 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
5183 getLocationOfByte(startFlag),
5184 /*IsStringLocation*/true,
5185 getSpecifierRange(startFlag, flagLen));
5186}
5187
5188void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
5189 unsigned flagLen) {
5190 // Warn about an invalid flag.
5191 auto Range = getSpecifierRange(startFlag, flagLen);
5192 StringRef flag(startFlag, flagLen);
5193 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
5194 getLocationOfByte(startFlag),
5195 /*IsStringLocation*/true,
5196 Range, FixItHint::CreateRemoval(Range));
5197}
5198
5199void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
5200 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
5201 // Warn about using '[...]' without a '@' conversion.
5202 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
5203 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
5204 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
5205 getLocationOfByte(conversionPosition),
5206 /*IsStringLocation*/true,
5207 Range, FixItHint::CreateRemoval(Range));
5208}
5209
Richard Smith55ce3522012-06-25 20:30:08 +00005210// Determines if the specified is a C++ class or struct containing
5211// a member with the specified name and kind (e.g. a CXXMethodDecl named
5212// "c_str()").
5213template<typename MemberKind>
5214static llvm::SmallPtrSet<MemberKind*, 1>
5215CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
5216 const RecordType *RT = Ty->getAs<RecordType>();
5217 llvm::SmallPtrSet<MemberKind*, 1> Results;
5218
5219 if (!RT)
5220 return Results;
5221 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00005222 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00005223 return Results;
5224
Alp Tokerb6cc5922014-05-03 03:45:55 +00005225 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00005226 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00005227 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00005228
5229 // We just need to include all members of the right kind turned up by the
5230 // filter, at this point.
5231 if (S.LookupQualifiedName(R, RT->getDecl()))
5232 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5233 NamedDecl *decl = (*I)->getUnderlyingDecl();
5234 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
5235 Results.insert(FK);
5236 }
5237 return Results;
5238}
5239
Richard Smith2868a732014-02-28 01:36:39 +00005240/// Check if we could call '.c_str()' on an object.
5241///
5242/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
5243/// allow the call, or if it would be ambiguous).
5244bool Sema::hasCStrMethod(const Expr *E) {
5245 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5246 MethodSet Results =
5247 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
5248 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5249 MI != ME; ++MI)
5250 if ((*MI)->getMinRequiredArguments() == 0)
5251 return true;
5252 return false;
5253}
5254
Richard Smith55ce3522012-06-25 20:30:08 +00005255// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005256// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00005257// Returns true when a c_str() conversion method is found.
5258bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00005259 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00005260 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5261
5262 MethodSet Results =
5263 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
5264
5265 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5266 MI != ME; ++MI) {
5267 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00005268 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00005269 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00005270 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00005271 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00005272 S.Diag(E->getLocStart(), diag::note_printf_c_str)
5273 << "c_str()"
5274 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
5275 return true;
5276 }
5277 }
5278
5279 return false;
5280}
5281
Ted Kremenekab278de2010-01-28 23:39:18 +00005282bool
Ted Kremenek02087932010-07-16 02:11:22 +00005283CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00005284 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00005285 const char *startSpecifier,
5286 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005287 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00005288 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005289 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00005290
Ted Kremenek6cd69422010-07-19 22:01:06 +00005291 if (FS.consumesDataArgument()) {
5292 if (atFirstArg) {
5293 atFirstArg = false;
5294 usesPositionalArgs = FS.usesPositionalArg();
5295 }
5296 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005297 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5298 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00005299 return false;
5300 }
Ted Kremenek5739de72010-01-29 01:06:55 +00005301 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005302
Ted Kremenekd1668192010-02-27 01:41:03 +00005303 // First check if the field width, precision, and conversion specifier
5304 // have matching data arguments.
5305 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
5306 startSpecifier, specifierLen)) {
5307 return false;
5308 }
5309
5310 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
5311 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005312 return false;
5313 }
5314
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005315 if (!CS.consumesDataArgument()) {
5316 // FIXME: Technically specifying a precision or field width here
5317 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00005318 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005319 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005320
Ted Kremenek4a49d982010-02-26 19:18:41 +00005321 // Consume the argument.
5322 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00005323 if (argIndex < NumDataArgs) {
5324 // The check to see if the argIndex is valid will come later.
5325 // We set the bit here because we may exit early from this
5326 // function if we encounter some other error.
5327 CoveredArgs.set(argIndex);
5328 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00005329
Dimitry Andric6b5ed342015-02-19 22:32:33 +00005330 // FreeBSD kernel extensions.
5331 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
5332 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
5333 // We need at least two arguments.
5334 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
5335 return false;
5336
5337 // Claim the second argument.
5338 CoveredArgs.set(argIndex + 1);
5339
5340 // Type check the first argument (int for %b, pointer for %D)
5341 const Expr *Ex = getDataArg(argIndex);
5342 const analyze_printf::ArgType &AT =
5343 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
5344 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
5345 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
5346 EmitFormatDiagnostic(
5347 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5348 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
5349 << false << Ex->getSourceRange(),
5350 Ex->getLocStart(), /*IsStringLocation*/false,
5351 getSpecifierRange(startSpecifier, specifierLen));
5352
5353 // Type check the second argument (char * for both %b and %D)
5354 Ex = getDataArg(argIndex + 1);
5355 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
5356 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
5357 EmitFormatDiagnostic(
5358 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5359 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
5360 << false << Ex->getSourceRange(),
5361 Ex->getLocStart(), /*IsStringLocation*/false,
5362 getSpecifierRange(startSpecifier, specifierLen));
5363
5364 return true;
5365 }
5366
Ted Kremenek4a49d982010-02-26 19:18:41 +00005367 // Check for using an Objective-C specific conversion specifier
5368 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005369 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00005370 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5371 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00005372 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005373
Tom Careb49ec692010-06-17 19:00:27 +00005374 // Check for invalid use of field width
5375 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00005376 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00005377 startSpecifier, specifierLen);
5378 }
5379
5380 // Check for invalid use of precision
5381 if (!FS.hasValidPrecision()) {
5382 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
5383 startSpecifier, specifierLen);
5384 }
5385
5386 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00005387 if (!FS.hasValidThousandsGroupingPrefix())
5388 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005389 if (!FS.hasValidLeadingZeros())
5390 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
5391 if (!FS.hasValidPlusPrefix())
5392 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00005393 if (!FS.hasValidSpacePrefix())
5394 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005395 if (!FS.hasValidAlternativeForm())
5396 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
5397 if (!FS.hasValidLeftJustified())
5398 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
5399
5400 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00005401 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
5402 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
5403 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005404 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
5405 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
5406 startSpecifier, specifierLen);
5407
5408 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00005409 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00005410 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5411 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00005412 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005413 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00005414 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005415 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5416 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00005417
Jordan Rose92303592012-09-08 04:00:03 +00005418 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
5419 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5420
Ted Kremenek9fcd8302010-01-29 01:43:31 +00005421 // The remaining checks depend on the data arguments.
5422 if (HasVAListArg)
5423 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005424
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005425 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00005426 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005427
Jordan Rose58bbe422012-07-19 18:10:08 +00005428 const Expr *Arg = getDataArg(argIndex);
5429 if (!Arg)
5430 return true;
5431
5432 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00005433}
5434
Jordan Roseaee34382012-09-05 22:56:26 +00005435static bool requiresParensToAddCast(const Expr *E) {
5436 // FIXME: We should have a general way to reason about operator
5437 // precedence and whether parens are actually needed here.
5438 // Take care of a few common cases where they aren't.
5439 const Expr *Inside = E->IgnoreImpCasts();
5440 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
5441 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
5442
5443 switch (Inside->getStmtClass()) {
5444 case Stmt::ArraySubscriptExprClass:
5445 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005446 case Stmt::CharacterLiteralClass:
5447 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005448 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005449 case Stmt::FloatingLiteralClass:
5450 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005451 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005452 case Stmt::ObjCArrayLiteralClass:
5453 case Stmt::ObjCBoolLiteralExprClass:
5454 case Stmt::ObjCBoxedExprClass:
5455 case Stmt::ObjCDictionaryLiteralClass:
5456 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005457 case Stmt::ObjCIvarRefExprClass:
5458 case Stmt::ObjCMessageExprClass:
5459 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005460 case Stmt::ObjCStringLiteralClass:
5461 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005462 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005463 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005464 case Stmt::UnaryOperatorClass:
5465 return false;
5466 default:
5467 return true;
5468 }
5469}
5470
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005471static std::pair<QualType, StringRef>
5472shouldNotPrintDirectly(const ASTContext &Context,
5473 QualType IntendedTy,
5474 const Expr *E) {
5475 // Use a 'while' to peel off layers of typedefs.
5476 QualType TyTy = IntendedTy;
5477 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
5478 StringRef Name = UserTy->getDecl()->getName();
5479 QualType CastTy = llvm::StringSwitch<QualType>(Name)
5480 .Case("NSInteger", Context.LongTy)
5481 .Case("NSUInteger", Context.UnsignedLongTy)
5482 .Case("SInt32", Context.IntTy)
5483 .Case("UInt32", Context.UnsignedIntTy)
5484 .Default(QualType());
5485
5486 if (!CastTy.isNull())
5487 return std::make_pair(CastTy, Name);
5488
5489 TyTy = UserTy->desugar();
5490 }
5491
5492 // Strip parens if necessary.
5493 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
5494 return shouldNotPrintDirectly(Context,
5495 PE->getSubExpr()->getType(),
5496 PE->getSubExpr());
5497
5498 // If this is a conditional expression, then its result type is constructed
5499 // via usual arithmetic conversions and thus there might be no necessary
5500 // typedef sugar there. Recurse to operands to check for NSInteger &
5501 // Co. usage condition.
5502 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5503 QualType TrueTy, FalseTy;
5504 StringRef TrueName, FalseName;
5505
5506 std::tie(TrueTy, TrueName) =
5507 shouldNotPrintDirectly(Context,
5508 CO->getTrueExpr()->getType(),
5509 CO->getTrueExpr());
5510 std::tie(FalseTy, FalseName) =
5511 shouldNotPrintDirectly(Context,
5512 CO->getFalseExpr()->getType(),
5513 CO->getFalseExpr());
5514
5515 if (TrueTy == FalseTy)
5516 return std::make_pair(TrueTy, TrueName);
5517 else if (TrueTy.isNull())
5518 return std::make_pair(FalseTy, FalseName);
5519 else if (FalseTy.isNull())
5520 return std::make_pair(TrueTy, TrueName);
5521 }
5522
5523 return std::make_pair(QualType(), StringRef());
5524}
5525
Richard Smith55ce3522012-06-25 20:30:08 +00005526bool
5527CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5528 const char *StartSpecifier,
5529 unsigned SpecifierLen,
5530 const Expr *E) {
5531 using namespace analyze_format_string;
5532 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005533 // Now type check the data expression that matches the
5534 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005535 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
5536 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00005537 if (!AT.isValid())
5538 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00005539
Jordan Rose598ec092012-12-05 18:44:40 +00005540 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00005541 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
5542 ExprTy = TET->getUnderlyingExpr()->getType();
5543 }
5544
Seth Cantrellb4802962015-03-04 03:12:10 +00005545 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
5546
5547 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00005548 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00005549 }
Jordan Rose98709982012-06-04 22:48:57 +00005550
Jordan Rose22b74712012-09-05 22:56:19 +00005551 // Look through argument promotions for our error message's reported type.
5552 // This includes the integral and floating promotions, but excludes array
5553 // and function pointer decay; seeing that an argument intended to be a
5554 // string has type 'char [6]' is probably more confusing than 'char *'.
5555 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5556 if (ICE->getCastKind() == CK_IntegralCast ||
5557 ICE->getCastKind() == CK_FloatingCast) {
5558 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00005559 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00005560
5561 // Check if we didn't match because of an implicit cast from a 'char'
5562 // or 'short' to an 'int'. This is done because printf is a varargs
5563 // function.
5564 if (ICE->getType() == S.Context.IntTy ||
5565 ICE->getType() == S.Context.UnsignedIntTy) {
5566 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00005567 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00005568 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00005569 }
Jordan Rose98709982012-06-04 22:48:57 +00005570 }
Jordan Rose598ec092012-12-05 18:44:40 +00005571 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
5572 // Special case for 'a', which has type 'int' in C.
5573 // Note, however, that we do /not/ want to treat multibyte constants like
5574 // 'MooV' as characters! This form is deprecated but still exists.
5575 if (ExprTy == S.Context.IntTy)
5576 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
5577 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00005578 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005579
Jordan Rosebc53ed12014-05-31 04:12:14 +00005580 // Look through enums to their underlying type.
5581 bool IsEnum = false;
5582 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
5583 ExprTy = EnumTy->getDecl()->getIntegerType();
5584 IsEnum = true;
5585 }
5586
Jordan Rose0e5badd2012-12-05 18:44:49 +00005587 // %C in an Objective-C context prints a unichar, not a wchar_t.
5588 // If the argument is an integer of some kind, believe the %C and suggest
5589 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00005590 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00005591 if (ObjCContext &&
5592 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
5593 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
5594 !ExprTy->isCharType()) {
5595 // 'unichar' is defined as a typedef of unsigned short, but we should
5596 // prefer using the typedef if it is visible.
5597 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00005598
5599 // While we are here, check if the value is an IntegerLiteral that happens
5600 // to be within the valid range.
5601 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
5602 const llvm::APInt &V = IL->getValue();
5603 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
5604 return true;
5605 }
5606
Jordan Rose0e5badd2012-12-05 18:44:49 +00005607 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
5608 Sema::LookupOrdinaryName);
5609 if (S.LookupName(Result, S.getCurScope())) {
5610 NamedDecl *ND = Result.getFoundDecl();
5611 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
5612 if (TD->getUnderlyingType() == IntendedTy)
5613 IntendedTy = S.Context.getTypedefType(TD);
5614 }
5615 }
5616 }
5617
5618 // Special-case some of Darwin's platform-independence types by suggesting
5619 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005620 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00005621 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005622 QualType CastTy;
5623 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
5624 if (!CastTy.isNull()) {
5625 IntendedTy = CastTy;
5626 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00005627 }
5628 }
5629
Jordan Rose22b74712012-09-05 22:56:19 +00005630 // We may be able to offer a FixItHint if it is a supported type.
5631 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00005632 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00005633 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005634
Jordan Rose22b74712012-09-05 22:56:19 +00005635 if (success) {
5636 // Get the fix string from the fixed format specifier
5637 SmallString<16> buf;
5638 llvm::raw_svector_ostream os(buf);
5639 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005640
Jordan Roseaee34382012-09-05 22:56:26 +00005641 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
5642
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005643 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00005644 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5645 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
5646 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5647 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00005648 // In this case, the specifier is wrong and should be changed to match
5649 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00005650 EmitFormatDiagnostic(S.PDiag(diag)
5651 << AT.getRepresentativeTypeName(S.Context)
5652 << IntendedTy << IsEnum << E->getSourceRange(),
5653 E->getLocStart(),
5654 /*IsStringLocation*/ false, SpecRange,
5655 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00005656 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00005657 // The canonical type for formatting this value is different from the
5658 // actual type of the expression. (This occurs, for example, with Darwin's
5659 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
5660 // should be printed as 'long' for 64-bit compatibility.)
5661 // Rather than emitting a normal format/argument mismatch, we want to
5662 // add a cast to the recommended type (and correct the format string
5663 // if necessary).
5664 SmallString<16> CastBuf;
5665 llvm::raw_svector_ostream CastFix(CastBuf);
5666 CastFix << "(";
5667 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
5668 CastFix << ")";
5669
5670 SmallVector<FixItHint,4> Hints;
5671 if (!AT.matchesType(S.Context, IntendedTy))
5672 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
5673
5674 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
5675 // If there's already a cast present, just replace it.
5676 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
5677 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
5678
5679 } else if (!requiresParensToAddCast(E)) {
5680 // If the expression has high enough precedence,
5681 // just write the C-style cast.
5682 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
5683 CastFix.str()));
5684 } else {
5685 // Otherwise, add parens around the expression as well as the cast.
5686 CastFix << "(";
5687 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
5688 CastFix.str()));
5689
Alp Tokerb6cc5922014-05-03 03:45:55 +00005690 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00005691 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
5692 }
5693
Jordan Rose0e5badd2012-12-05 18:44:49 +00005694 if (ShouldNotPrintDirectly) {
5695 // The expression has a type that should not be printed directly.
5696 // We extract the name from the typedef because we don't want to show
5697 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005698 StringRef Name;
5699 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
5700 Name = TypedefTy->getDecl()->getName();
5701 else
5702 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00005703 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00005704 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00005705 << E->getSourceRange(),
5706 E->getLocStart(), /*IsStringLocation=*/false,
5707 SpecRange, Hints);
5708 } else {
5709 // In this case, the expression could be printed using a different
5710 // specifier, but we've decided that the specifier is probably correct
5711 // and we should cast instead. Just use the normal warning message.
5712 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00005713 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5714 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00005715 << E->getSourceRange(),
5716 E->getLocStart(), /*IsStringLocation*/false,
5717 SpecRange, Hints);
5718 }
Jordan Roseaee34382012-09-05 22:56:26 +00005719 }
Jordan Rose22b74712012-09-05 22:56:19 +00005720 } else {
5721 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
5722 SpecifierLen);
5723 // Since the warning for passing non-POD types to variadic functions
5724 // was deferred until now, we emit a warning for non-POD
5725 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00005726 switch (S.isValidVarArgType(ExprTy)) {
5727 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00005728 case Sema::VAK_ValidInCXX11: {
5729 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5730 if (match == analyze_printf::ArgType::NoMatchPedantic) {
5731 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5732 }
Richard Smithd7293d72013-08-05 18:49:43 +00005733
Seth Cantrellb4802962015-03-04 03:12:10 +00005734 EmitFormatDiagnostic(
5735 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
5736 << IsEnum << CSR << E->getSourceRange(),
5737 E->getLocStart(), /*IsStringLocation*/ false, CSR);
5738 break;
5739 }
Richard Smithd7293d72013-08-05 18:49:43 +00005740 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00005741 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00005742 EmitFormatDiagnostic(
5743 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005744 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00005745 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00005746 << CallType
5747 << AT.getRepresentativeTypeName(S.Context)
5748 << CSR
5749 << E->getSourceRange(),
5750 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00005751 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00005752 break;
5753
5754 case Sema::VAK_Invalid:
5755 if (ExprTy->isObjCObjectType())
5756 EmitFormatDiagnostic(
5757 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
5758 << S.getLangOpts().CPlusPlus11
5759 << ExprTy
5760 << CallType
5761 << AT.getRepresentativeTypeName(S.Context)
5762 << CSR
5763 << E->getSourceRange(),
5764 E->getLocStart(), /*IsStringLocation*/false, CSR);
5765 else
5766 // FIXME: If this is an initializer list, suggest removing the braces
5767 // or inserting a cast to the target type.
5768 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
5769 << isa<InitListExpr>(E) << ExprTy << CallType
5770 << AT.getRepresentativeTypeName(S.Context)
5771 << E->getSourceRange();
5772 break;
5773 }
5774
5775 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
5776 "format string specifier index out of range");
5777 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005778 }
5779
Ted Kremenekab278de2010-01-28 23:39:18 +00005780 return true;
5781}
5782
Ted Kremenek02087932010-07-16 02:11:22 +00005783//===--- CHECK: Scanf format string checking ------------------------------===//
5784
5785namespace {
5786class CheckScanfHandler : public CheckFormatHandler {
5787public:
Stephen Hines648c3692016-09-16 01:07:04 +00005788 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
Ted Kremenek02087932010-07-16 02:11:22 +00005789 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005790 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005791 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005792 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00005793 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005794 llvm::SmallBitVector &CheckedVarArgs,
5795 UncoveredArgHandler &UncoveredArg)
Richard Smithd7293d72013-08-05 18:49:43 +00005796 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
5797 numDataArgs, beg, hasVAListArg,
5798 Args, formatIdx, inFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005799 CheckedVarArgs, UncoveredArg)
Jordan Rose3e0ec582012-07-19 18:10:23 +00005800 {}
Ted Kremenek02087932010-07-16 02:11:22 +00005801
5802 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
5803 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005804 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00005805
5806 bool HandleInvalidScanfConversionSpecifier(
5807 const analyze_scanf::ScanfSpecifier &FS,
5808 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005809 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00005810
Craig Toppere14c0f82014-03-12 04:55:44 +00005811 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00005812};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005813} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00005814
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00005815void CheckScanfHandler::HandleIncompleteScanList(const char *start,
5816 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005817 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
5818 getLocationOfByte(end), /*IsStringLocation*/true,
5819 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00005820}
5821
Ted Kremenekce815422010-07-19 21:25:57 +00005822bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
5823 const analyze_scanf::ScanfSpecifier &FS,
5824 const char *startSpecifier,
5825 unsigned specifierLen) {
5826
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005827 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00005828 FS.getConversionSpecifier();
5829
5830 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5831 getLocationOfByte(CS.getStart()),
5832 startSpecifier, specifierLen,
5833 CS.getStart(), CS.getLength());
5834}
5835
Ted Kremenek02087932010-07-16 02:11:22 +00005836bool CheckScanfHandler::HandleScanfSpecifier(
5837 const analyze_scanf::ScanfSpecifier &FS,
5838 const char *startSpecifier,
5839 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00005840 using namespace analyze_scanf;
5841 using namespace analyze_format_string;
5842
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005843 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00005844
Ted Kremenek6cd69422010-07-19 22:01:06 +00005845 // Handle case where '%' and '*' don't consume an argument. These shouldn't
5846 // be used to decide if we are using positional arguments consistently.
5847 if (FS.consumesDataArgument()) {
5848 if (atFirstArg) {
5849 atFirstArg = false;
5850 usesPositionalArgs = FS.usesPositionalArg();
5851 }
5852 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005853 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5854 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00005855 return false;
5856 }
Ted Kremenek02087932010-07-16 02:11:22 +00005857 }
5858
5859 // Check if the field with is non-zero.
5860 const OptionalAmount &Amt = FS.getFieldWidth();
5861 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
5862 if (Amt.getConstantAmount() == 0) {
5863 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
5864 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00005865 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
5866 getLocationOfByte(Amt.getStart()),
5867 /*IsStringLocation*/true, R,
5868 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00005869 }
5870 }
Seth Cantrellb4802962015-03-04 03:12:10 +00005871
Ted Kremenek02087932010-07-16 02:11:22 +00005872 if (!FS.consumesDataArgument()) {
5873 // FIXME: Technically specifying a precision or field width here
5874 // makes no sense. Worth issuing a warning at some point.
5875 return true;
5876 }
Seth Cantrellb4802962015-03-04 03:12:10 +00005877
Ted Kremenek02087932010-07-16 02:11:22 +00005878 // Consume the argument.
5879 unsigned argIndex = FS.getArgIndex();
5880 if (argIndex < NumDataArgs) {
5881 // The check to see if the argIndex is valid will come later.
5882 // We set the bit here because we may exit early from this
5883 // function if we encounter some other error.
5884 CoveredArgs.set(argIndex);
5885 }
Seth Cantrellb4802962015-03-04 03:12:10 +00005886
Ted Kremenek4407ea42010-07-20 20:04:47 +00005887 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00005888 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00005889 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5890 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00005891 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005892 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00005893 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005894 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5895 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005896
Jordan Rose92303592012-09-08 04:00:03 +00005897 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
5898 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5899
Ted Kremenek02087932010-07-16 02:11:22 +00005900 // The remaining checks depend on the data arguments.
5901 if (HasVAListArg)
5902 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00005903
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005904 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00005905 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00005906
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005907 // Check that the argument type matches the format specifier.
5908 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00005909 if (!Ex)
5910 return true;
5911
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00005912 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00005913
5914 if (!AT.isValid()) {
5915 return true;
5916 }
5917
Seth Cantrellb4802962015-03-04 03:12:10 +00005918 analyze_format_string::ArgType::MatchKind match =
5919 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00005920 if (match == analyze_format_string::ArgType::Match) {
5921 return true;
5922 }
Seth Cantrellb4802962015-03-04 03:12:10 +00005923
Seth Cantrell79340072015-03-04 05:58:08 +00005924 ScanfSpecifier fixedFS = FS;
5925 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
5926 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005927
Seth Cantrell79340072015-03-04 05:58:08 +00005928 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5929 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
5930 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5931 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005932
Seth Cantrell79340072015-03-04 05:58:08 +00005933 if (success) {
5934 // Get the fix string from the fixed format specifier.
5935 SmallString<128> buf;
5936 llvm::raw_svector_ostream os(buf);
5937 fixedFS.toString(os);
5938
5939 EmitFormatDiagnostic(
5940 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
5941 << Ex->getType() << false << Ex->getSourceRange(),
5942 Ex->getLocStart(),
5943 /*IsStringLocation*/ false,
5944 getSpecifierRange(startSpecifier, specifierLen),
5945 FixItHint::CreateReplacement(
5946 getSpecifierRange(startSpecifier, specifierLen), os.str()));
5947 } else {
5948 EmitFormatDiagnostic(S.PDiag(diag)
5949 << AT.getRepresentativeTypeName(S.Context)
5950 << Ex->getType() << false << Ex->getSourceRange(),
5951 Ex->getLocStart(),
5952 /*IsStringLocation*/ false,
5953 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00005954 }
5955
Ted Kremenek02087932010-07-16 02:11:22 +00005956 return true;
5957}
5958
Stephen Hines648c3692016-09-16 01:07:04 +00005959static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005960 const Expr *OrigFormatExpr,
5961 ArrayRef<const Expr *> Args,
5962 bool HasVAListArg, unsigned format_idx,
5963 unsigned firstDataArg,
5964 Sema::FormatStringType Type,
5965 bool inFunctionCall,
5966 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005967 llvm::SmallBitVector &CheckedVarArgs,
5968 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00005969 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00005970 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005971 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005972 S, inFunctionCall, Args[format_idx],
5973 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00005974 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00005975 return;
5976 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005977
Ted Kremenekab278de2010-01-28 23:39:18 +00005978 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005979 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00005980 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005981 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005982 const ConstantArrayType *T =
5983 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005984 assert(T && "String literal not of constant array type!");
5985 size_t TypeSize = T->getSize().getZExtValue();
5986 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005987 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005988
5989 // Emit a warning if the string literal is truncated and does not contain an
5990 // embedded null character.
5991 if (TypeSize <= StrRef.size() &&
5992 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
5993 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005994 S, inFunctionCall, Args[format_idx],
5995 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00005996 FExpr->getLocStart(),
5997 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
5998 return;
5999 }
6000
Ted Kremenekab278de2010-01-28 23:39:18 +00006001 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00006002 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006003 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006004 S, inFunctionCall, Args[format_idx],
6005 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00006006 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00006007 return;
6008 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006009
6010 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
6011 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSTrace) {
6012 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, firstDataArg,
6013 numDataArgs, (Type == Sema::FST_NSString ||
6014 Type == Sema::FST_OSTrace),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00006015 Str, HasVAListArg, Args, format_idx,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006016 inFunctionCall, CallType, CheckedVarArgs,
6017 UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006018
Hans Wennborg23926bd2011-12-15 10:25:47 +00006019 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006020 S.getLangOpts(),
6021 S.Context.getTargetInfo(),
6022 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00006023 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006024 } else if (Type == Sema::FST_Scanf) {
6025 CheckScanfHandler H(S, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00006026 Str, HasVAListArg, Args, format_idx,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006027 inFunctionCall, CallType, CheckedVarArgs,
6028 UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006029
Hans Wennborg23926bd2011-12-15 10:25:47 +00006030 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006031 S.getLangOpts(),
6032 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00006033 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00006034 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00006035}
6036
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00006037bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
6038 // Str - The format string. NOTE: this is NOT null-terminated!
6039 StringRef StrRef = FExpr->getString();
6040 const char *Str = StrRef.data();
6041 // Account for cases where the string literal is truncated in a declaration.
6042 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
6043 assert(T && "String literal not of constant array type!");
6044 size_t TypeSize = T->getSize().getZExtValue();
6045 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6046 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
6047 getLangOpts(),
6048 Context.getTargetInfo());
6049}
6050
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006051//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
6052
6053// Returns the related absolute value function that is larger, of 0 if one
6054// does not exist.
6055static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
6056 switch (AbsFunction) {
6057 default:
6058 return 0;
6059
6060 case Builtin::BI__builtin_abs:
6061 return Builtin::BI__builtin_labs;
6062 case Builtin::BI__builtin_labs:
6063 return Builtin::BI__builtin_llabs;
6064 case Builtin::BI__builtin_llabs:
6065 return 0;
6066
6067 case Builtin::BI__builtin_fabsf:
6068 return Builtin::BI__builtin_fabs;
6069 case Builtin::BI__builtin_fabs:
6070 return Builtin::BI__builtin_fabsl;
6071 case Builtin::BI__builtin_fabsl:
6072 return 0;
6073
6074 case Builtin::BI__builtin_cabsf:
6075 return Builtin::BI__builtin_cabs;
6076 case Builtin::BI__builtin_cabs:
6077 return Builtin::BI__builtin_cabsl;
6078 case Builtin::BI__builtin_cabsl:
6079 return 0;
6080
6081 case Builtin::BIabs:
6082 return Builtin::BIlabs;
6083 case Builtin::BIlabs:
6084 return Builtin::BIllabs;
6085 case Builtin::BIllabs:
6086 return 0;
6087
6088 case Builtin::BIfabsf:
6089 return Builtin::BIfabs;
6090 case Builtin::BIfabs:
6091 return Builtin::BIfabsl;
6092 case Builtin::BIfabsl:
6093 return 0;
6094
6095 case Builtin::BIcabsf:
6096 return Builtin::BIcabs;
6097 case Builtin::BIcabs:
6098 return Builtin::BIcabsl;
6099 case Builtin::BIcabsl:
6100 return 0;
6101 }
6102}
6103
6104// Returns the argument type of the absolute value function.
6105static QualType getAbsoluteValueArgumentType(ASTContext &Context,
6106 unsigned AbsType) {
6107 if (AbsType == 0)
6108 return QualType();
6109
6110 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
6111 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
6112 if (Error != ASTContext::GE_None)
6113 return QualType();
6114
6115 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
6116 if (!FT)
6117 return QualType();
6118
6119 if (FT->getNumParams() != 1)
6120 return QualType();
6121
6122 return FT->getParamType(0);
6123}
6124
6125// Returns the best absolute value function, or zero, based on type and
6126// current absolute value function.
6127static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
6128 unsigned AbsFunctionKind) {
6129 unsigned BestKind = 0;
6130 uint64_t ArgSize = Context.getTypeSize(ArgType);
6131 for (unsigned Kind = AbsFunctionKind; Kind != 0;
6132 Kind = getLargerAbsoluteValueFunction(Kind)) {
6133 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
6134 if (Context.getTypeSize(ParamType) >= ArgSize) {
6135 if (BestKind == 0)
6136 BestKind = Kind;
6137 else if (Context.hasSameType(ParamType, ArgType)) {
6138 BestKind = Kind;
6139 break;
6140 }
6141 }
6142 }
6143 return BestKind;
6144}
6145
6146enum AbsoluteValueKind {
6147 AVK_Integer,
6148 AVK_Floating,
6149 AVK_Complex
6150};
6151
6152static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
6153 if (T->isIntegralOrEnumerationType())
6154 return AVK_Integer;
6155 if (T->isRealFloatingType())
6156 return AVK_Floating;
6157 if (T->isAnyComplexType())
6158 return AVK_Complex;
6159
6160 llvm_unreachable("Type not integer, floating, or complex");
6161}
6162
6163// Changes the absolute value function to a different type. Preserves whether
6164// the function is a builtin.
6165static unsigned changeAbsFunction(unsigned AbsKind,
6166 AbsoluteValueKind ValueKind) {
6167 switch (ValueKind) {
6168 case AVK_Integer:
6169 switch (AbsKind) {
6170 default:
6171 return 0;
6172 case Builtin::BI__builtin_fabsf:
6173 case Builtin::BI__builtin_fabs:
6174 case Builtin::BI__builtin_fabsl:
6175 case Builtin::BI__builtin_cabsf:
6176 case Builtin::BI__builtin_cabs:
6177 case Builtin::BI__builtin_cabsl:
6178 return Builtin::BI__builtin_abs;
6179 case Builtin::BIfabsf:
6180 case Builtin::BIfabs:
6181 case Builtin::BIfabsl:
6182 case Builtin::BIcabsf:
6183 case Builtin::BIcabs:
6184 case Builtin::BIcabsl:
6185 return Builtin::BIabs;
6186 }
6187 case AVK_Floating:
6188 switch (AbsKind) {
6189 default:
6190 return 0;
6191 case Builtin::BI__builtin_abs:
6192 case Builtin::BI__builtin_labs:
6193 case Builtin::BI__builtin_llabs:
6194 case Builtin::BI__builtin_cabsf:
6195 case Builtin::BI__builtin_cabs:
6196 case Builtin::BI__builtin_cabsl:
6197 return Builtin::BI__builtin_fabsf;
6198 case Builtin::BIabs:
6199 case Builtin::BIlabs:
6200 case Builtin::BIllabs:
6201 case Builtin::BIcabsf:
6202 case Builtin::BIcabs:
6203 case Builtin::BIcabsl:
6204 return Builtin::BIfabsf;
6205 }
6206 case AVK_Complex:
6207 switch (AbsKind) {
6208 default:
6209 return 0;
6210 case Builtin::BI__builtin_abs:
6211 case Builtin::BI__builtin_labs:
6212 case Builtin::BI__builtin_llabs:
6213 case Builtin::BI__builtin_fabsf:
6214 case Builtin::BI__builtin_fabs:
6215 case Builtin::BI__builtin_fabsl:
6216 return Builtin::BI__builtin_cabsf;
6217 case Builtin::BIabs:
6218 case Builtin::BIlabs:
6219 case Builtin::BIllabs:
6220 case Builtin::BIfabsf:
6221 case Builtin::BIfabs:
6222 case Builtin::BIfabsl:
6223 return Builtin::BIcabsf;
6224 }
6225 }
6226 llvm_unreachable("Unable to convert function");
6227}
6228
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00006229static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006230 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
6231 if (!FnInfo)
6232 return 0;
6233
6234 switch (FDecl->getBuiltinID()) {
6235 default:
6236 return 0;
6237 case Builtin::BI__builtin_abs:
6238 case Builtin::BI__builtin_fabs:
6239 case Builtin::BI__builtin_fabsf:
6240 case Builtin::BI__builtin_fabsl:
6241 case Builtin::BI__builtin_labs:
6242 case Builtin::BI__builtin_llabs:
6243 case Builtin::BI__builtin_cabs:
6244 case Builtin::BI__builtin_cabsf:
6245 case Builtin::BI__builtin_cabsl:
6246 case Builtin::BIabs:
6247 case Builtin::BIlabs:
6248 case Builtin::BIllabs:
6249 case Builtin::BIfabs:
6250 case Builtin::BIfabsf:
6251 case Builtin::BIfabsl:
6252 case Builtin::BIcabs:
6253 case Builtin::BIcabsf:
6254 case Builtin::BIcabsl:
6255 return FDecl->getBuiltinID();
6256 }
6257 llvm_unreachable("Unknown Builtin type");
6258}
6259
6260// If the replacement is valid, emit a note with replacement function.
6261// Additionally, suggest including the proper header if not already included.
6262static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00006263 unsigned AbsKind, QualType ArgType) {
6264 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00006265 const char *HeaderName = nullptr;
Mehdi Aminib1bdc472016-10-10 21:34:29 +00006266 StringRef FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00006267 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
6268 FunctionName = "std::abs";
6269 if (ArgType->isIntegralOrEnumerationType()) {
6270 HeaderName = "cstdlib";
6271 } else if (ArgType->isRealFloatingType()) {
6272 HeaderName = "cmath";
6273 } else {
6274 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006275 }
Richard Trieubeffb832014-04-15 23:47:53 +00006276
6277 // Lookup all std::abs
6278 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00006279 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00006280 R.suppressDiagnostics();
6281 S.LookupQualifiedName(R, Std);
6282
6283 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006284 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00006285 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
6286 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
6287 } else {
6288 FDecl = dyn_cast<FunctionDecl>(I);
6289 }
6290 if (!FDecl)
6291 continue;
6292
6293 // Found std::abs(), check that they are the right ones.
6294 if (FDecl->getNumParams() != 1)
6295 continue;
6296
6297 // Check that the parameter type can handle the argument.
6298 QualType ParamType = FDecl->getParamDecl(0)->getType();
6299 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
6300 S.Context.getTypeSize(ArgType) <=
6301 S.Context.getTypeSize(ParamType)) {
6302 // Found a function, don't need the header hint.
6303 EmitHeaderHint = false;
6304 break;
6305 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006306 }
Richard Trieubeffb832014-04-15 23:47:53 +00006307 }
6308 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00006309 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00006310 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
6311
6312 if (HeaderName) {
6313 DeclarationName DN(&S.Context.Idents.get(FunctionName));
6314 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
6315 R.suppressDiagnostics();
6316 S.LookupName(R, S.getCurScope());
6317
6318 if (R.isSingleResult()) {
6319 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
6320 if (FD && FD->getBuiltinID() == AbsKind) {
6321 EmitHeaderHint = false;
6322 } else {
6323 return;
6324 }
6325 } else if (!R.empty()) {
6326 return;
6327 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006328 }
6329 }
6330
6331 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00006332 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006333
Richard Trieubeffb832014-04-15 23:47:53 +00006334 if (!HeaderName)
6335 return;
6336
6337 if (!EmitHeaderHint)
6338 return;
6339
Alp Toker5d96e0a2014-07-11 20:53:51 +00006340 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
6341 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00006342}
6343
6344static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
6345 if (!FDecl)
6346 return false;
6347
6348 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
6349 return false;
6350
6351 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
6352
6353 while (ND && ND->isInlineNamespace()) {
6354 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006355 }
Richard Trieubeffb832014-04-15 23:47:53 +00006356
6357 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
6358 return false;
6359
6360 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
6361 return false;
6362
6363 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006364}
6365
6366// Warn when using the wrong abs() function.
6367void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
6368 const FunctionDecl *FDecl,
6369 IdentifierInfo *FnInfo) {
6370 if (Call->getNumArgs() != 1)
6371 return;
6372
6373 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00006374 bool IsStdAbs = IsFunctionStdAbs(FDecl);
6375 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006376 return;
6377
6378 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6379 QualType ParamType = Call->getArg(0)->getType();
6380
Alp Toker5d96e0a2014-07-11 20:53:51 +00006381 // Unsigned types cannot be negative. Suggest removing the absolute value
6382 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006383 if (ArgType->isUnsignedIntegerType()) {
Mehdi Aminib1bdc472016-10-10 21:34:29 +00006384 StringRef FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00006385 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006386 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
6387 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00006388 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006389 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
6390 return;
6391 }
6392
David Majnemer7f77eb92015-11-15 03:04:34 +00006393 // Taking the absolute value of a pointer is very suspicious, they probably
6394 // wanted to index into an array, dereference a pointer, call a function, etc.
6395 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
6396 unsigned DiagType = 0;
6397 if (ArgType->isFunctionType())
6398 DiagType = 1;
6399 else if (ArgType->isArrayType())
6400 DiagType = 2;
6401
6402 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
6403 return;
6404 }
6405
Richard Trieubeffb832014-04-15 23:47:53 +00006406 // std::abs has overloads which prevent most of the absolute value problems
6407 // from occurring.
6408 if (IsStdAbs)
6409 return;
6410
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006411 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
6412 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
6413
6414 // The argument and parameter are the same kind. Check if they are the right
6415 // size.
6416 if (ArgValueKind == ParamValueKind) {
6417 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
6418 return;
6419
6420 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
6421 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
6422 << FDecl << ArgType << ParamType;
6423
6424 if (NewAbsKind == 0)
6425 return;
6426
6427 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00006428 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006429 return;
6430 }
6431
6432 // ArgValueKind != ParamValueKind
6433 // The wrong type of absolute value function was used. Attempt to find the
6434 // proper one.
6435 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
6436 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
6437 if (NewAbsKind == 0)
6438 return;
6439
6440 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
6441 << FDecl << ParamValueKind << ArgValueKind;
6442
6443 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00006444 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006445}
6446
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006447//===--- CHECK: Standard memory functions ---------------------------------===//
6448
Nico Weber0e6daef2013-12-26 23:38:39 +00006449/// \brief Takes the expression passed to the size_t parameter of functions
6450/// such as memcmp, strncat, etc and warns if it's a comparison.
6451///
6452/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
6453static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
6454 IdentifierInfo *FnName,
6455 SourceLocation FnLoc,
6456 SourceLocation RParenLoc) {
6457 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
6458 if (!Size)
6459 return false;
6460
6461 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
6462 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
6463 return false;
6464
Nico Weber0e6daef2013-12-26 23:38:39 +00006465 SourceRange SizeRange = Size->getSourceRange();
6466 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
6467 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00006468 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00006469 << FnName << FixItHint::CreateInsertion(
6470 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00006471 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00006472 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00006473 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00006474 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
6475 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00006476
6477 return true;
6478}
6479
Reid Kleckner5fb5b122014-06-27 23:58:21 +00006480/// \brief Determine whether the given type is or contains a dynamic class type
6481/// (e.g., whether it has a vtable).
6482static const CXXRecordDecl *getContainedDynamicClass(QualType T,
6483 bool &IsContained) {
6484 // Look through array types while ignoring qualifiers.
6485 const Type *Ty = T->getBaseElementTypeUnsafe();
6486 IsContained = false;
6487
6488 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
6489 RD = RD ? RD->getDefinition() : nullptr;
Richard Trieu1c7237a2016-03-31 04:18:07 +00006490 if (!RD || RD->isInvalidDecl())
Reid Kleckner5fb5b122014-06-27 23:58:21 +00006491 return nullptr;
6492
6493 if (RD->isDynamicClass())
6494 return RD;
6495
6496 // Check all the fields. If any bases were dynamic, the class is dynamic.
6497 // It's impossible for a class to transitively contain itself by value, so
6498 // infinite recursion is impossible.
6499 for (auto *FD : RD->fields()) {
6500 bool SubContained;
6501 if (const CXXRecordDecl *ContainedRD =
6502 getContainedDynamicClass(FD->getType(), SubContained)) {
6503 IsContained = true;
6504 return ContainedRD;
6505 }
6506 }
6507
6508 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00006509}
6510
Chandler Carruth889ed862011-06-21 23:04:20 +00006511/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006512/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00006513static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00006514 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006515 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6516 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
6517 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00006518
Craig Topperc3ec1492014-05-26 06:22:03 +00006519 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006520}
6521
Chandler Carruth889ed862011-06-21 23:04:20 +00006522/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00006523static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006524 if (const UnaryExprOrTypeTraitExpr *SizeOf =
6525 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6526 if (SizeOf->getKind() == clang::UETT_SizeOf)
6527 return SizeOf->getTypeOfArgument();
6528
6529 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00006530}
6531
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006532/// \brief Check for dangerous or invalid arguments to memset().
6533///
Chandler Carruthac687262011-06-03 06:23:57 +00006534/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00006535/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
6536/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006537///
6538/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00006539void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00006540 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00006541 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00006542 assert(BId != 0);
6543
Ted Kremenekb5fabb22011-04-28 01:38:02 +00006544 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00006545 // we have enough arguments, and if not, abort further checking.
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00006546 unsigned ExpectedNumArgs =
6547 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00006548 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00006549 return;
6550
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00006551 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
Anna Zaks22122702012-01-17 00:37:07 +00006552 BId == Builtin::BIstrndup ? 1 : 2);
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00006553 unsigned LenArg =
6554 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00006555 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006556
Nico Weber0e6daef2013-12-26 23:38:39 +00006557 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
6558 Call->getLocStart(), Call->getRParenLoc()))
6559 return;
6560
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006561 // We have special checking when the length is a sizeof expression.
6562 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
6563 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
6564 llvm::FoldingSetNodeID SizeOfArgID;
6565
Bruno Cardoso Lopesc73e4c32016-08-11 18:33:15 +00006566 // Although widely used, 'bzero' is not a standard function. Be more strict
6567 // with the argument types before allowing diagnostics and only allow the
6568 // form bzero(ptr, sizeof(...)).
6569 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6570 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
6571 return;
6572
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006573 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
6574 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00006575 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006576
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006577 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00006578 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006579 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00006580 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00006581
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006582 // Never warn about void type pointers. This can be used to suppress
6583 // false positives.
6584 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006585 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006586
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006587 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
6588 // actually comparing the expressions for equality. Because computing the
6589 // expression IDs can be expensive, we only do this if the diagnostic is
6590 // enabled.
6591 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006592 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
6593 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006594 // We only compute IDs for expressions if the warning is enabled, and
6595 // cache the sizeof arg's ID.
6596 if (SizeOfArgID == llvm::FoldingSetNodeID())
6597 SizeOfArg->Profile(SizeOfArgID, Context, true);
6598 llvm::FoldingSetNodeID DestID;
6599 Dest->Profile(DestID, Context, true);
6600 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00006601 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
6602 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006603 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00006604 StringRef ReadableName = FnName->getName();
6605
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006606 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00006607 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006608 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00006609 if (!PointeeTy->isIncompleteType() &&
6610 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006611 ActionIdx = 2; // If the pointee's size is sizeof(char),
6612 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00006613
6614 // If the function is defined as a builtin macro, do not show macro
6615 // expansion.
6616 SourceLocation SL = SizeOfArg->getExprLoc();
6617 SourceRange DSR = Dest->getSourceRange();
6618 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00006619 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00006620
6621 if (SM.isMacroArgExpansion(SL)) {
6622 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
6623 SL = SM.getSpellingLoc(SL);
6624 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
6625 SM.getSpellingLoc(DSR.getEnd()));
6626 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
6627 SM.getSpellingLoc(SSR.getEnd()));
6628 }
6629
Anna Zaksd08d9152012-05-30 23:14:52 +00006630 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006631 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00006632 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00006633 << PointeeTy
6634 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00006635 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00006636 << SSR);
6637 DiagRuntimeBehavior(SL, SizeOfArg,
6638 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
6639 << ActionIdx
6640 << SSR);
6641
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006642 break;
6643 }
6644 }
6645
6646 // Also check for cases where the sizeof argument is the exact same
6647 // type as the memory argument, and where it points to a user-defined
6648 // record type.
6649 if (SizeOfArgTy != QualType()) {
6650 if (PointeeTy->isRecordType() &&
6651 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
6652 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
6653 PDiag(diag::warn_sizeof_pointer_type_memaccess)
6654 << FnName << SizeOfArgTy << ArgIdx
6655 << PointeeTy << Dest->getSourceRange()
6656 << LenExpr->getSourceRange());
6657 break;
6658 }
Nico Weberc5e73862011-06-14 16:14:58 +00006659 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00006660 } else if (DestTy->isArrayType()) {
6661 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00006662 }
Nico Weberc5e73862011-06-14 16:14:58 +00006663
Nico Weberc44b35e2015-03-21 17:37:46 +00006664 if (PointeeTy == QualType())
6665 continue;
Anna Zaks22122702012-01-17 00:37:07 +00006666
Nico Weberc44b35e2015-03-21 17:37:46 +00006667 // Always complain about dynamic classes.
6668 bool IsContained;
6669 if (const CXXRecordDecl *ContainedRD =
6670 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00006671
Nico Weberc44b35e2015-03-21 17:37:46 +00006672 unsigned OperationType = 0;
6673 // "overwritten" if we're warning about the destination for any call
6674 // but memcmp; otherwise a verb appropriate to the call.
6675 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
6676 if (BId == Builtin::BImemcpy)
6677 OperationType = 1;
6678 else if(BId == Builtin::BImemmove)
6679 OperationType = 2;
6680 else if (BId == Builtin::BImemcmp)
6681 OperationType = 3;
6682 }
6683
John McCall31168b02011-06-15 23:02:42 +00006684 DiagRuntimeBehavior(
6685 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00006686 PDiag(diag::warn_dyn_class_memaccess)
6687 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
6688 << FnName << IsContained << ContainedRD << OperationType
6689 << Call->getCallee()->getSourceRange());
6690 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
6691 BId != Builtin::BImemset)
6692 DiagRuntimeBehavior(
6693 Dest->getExprLoc(), Dest,
6694 PDiag(diag::warn_arc_object_memaccess)
6695 << ArgIdx << FnName << PointeeTy
6696 << Call->getCallee()->getSourceRange());
6697 else
6698 continue;
6699
6700 DiagRuntimeBehavior(
6701 Dest->getExprLoc(), Dest,
6702 PDiag(diag::note_bad_memaccess_silence)
6703 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
6704 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006705 }
6706}
6707
Ted Kremenek6865f772011-08-18 20:55:45 +00006708// A little helper routine: ignore addition and subtraction of integer literals.
6709// This intentionally does not ignore all integer constant expressions because
6710// we don't want to remove sizeof().
6711static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
6712 Ex = Ex->IgnoreParenCasts();
6713
6714 for (;;) {
6715 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
6716 if (!BO || !BO->isAdditiveOp())
6717 break;
6718
6719 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
6720 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
6721
6722 if (isa<IntegerLiteral>(RHS))
6723 Ex = LHS;
6724 else if (isa<IntegerLiteral>(LHS))
6725 Ex = RHS;
6726 else
6727 break;
6728 }
6729
6730 return Ex;
6731}
6732
Anna Zaks13b08572012-08-08 21:42:23 +00006733static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
6734 ASTContext &Context) {
6735 // Only handle constant-sized or VLAs, but not flexible members.
6736 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
6737 // Only issue the FIXIT for arrays of size > 1.
6738 if (CAT->getSize().getSExtValue() <= 1)
6739 return false;
6740 } else if (!Ty->isVariableArrayType()) {
6741 return false;
6742 }
6743 return true;
6744}
6745
Ted Kremenek6865f772011-08-18 20:55:45 +00006746// Warn if the user has made the 'size' argument to strlcpy or strlcat
6747// be the size of the source, instead of the destination.
6748void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
6749 IdentifierInfo *FnName) {
6750
6751 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00006752 unsigned NumArgs = Call->getNumArgs();
6753 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00006754 return;
6755
6756 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
6757 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00006758 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00006759
6760 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
6761 Call->getLocStart(), Call->getRParenLoc()))
6762 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00006763
6764 // Look for 'strlcpy(dst, x, sizeof(x))'
6765 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
6766 CompareWithSrc = Ex;
6767 else {
6768 // Look for 'strlcpy(dst, x, strlen(x))'
6769 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00006770 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
6771 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00006772 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
6773 }
6774 }
6775
6776 if (!CompareWithSrc)
6777 return;
6778
6779 // Determine if the argument to sizeof/strlen is equal to the source
6780 // argument. In principle there's all kinds of things you could do
6781 // here, for instance creating an == expression and evaluating it with
6782 // EvaluateAsBooleanCondition, but this uses a more direct technique:
6783 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
6784 if (!SrcArgDRE)
6785 return;
6786
6787 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
6788 if (!CompareWithSrcDRE ||
6789 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
6790 return;
6791
6792 const Expr *OriginalSizeArg = Call->getArg(2);
6793 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
6794 << OriginalSizeArg->getSourceRange() << FnName;
6795
6796 // Output a FIXIT hint if the destination is an array (rather than a
6797 // pointer to an array). This could be enhanced to handle some
6798 // pointers if we know the actual size, like if DstArg is 'array+2'
6799 // we could say 'sizeof(array)-2'.
6800 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00006801 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00006802 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00006803
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00006804 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00006805 llvm::raw_svector_ostream OS(sizeString);
6806 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00006807 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00006808 OS << ")";
6809
6810 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
6811 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
6812 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00006813}
6814
Anna Zaks314cd092012-02-01 19:08:57 +00006815/// Check if two expressions refer to the same declaration.
6816static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
6817 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
6818 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
6819 return D1->getDecl() == D2->getDecl();
6820 return false;
6821}
6822
6823static const Expr *getStrlenExprArg(const Expr *E) {
6824 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6825 const FunctionDecl *FD = CE->getDirectCallee();
6826 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00006827 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00006828 return CE->getArg(0)->IgnoreParenCasts();
6829 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006830 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00006831}
6832
6833// Warn on anti-patterns as the 'size' argument to strncat.
6834// The correct size argument should look like following:
6835// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
6836void Sema::CheckStrncatArguments(const CallExpr *CE,
6837 IdentifierInfo *FnName) {
6838 // Don't crash if the user has the wrong number of arguments.
6839 if (CE->getNumArgs() < 3)
6840 return;
6841 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
6842 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
6843 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
6844
Nico Weber0e6daef2013-12-26 23:38:39 +00006845 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
6846 CE->getRParenLoc()))
6847 return;
6848
Anna Zaks314cd092012-02-01 19:08:57 +00006849 // Identify common expressions, which are wrongly used as the size argument
6850 // to strncat and may lead to buffer overflows.
6851 unsigned PatternType = 0;
6852 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
6853 // - sizeof(dst)
6854 if (referToTheSameDecl(SizeOfArg, DstArg))
6855 PatternType = 1;
6856 // - sizeof(src)
6857 else if (referToTheSameDecl(SizeOfArg, SrcArg))
6858 PatternType = 2;
6859 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
6860 if (BE->getOpcode() == BO_Sub) {
6861 const Expr *L = BE->getLHS()->IgnoreParenCasts();
6862 const Expr *R = BE->getRHS()->IgnoreParenCasts();
6863 // - sizeof(dst) - strlen(dst)
6864 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
6865 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
6866 PatternType = 1;
6867 // - sizeof(src) - (anything)
6868 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
6869 PatternType = 2;
6870 }
6871 }
6872
6873 if (PatternType == 0)
6874 return;
6875
Anna Zaks5069aa32012-02-03 01:27:37 +00006876 // Generate the diagnostic.
6877 SourceLocation SL = LenArg->getLocStart();
6878 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00006879 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00006880
6881 // If the function is defined as a builtin macro, do not show macro expansion.
6882 if (SM.isMacroArgExpansion(SL)) {
6883 SL = SM.getSpellingLoc(SL);
6884 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
6885 SM.getSpellingLoc(SR.getEnd()));
6886 }
6887
Anna Zaks13b08572012-08-08 21:42:23 +00006888 // Check if the destination is an array (rather than a pointer to an array).
6889 QualType DstTy = DstArg->getType();
6890 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
6891 Context);
6892 if (!isKnownSizeArray) {
6893 if (PatternType == 1)
6894 Diag(SL, diag::warn_strncat_wrong_size) << SR;
6895 else
6896 Diag(SL, diag::warn_strncat_src_size) << SR;
6897 return;
6898 }
6899
Anna Zaks314cd092012-02-01 19:08:57 +00006900 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00006901 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00006902 else
Anna Zaks5069aa32012-02-03 01:27:37 +00006903 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00006904
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00006905 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00006906 llvm::raw_svector_ostream OS(sizeString);
6907 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00006908 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00006909 OS << ") - ";
6910 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00006911 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00006912 OS << ") - 1";
6913
Anna Zaks5069aa32012-02-03 01:27:37 +00006914 Diag(SL, diag::note_strncat_wrong_size)
6915 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00006916}
6917
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006918//===--- CHECK: Return Address of Stack Variable --------------------------===//
6919
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006920static const Expr *EvalVal(const Expr *E,
6921 SmallVectorImpl<const DeclRefExpr *> &refVars,
6922 const Decl *ParentDecl);
6923static const Expr *EvalAddr(const Expr *E,
6924 SmallVectorImpl<const DeclRefExpr *> &refVars,
6925 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006926
6927/// CheckReturnStackAddr - Check if a return statement returns the address
6928/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006929static void
6930CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
6931 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00006932
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006933 const Expr *stackE = nullptr;
6934 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006935
6936 // Perform checking for returned stack addresses, local blocks,
6937 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00006938 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006939 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006940 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00006941 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006942 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006943 }
6944
Craig Topperc3ec1492014-05-26 06:22:03 +00006945 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006946 return; // Nothing suspicious was found.
6947
Richard Trieu81b6c562016-08-05 23:24:47 +00006948 // Parameters are initalized in the calling scope, so taking the address
6949 // of a parameter reference doesn't need a warning.
6950 for (auto *DRE : refVars)
6951 if (isa<ParmVarDecl>(DRE->getDecl()))
6952 return;
6953
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006954 SourceLocation diagLoc;
6955 SourceRange diagRange;
6956 if (refVars.empty()) {
6957 diagLoc = stackE->getLocStart();
6958 diagRange = stackE->getSourceRange();
6959 } else {
6960 // We followed through a reference variable. 'stackE' contains the
6961 // problematic expression but we will warn at the return statement pointing
6962 // at the reference variable. We will later display the "trail" of
6963 // reference variables using notes.
6964 diagLoc = refVars[0]->getLocStart();
6965 diagRange = refVars[0]->getSourceRange();
6966 }
6967
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006968 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
6969 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00006970 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006971 << DR->getDecl()->getDeclName() << diagRange;
6972 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006973 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006974 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006975 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006976 } else { // local temporary.
Richard Trieu81b6c562016-08-05 23:24:47 +00006977 // If there is an LValue->RValue conversion, then the value of the
6978 // reference type is used, not the reference.
6979 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
6980 if (ICE->getCastKind() == CK_LValueToRValue) {
6981 return;
6982 }
6983 }
Craig Topperda7b27f2015-11-17 05:40:09 +00006984 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
6985 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006986 }
6987
6988 // Display the "trail" of reference variables that we followed until we
6989 // found the problematic expression using notes.
6990 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006991 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006992 // If this var binds to another reference var, show the range of the next
6993 // var, otherwise the var binds to the problematic expression, in which case
6994 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006995 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
6996 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006997 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
6998 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006999 }
7000}
7001
7002/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
7003/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007004/// to a location on the stack, a local block, an address of a label, or a
7005/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007006/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007007/// encounter a subexpression that (1) clearly does not lead to one of the
7008/// above problematic expressions (2) is something we cannot determine leads to
7009/// a problematic expression based on such local checking.
7010///
7011/// Both EvalAddr and EvalVal follow through reference variables to evaluate
7012/// the expression that they point to. Such variables are added to the
7013/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007014///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00007015/// EvalAddr processes expressions that are pointers that are used as
7016/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007017/// At the base case of the recursion is a check for the above problematic
7018/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007019///
7020/// This implementation handles:
7021///
7022/// * pointer-to-pointer casts
7023/// * implicit conversions from array references to pointers
7024/// * taking the address of fields
7025/// * arbitrary interplay between "&" and "*" operators
7026/// * pointer arithmetic from an address of a stack variable
7027/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007028static const Expr *EvalAddr(const Expr *E,
7029 SmallVectorImpl<const DeclRefExpr *> &refVars,
7030 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007031 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00007032 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007033
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007034 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00007035 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00007036 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007037 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00007038 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00007039
Peter Collingbourne91147592011-04-15 00:35:48 +00007040 E = E->IgnoreParens();
7041
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007042 // Our "symbolic interpreter" is just a dispatch off the currently
7043 // viewed AST node. We then recursively traverse the AST by calling
7044 // EvalAddr and EvalVal appropriately.
7045 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007046 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007047 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007048
Richard Smith40f08eb2014-01-30 22:05:38 +00007049 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00007050 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00007051 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00007052
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007053 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007054 // If this is a reference variable, follow through to the expression that
7055 // it points to.
7056 if (V->hasLocalStorage() &&
7057 V->getType()->isReferenceType() && V->hasInit()) {
7058 // Add the reference variable to the "trail".
7059 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007060 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007061 }
7062
Craig Topperc3ec1492014-05-26 06:22:03 +00007063 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007064 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007065
Chris Lattner934edb22007-12-28 05:31:15 +00007066 case Stmt::UnaryOperatorClass: {
7067 // The only unary operator that make sense to handle here
7068 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007069 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007070
John McCalle3027922010-08-25 11:45:40 +00007071 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007072 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007073 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007074 }
Mike Stump11289f42009-09-09 15:08:12 +00007075
Chris Lattner934edb22007-12-28 05:31:15 +00007076 case Stmt::BinaryOperatorClass: {
7077 // Handle pointer arithmetic. All other binary operators are not valid
7078 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007079 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00007080 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00007081
John McCalle3027922010-08-25 11:45:40 +00007082 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00007083 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007084
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007085 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00007086
7087 // Determine which argument is the real pointer base. It could be
7088 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007089 if (!Base->getType()->isPointerType())
7090 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00007091
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007092 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007093 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00007094 }
Steve Naroff2752a172008-09-10 19:17:48 +00007095
Chris Lattner934edb22007-12-28 05:31:15 +00007096 // For conditional operators we need to see if either the LHS or RHS are
7097 // valid DeclRefExpr*s. If one of them is valid, we return it.
7098 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007099 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007100
Chris Lattner934edb22007-12-28 05:31:15 +00007101 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007102 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007103 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007104 // In C++, we can have a throw-expression, which has 'void' type.
7105 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007106 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007107 return LHS;
7108 }
Chris Lattner934edb22007-12-28 05:31:15 +00007109
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007110 // In C++, we can have a throw-expression, which has 'void' type.
7111 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00007112 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007113
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007114 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00007115 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007116
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007117 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00007118 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007119 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00007120 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007121
7122 case Stmt::AddrLabelExprClass:
7123 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00007124
John McCall28fc7092011-11-10 05:35:25 +00007125 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007126 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7127 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00007128
Ted Kremenekc3b4c522008-08-07 00:49:01 +00007129 // For casts, we need to handle conversions from arrays to
7130 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00007131 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00007132 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00007133 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00007134 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00007135 case Stmt::CXXStaticCastExprClass:
7136 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00007137 case Stmt::CXXConstCastExprClass:
7138 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007139 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00007140 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00007141 case CK_LValueToRValue:
7142 case CK_NoOp:
7143 case CK_BaseToDerived:
7144 case CK_DerivedToBase:
7145 case CK_UncheckedDerivedToBase:
7146 case CK_Dynamic:
7147 case CK_CPointerToObjCPointerCast:
7148 case CK_BlockPointerToObjCPointerCast:
7149 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007150 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00007151
7152 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007153 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00007154
Richard Trieudadefde2014-07-02 04:39:38 +00007155 case CK_BitCast:
7156 if (SubExpr->getType()->isAnyPointerType() ||
7157 SubExpr->getType()->isBlockPointerType() ||
7158 SubExpr->getType()->isObjCQualifiedIdType())
7159 return EvalAddr(SubExpr, refVars, ParentDecl);
7160 else
7161 return nullptr;
7162
Eli Friedman8195ad72012-02-23 23:04:32 +00007163 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00007164 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00007165 }
Chris Lattner934edb22007-12-28 05:31:15 +00007166 }
Mike Stump11289f42009-09-09 15:08:12 +00007167
Douglas Gregorfe314812011-06-21 17:03:29 +00007168 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007169 if (const Expr *Result =
7170 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7171 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00007172 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00007173 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007174
Chris Lattner934edb22007-12-28 05:31:15 +00007175 // Everything else: we simply don't reason about them.
7176 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00007177 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00007178 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007179}
Mike Stump11289f42009-09-09 15:08:12 +00007180
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007181/// EvalVal - This function is complements EvalAddr in the mutual recursion.
7182/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007183static const Expr *EvalVal(const Expr *E,
7184 SmallVectorImpl<const DeclRefExpr *> &refVars,
7185 const Decl *ParentDecl) {
7186 do {
7187 // We should only be called for evaluating non-pointer expressions, or
7188 // expressions with a pointer type that are not used as references but
7189 // instead
7190 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00007191
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007192 // Our "symbolic interpreter" is just a dispatch off the currently
7193 // viewed AST node. We then recursively traverse the AST by calling
7194 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00007195
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007196 E = E->IgnoreParens();
7197 switch (E->getStmtClass()) {
7198 case Stmt::ImplicitCastExprClass: {
7199 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
7200 if (IE->getValueKind() == VK_LValue) {
7201 E = IE->getSubExpr();
7202 continue;
7203 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007204 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007205 }
Richard Smith40f08eb2014-01-30 22:05:38 +00007206
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007207 case Stmt::ExprWithCleanupsClass:
7208 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7209 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007210
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007211 case Stmt::DeclRefExprClass: {
7212 // When we hit a DeclRefExpr we are looking at code that refers to a
7213 // variable's name. If it's not a reference variable we check if it has
7214 // local storage within the function, and if so, return the expression.
7215 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7216
7217 // If we leave the immediate function, the lifetime isn't about to end.
7218 if (DR->refersToEnclosingVariableOrCapture())
7219 return nullptr;
7220
7221 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
7222 // Check if it refers to itself, e.g. "int& i = i;".
7223 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007224 return DR;
7225
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007226 if (V->hasLocalStorage()) {
7227 if (!V->getType()->isReferenceType())
7228 return DR;
7229
7230 // Reference variable, follow through to the expression that
7231 // it points to.
7232 if (V->hasInit()) {
7233 // Add the reference variable to the "trail".
7234 refVars.push_back(DR);
7235 return EvalVal(V->getInit(), refVars, V);
7236 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007237 }
7238 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007239
7240 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007241 }
Mike Stump11289f42009-09-09 15:08:12 +00007242
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007243 case Stmt::UnaryOperatorClass: {
7244 // The only unary operator that make sense to handle here
7245 // is Deref. All others don't resolve to a "name." This includes
7246 // handling all sorts of rvalues passed to a unary operator.
7247 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007248
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007249 if (U->getOpcode() == UO_Deref)
7250 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00007251
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007252 return nullptr;
7253 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007254
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007255 case Stmt::ArraySubscriptExprClass: {
7256 // Array subscripts are potential references to data on the stack. We
7257 // retrieve the DeclRefExpr* for the array variable if it indeed
7258 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00007259 const auto *ASE = cast<ArraySubscriptExpr>(E);
7260 if (ASE->isTypeDependent())
7261 return nullptr;
7262 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007263 }
Mike Stump11289f42009-09-09 15:08:12 +00007264
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007265 case Stmt::OMPArraySectionExprClass: {
7266 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
7267 ParentDecl);
7268 }
Mike Stump11289f42009-09-09 15:08:12 +00007269
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007270 case Stmt::ConditionalOperatorClass: {
7271 // For conditional operators we need to see if either the LHS or RHS are
7272 // non-NULL Expr's. If one is non-NULL, we return it.
7273 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00007274
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007275 // Handle the GNU extension for missing LHS.
7276 if (const Expr *LHSExpr = C->getLHS()) {
7277 // In C++, we can have a throw-expression, which has 'void' type.
7278 if (!LHSExpr->getType()->isVoidType())
7279 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
7280 return LHS;
7281 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007282
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007283 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007284 if (C->getRHS()->getType()->isVoidType())
7285 return nullptr;
7286
7287 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007288 }
7289
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007290 // Accesses to members are potential references to data on the stack.
7291 case Stmt::MemberExprClass: {
7292 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00007293
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007294 // Check for indirect access. We only want direct field accesses.
7295 if (M->isArrow())
7296 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007297
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007298 // Check whether the member type is itself a reference, in which case
7299 // we're not going to refer to the member, but to what the member refers
7300 // to.
7301 if (M->getMemberDecl()->getType()->isReferenceType())
7302 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007303
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007304 return EvalVal(M->getBase(), refVars, ParentDecl);
7305 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00007306
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007307 case Stmt::MaterializeTemporaryExprClass:
7308 if (const Expr *Result =
7309 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7310 refVars, ParentDecl))
7311 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007312 return E;
7313
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007314 default:
7315 // Check that we don't return or take the address of a reference to a
7316 // temporary. This is only useful in C++.
7317 if (!E->isTypeDependent() && E->isRValue())
7318 return E;
7319
7320 // Everything else: we simply don't reason about them.
7321 return nullptr;
7322 }
7323 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007324}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007325
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007326void
7327Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
7328 SourceLocation ReturnLoc,
7329 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00007330 const AttrVec *Attrs,
7331 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007332 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
7333
7334 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00007335 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
7336 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00007337 CheckNonNullExpr(*this, RetValExp))
7338 Diag(ReturnLoc, diag::warn_null_ret)
7339 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00007340
7341 // C++11 [basic.stc.dynamic.allocation]p4:
7342 // If an allocation function declared with a non-throwing
7343 // exception-specification fails to allocate storage, it shall return
7344 // a null pointer. Any other allocation function that fails to allocate
7345 // storage shall indicate failure only by throwing an exception [...]
7346 if (FD) {
7347 OverloadedOperatorKind Op = FD->getOverloadedOperator();
7348 if (Op == OO_New || Op == OO_Array_New) {
7349 const FunctionProtoType *Proto
7350 = FD->getType()->castAs<FunctionProtoType>();
7351 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
7352 CheckNonNullExpr(*this, RetValExp))
7353 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
7354 << FD << getLangOpts().CPlusPlus11;
7355 }
7356 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007357}
7358
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007359//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
7360
7361/// Check for comparisons of floating point operands using != and ==.
7362/// Issue a warning if these are no self-comparisons, as they are not likely
7363/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00007364void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00007365 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
7366 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007367
7368 // Special case: check for x == x (which is OK).
7369 // Do not emit warnings for such cases.
7370 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
7371 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
7372 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00007373 return;
Mike Stump11289f42009-09-09 15:08:12 +00007374
Ted Kremenekeda40e22007-11-29 00:59:04 +00007375 // Special case: check for comparisons against literals that can be exactly
7376 // represented by APFloat. In such cases, do not emit a warning. This
7377 // is a heuristic: often comparison against such literals are used to
7378 // detect if a value in a variable has not changed. This clearly can
7379 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00007380 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
7381 if (FLL->isExact())
7382 return;
7383 } else
7384 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
7385 if (FLR->isExact())
7386 return;
Mike Stump11289f42009-09-09 15:08:12 +00007387
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007388 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00007389 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00007390 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00007391 return;
Mike Stump11289f42009-09-09 15:08:12 +00007392
David Blaikie1f4ff152012-07-16 20:47:22 +00007393 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00007394 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00007395 return;
Mike Stump11289f42009-09-09 15:08:12 +00007396
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007397 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00007398 Diag(Loc, diag::warn_floatingpoint_eq)
7399 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007400}
John McCallca01b222010-01-04 23:21:16 +00007401
John McCall70aa5392010-01-06 05:24:50 +00007402//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
7403//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00007404
John McCall70aa5392010-01-06 05:24:50 +00007405namespace {
John McCallca01b222010-01-04 23:21:16 +00007406
John McCall70aa5392010-01-06 05:24:50 +00007407/// Structure recording the 'active' range of an integer-valued
7408/// expression.
7409struct IntRange {
7410 /// The number of bits active in the int.
7411 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00007412
John McCall70aa5392010-01-06 05:24:50 +00007413 /// True if the int is known not to have negative values.
7414 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00007415
John McCall70aa5392010-01-06 05:24:50 +00007416 IntRange(unsigned Width, bool NonNegative)
7417 : Width(Width), NonNegative(NonNegative)
7418 {}
John McCallca01b222010-01-04 23:21:16 +00007419
John McCall817d4af2010-11-10 23:38:19 +00007420 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00007421 static IntRange forBoolType() {
7422 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00007423 }
7424
John McCall817d4af2010-11-10 23:38:19 +00007425 /// Returns the range of an opaque value of the given integral type.
7426 static IntRange forValueOfType(ASTContext &C, QualType T) {
7427 return forValueOfCanonicalType(C,
7428 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00007429 }
7430
John McCall817d4af2010-11-10 23:38:19 +00007431 /// Returns the range of an opaque value of a canonical integral type.
7432 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00007433 assert(T->isCanonicalUnqualified());
7434
7435 if (const VectorType *VT = dyn_cast<VectorType>(T))
7436 T = VT->getElementType().getTypePtr();
7437 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7438 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00007439 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7440 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00007441
David Majnemer6a426652013-06-07 22:07:20 +00007442 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00007443 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00007444 EnumDecl *Enum = ET->getDecl();
7445 if (!Enum->isCompleteDefinition())
7446 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00007447
David Majnemer6a426652013-06-07 22:07:20 +00007448 unsigned NumPositive = Enum->getNumPositiveBits();
7449 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00007450
David Majnemer6a426652013-06-07 22:07:20 +00007451 if (NumNegative == 0)
7452 return IntRange(NumPositive, true/*NonNegative*/);
7453 else
7454 return IntRange(std::max(NumPositive + 1, NumNegative),
7455 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00007456 }
John McCall70aa5392010-01-06 05:24:50 +00007457
7458 const BuiltinType *BT = cast<BuiltinType>(T);
7459 assert(BT->isInteger());
7460
7461 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7462 }
7463
John McCall817d4af2010-11-10 23:38:19 +00007464 /// Returns the "target" range of a canonical integral type, i.e.
7465 /// the range of values expressible in the type.
7466 ///
7467 /// This matches forValueOfCanonicalType except that enums have the
7468 /// full range of their type, not the range of their enumerators.
7469 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
7470 assert(T->isCanonicalUnqualified());
7471
7472 if (const VectorType *VT = dyn_cast<VectorType>(T))
7473 T = VT->getElementType().getTypePtr();
7474 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7475 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00007476 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7477 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00007478 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00007479 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00007480
7481 const BuiltinType *BT = cast<BuiltinType>(T);
7482 assert(BT->isInteger());
7483
7484 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7485 }
7486
7487 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00007488 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00007489 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00007490 L.NonNegative && R.NonNegative);
7491 }
7492
John McCall817d4af2010-11-10 23:38:19 +00007493 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00007494 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00007495 return IntRange(std::min(L.Width, R.Width),
7496 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00007497 }
7498};
7499
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007500IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00007501 if (value.isSigned() && value.isNegative())
7502 return IntRange(value.getMinSignedBits(), false);
7503
7504 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00007505 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00007506
7507 // isNonNegative() just checks the sign bit without considering
7508 // signedness.
7509 return IntRange(value.getActiveBits(), true);
7510}
7511
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007512IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
7513 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00007514 if (result.isInt())
7515 return GetValueRange(C, result.getInt(), MaxWidth);
7516
7517 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00007518 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
7519 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
7520 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
7521 R = IntRange::join(R, El);
7522 }
John McCall70aa5392010-01-06 05:24:50 +00007523 return R;
7524 }
7525
7526 if (result.isComplexInt()) {
7527 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
7528 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
7529 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00007530 }
7531
7532 // This can happen with lossless casts to intptr_t of "based" lvalues.
7533 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00007534 // FIXME: The only reason we need to pass the type in here is to get
7535 // the sign right on this one case. It would be nice if APValue
7536 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007537 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00007538 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00007539}
John McCall70aa5392010-01-06 05:24:50 +00007540
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007541QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00007542 QualType Ty = E->getType();
7543 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
7544 Ty = AtomicRHS->getValueType();
7545 return Ty;
7546}
7547
John McCall70aa5392010-01-06 05:24:50 +00007548/// Pseudo-evaluate the given integer expression, estimating the
7549/// range of values it might take.
7550///
7551/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007552IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00007553 E = E->IgnoreParens();
7554
7555 // Try a full evaluation first.
7556 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00007557 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00007558 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00007559
7560 // I think we only want to look through implicit casts here; if the
7561 // user has an explicit widening cast, we should treat the value as
7562 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007563 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00007564 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00007565 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
7566
Eli Friedmane6d33952013-07-08 20:20:06 +00007567 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00007568
George Burgess IVdf1ed002016-01-13 01:52:39 +00007569 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
7570 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00007571
John McCall70aa5392010-01-06 05:24:50 +00007572 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00007573 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00007574 return OutputTypeRange;
7575
7576 IntRange SubRange
7577 = GetExprRange(C, CE->getSubExpr(),
7578 std::min(MaxWidth, OutputTypeRange.Width));
7579
7580 // Bail out if the subexpr's range is as wide as the cast type.
7581 if (SubRange.Width >= OutputTypeRange.Width)
7582 return OutputTypeRange;
7583
7584 // Otherwise, we take the smaller width, and we're non-negative if
7585 // either the output type or the subexpr is.
7586 return IntRange(SubRange.Width,
7587 SubRange.NonNegative || OutputTypeRange.NonNegative);
7588 }
7589
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007590 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00007591 // If we can fold the condition, just take that operand.
7592 bool CondResult;
7593 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
7594 return GetExprRange(C, CondResult ? CO->getTrueExpr()
7595 : CO->getFalseExpr(),
7596 MaxWidth);
7597
7598 // Otherwise, conservatively merge.
7599 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
7600 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
7601 return IntRange::join(L, R);
7602 }
7603
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007604 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00007605 switch (BO->getOpcode()) {
7606
7607 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00007608 case BO_LAnd:
7609 case BO_LOr:
7610 case BO_LT:
7611 case BO_GT:
7612 case BO_LE:
7613 case BO_GE:
7614 case BO_EQ:
7615 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00007616 return IntRange::forBoolType();
7617
John McCallc3688382011-07-13 06:35:24 +00007618 // The type of the assignments is the type of the LHS, so the RHS
7619 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00007620 case BO_MulAssign:
7621 case BO_DivAssign:
7622 case BO_RemAssign:
7623 case BO_AddAssign:
7624 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00007625 case BO_XorAssign:
7626 case BO_OrAssign:
7627 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00007628 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00007629
John McCallc3688382011-07-13 06:35:24 +00007630 // Simple assignments just pass through the RHS, which will have
7631 // been coerced to the LHS type.
7632 case BO_Assign:
7633 // TODO: bitfields?
7634 return GetExprRange(C, BO->getRHS(), MaxWidth);
7635
John McCall70aa5392010-01-06 05:24:50 +00007636 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00007637 case BO_PtrMemD:
7638 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00007639 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00007640
John McCall2ce81ad2010-01-06 22:07:33 +00007641 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00007642 case BO_And:
7643 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00007644 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
7645 GetExprRange(C, BO->getRHS(), MaxWidth));
7646
John McCall70aa5392010-01-06 05:24:50 +00007647 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00007648 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00007649 // ...except that we want to treat '1 << (blah)' as logically
7650 // positive. It's an important idiom.
7651 if (IntegerLiteral *I
7652 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
7653 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00007654 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00007655 return IntRange(R.Width, /*NonNegative*/ true);
7656 }
7657 }
7658 // fallthrough
7659
John McCalle3027922010-08-25 11:45:40 +00007660 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00007661 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00007662
John McCall2ce81ad2010-01-06 22:07:33 +00007663 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00007664 case BO_Shr:
7665 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00007666 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
7667
7668 // If the shift amount is a positive constant, drop the width by
7669 // that much.
7670 llvm::APSInt shift;
7671 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
7672 shift.isNonNegative()) {
7673 unsigned zext = shift.getZExtValue();
7674 if (zext >= L.Width)
7675 L.Width = (L.NonNegative ? 0 : 1);
7676 else
7677 L.Width -= zext;
7678 }
7679
7680 return L;
7681 }
7682
7683 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00007684 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00007685 return GetExprRange(C, BO->getRHS(), MaxWidth);
7686
John McCall2ce81ad2010-01-06 22:07:33 +00007687 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00007688 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00007689 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00007690 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00007691 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007692
John McCall51431812011-07-14 22:39:48 +00007693 // The width of a division result is mostly determined by the size
7694 // of the LHS.
7695 case BO_Div: {
7696 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00007697 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00007698 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
7699
7700 // If the divisor is constant, use that.
7701 llvm::APSInt divisor;
7702 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
7703 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
7704 if (log2 >= L.Width)
7705 L.Width = (L.NonNegative ? 0 : 1);
7706 else
7707 L.Width = std::min(L.Width - log2, MaxWidth);
7708 return L;
7709 }
7710
7711 // Otherwise, just use the LHS's width.
7712 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
7713 return IntRange(L.Width, L.NonNegative && R.NonNegative);
7714 }
7715
7716 // The result of a remainder can't be larger than the result of
7717 // either side.
7718 case BO_Rem: {
7719 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00007720 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00007721 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
7722 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
7723
7724 IntRange meet = IntRange::meet(L, R);
7725 meet.Width = std::min(meet.Width, MaxWidth);
7726 return meet;
7727 }
7728
7729 // The default behavior is okay for these.
7730 case BO_Mul:
7731 case BO_Add:
7732 case BO_Xor:
7733 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00007734 break;
7735 }
7736
John McCall51431812011-07-14 22:39:48 +00007737 // The default case is to treat the operation as if it were closed
7738 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00007739 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
7740 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
7741 return IntRange::join(L, R);
7742 }
7743
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007744 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00007745 switch (UO->getOpcode()) {
7746 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00007747 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00007748 return IntRange::forBoolType();
7749
7750 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00007751 case UO_Deref:
7752 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00007753 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00007754
7755 default:
7756 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
7757 }
7758 }
7759
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007760 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00007761 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
7762
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007763 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00007764 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00007765 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00007766
Eli Friedmane6d33952013-07-08 20:20:06 +00007767 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00007768}
John McCall263a48b2010-01-04 23:31:57 +00007769
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007770IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00007771 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00007772}
7773
John McCall263a48b2010-01-04 23:31:57 +00007774/// Checks whether the given value, which currently has the given
7775/// source semantics, has the same value when coerced through the
7776/// target semantics.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007777bool IsSameFloatAfterCast(const llvm::APFloat &value,
7778 const llvm::fltSemantics &Src,
7779 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00007780 llvm::APFloat truncated = value;
7781
7782 bool ignored;
7783 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
7784 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
7785
7786 return truncated.bitwiseIsEqual(value);
7787}
7788
7789/// Checks whether the given value, which currently has the given
7790/// source semantics, has the same value when coerced through the
7791/// target semantics.
7792///
7793/// The value might be a vector of floats (or a complex number).
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007794bool IsSameFloatAfterCast(const APValue &value,
7795 const llvm::fltSemantics &Src,
7796 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00007797 if (value.isFloat())
7798 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
7799
7800 if (value.isVector()) {
7801 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
7802 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
7803 return false;
7804 return true;
7805 }
7806
7807 assert(value.isComplexFloat());
7808 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
7809 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
7810}
7811
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007812void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007813
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007814bool IsZero(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00007815 // Suppress cases where we are comparing against an enum constant.
7816 if (const DeclRefExpr *DR =
7817 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
7818 if (isa<EnumConstantDecl>(DR->getDecl()))
7819 return false;
7820
7821 // Suppress cases where the '0' value is expanded from a macro.
7822 if (E->getLocStart().isMacroID())
7823 return false;
7824
John McCallcc7e5bf2010-05-06 08:58:33 +00007825 llvm::APSInt Value;
7826 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
7827}
7828
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007829bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00007830 // Strip off implicit integral promotions.
7831 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00007832 if (ICE->getCastKind() != CK_IntegralCast &&
7833 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00007834 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00007835 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00007836 }
7837
7838 return E->getType()->isEnumeralType();
7839}
7840
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007841void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00007842 // Disable warning in template instantiations.
7843 if (!S.ActiveTemplateInstantiations.empty())
7844 return;
7845
John McCalle3027922010-08-25 11:45:40 +00007846 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00007847 if (E->isValueDependent())
7848 return;
7849
John McCalle3027922010-08-25 11:45:40 +00007850 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007851 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00007852 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00007853 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00007854 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007855 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00007856 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00007857 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00007858 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007859 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00007860 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00007861 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00007862 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007863 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00007864 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00007865 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
7866 }
7867}
7868
Benjamin Kramer7320b992016-06-15 14:20:56 +00007869void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant,
7870 Expr *Other, const llvm::APSInt &Value,
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007871 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00007872 // Disable warning in template instantiations.
7873 if (!S.ActiveTemplateInstantiations.empty())
7874 return;
7875
Richard Trieu0f097742014-04-04 04:13:47 +00007876 // TODO: Investigate using GetExprRange() to get tighter bounds
7877 // on the bit ranges.
7878 QualType OtherT = Other->getType();
David Majnemer7800f1f2015-05-23 01:32:17 +00007879 if (const auto *AT = OtherT->getAs<AtomicType>())
Justin Bogner4f42fc42014-07-21 18:01:53 +00007880 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00007881 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
7882 unsigned OtherWidth = OtherRange.Width;
7883
7884 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
7885
Richard Trieu560910c2012-11-14 22:50:24 +00007886 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00007887 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00007888 return;
7889
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007890 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00007891 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00007892
Richard Trieu0f097742014-04-04 04:13:47 +00007893 // Used for diagnostic printout.
7894 enum {
7895 LiteralConstant = 0,
7896 CXXBoolLiteralTrue,
7897 CXXBoolLiteralFalse
7898 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00007899
Richard Trieu0f097742014-04-04 04:13:47 +00007900 if (!OtherIsBooleanType) {
7901 QualType ConstantT = Constant->getType();
7902 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00007903
Richard Trieu0f097742014-04-04 04:13:47 +00007904 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
7905 return;
7906 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
7907 "comparison with non-integer type");
7908
7909 bool ConstantSigned = ConstantT->isSignedIntegerType();
7910 bool CommonSigned = CommonT->isSignedIntegerType();
7911
7912 bool EqualityOnly = false;
7913
7914 if (CommonSigned) {
7915 // The common type is signed, therefore no signed to unsigned conversion.
7916 if (!OtherRange.NonNegative) {
7917 // Check that the constant is representable in type OtherT.
7918 if (ConstantSigned) {
7919 if (OtherWidth >= Value.getMinSignedBits())
7920 return;
7921 } else { // !ConstantSigned
7922 if (OtherWidth >= Value.getActiveBits() + 1)
7923 return;
7924 }
7925 } else { // !OtherSigned
7926 // Check that the constant is representable in type OtherT.
7927 // Negative values are out of range.
7928 if (ConstantSigned) {
7929 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
7930 return;
7931 } else { // !ConstantSigned
7932 if (OtherWidth >= Value.getActiveBits())
7933 return;
7934 }
Richard Trieu560910c2012-11-14 22:50:24 +00007935 }
Richard Trieu0f097742014-04-04 04:13:47 +00007936 } else { // !CommonSigned
7937 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00007938 if (OtherWidth >= Value.getActiveBits())
7939 return;
Craig Toppercf360162014-06-18 05:13:11 +00007940 } else { // OtherSigned
7941 assert(!ConstantSigned &&
7942 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00007943 // Check to see if the constant is representable in OtherT.
7944 if (OtherWidth > Value.getActiveBits())
7945 return;
7946 // Check to see if the constant is equivalent to a negative value
7947 // cast to CommonT.
7948 if (S.Context.getIntWidth(ConstantT) ==
7949 S.Context.getIntWidth(CommonT) &&
7950 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
7951 return;
7952 // The constant value rests between values that OtherT can represent
7953 // after conversion. Relational comparison still works, but equality
7954 // comparisons will be tautological.
7955 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00007956 }
7957 }
Richard Trieu0f097742014-04-04 04:13:47 +00007958
7959 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
7960
7961 if (op == BO_EQ || op == BO_NE) {
7962 IsTrue = op == BO_NE;
7963 } else if (EqualityOnly) {
7964 return;
7965 } else if (RhsConstant) {
7966 if (op == BO_GT || op == BO_GE)
7967 IsTrue = !PositiveConstant;
7968 else // op == BO_LT || op == BO_LE
7969 IsTrue = PositiveConstant;
7970 } else {
7971 if (op == BO_LT || op == BO_LE)
7972 IsTrue = !PositiveConstant;
7973 else // op == BO_GT || op == BO_GE
7974 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00007975 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007976 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00007977 // Other isKnownToHaveBooleanValue
7978 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
7979 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
7980 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
7981
7982 static const struct LinkedConditions {
7983 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
7984 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
7985 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
7986 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
7987 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
7988 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
7989
7990 } TruthTable = {
7991 // Constant on LHS. | Constant on RHS. |
7992 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
7993 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
7994 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
7995 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
7996 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
7997 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
7998 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
7999 };
8000
8001 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
8002
8003 enum ConstantValue ConstVal = Zero;
8004 if (Value.isUnsigned() || Value.isNonNegative()) {
8005 if (Value == 0) {
8006 LiteralOrBoolConstant =
8007 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
8008 ConstVal = Zero;
8009 } else if (Value == 1) {
8010 LiteralOrBoolConstant =
8011 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
8012 ConstVal = One;
8013 } else {
8014 LiteralOrBoolConstant = LiteralConstant;
8015 ConstVal = GT_One;
8016 }
8017 } else {
8018 ConstVal = LT_Zero;
8019 }
8020
8021 CompareBoolWithConstantResult CmpRes;
8022
8023 switch (op) {
8024 case BO_LT:
8025 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
8026 break;
8027 case BO_GT:
8028 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
8029 break;
8030 case BO_LE:
8031 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
8032 break;
8033 case BO_GE:
8034 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
8035 break;
8036 case BO_EQ:
8037 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
8038 break;
8039 case BO_NE:
8040 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
8041 break;
8042 default:
8043 CmpRes = Unkwn;
8044 break;
8045 }
8046
8047 if (CmpRes == AFals) {
8048 IsTrue = false;
8049 } else if (CmpRes == ATrue) {
8050 IsTrue = true;
8051 } else {
8052 return;
8053 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008054 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008055
8056 // If this is a comparison to an enum constant, include that
8057 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00008058 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008059 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
8060 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
8061
8062 SmallString<64> PrettySourceValue;
8063 llvm::raw_svector_ostream OS(PrettySourceValue);
8064 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00008065 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008066 else
8067 OS << Value;
8068
Richard Trieu0f097742014-04-04 04:13:47 +00008069 S.DiagRuntimeBehavior(
8070 E->getOperatorLoc(), E,
8071 S.PDiag(diag::warn_out_of_range_compare)
8072 << OS.str() << LiteralOrBoolConstant
8073 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
8074 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008075}
8076
John McCallcc7e5bf2010-05-06 08:58:33 +00008077/// Analyze the operands of the given comparison. Implements the
8078/// fallback case from AnalyzeComparison.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008079void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00008080 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8081 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00008082}
John McCall263a48b2010-01-04 23:31:57 +00008083
John McCallca01b222010-01-04 23:21:16 +00008084/// \brief Implements -Wsign-compare.
8085///
Richard Trieu82402a02011-09-15 21:56:47 +00008086/// \param E the binary operator to check for warnings
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008087void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008088 // The type the comparison is being performed in.
8089 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00008090
8091 // Only analyze comparison operators where both sides have been converted to
8092 // the same type.
8093 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
8094 return AnalyzeImpConvsInComparison(S, E);
8095
8096 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00008097 if (E->isValueDependent())
8098 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008099
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008100 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
8101 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008102
8103 bool IsComparisonConstant = false;
8104
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008105 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008106 // of 'true' or 'false'.
8107 if (T->isIntegralType(S.Context)) {
8108 llvm::APSInt RHSValue;
8109 bool IsRHSIntegralLiteral =
8110 RHS->isIntegerConstantExpr(RHSValue, S.Context);
8111 llvm::APSInt LHSValue;
8112 bool IsLHSIntegralLiteral =
8113 LHS->isIntegerConstantExpr(LHSValue, S.Context);
8114 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
8115 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
8116 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
8117 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
8118 else
8119 IsComparisonConstant =
8120 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008121 } else if (!T->hasUnsignedIntegerRepresentation())
8122 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008123
John McCallcc7e5bf2010-05-06 08:58:33 +00008124 // We don't do anything special if this isn't an unsigned integral
8125 // comparison: we're only interested in integral comparisons, and
8126 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00008127 //
8128 // We also don't care about value-dependent expressions or expressions
8129 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008130 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00008131 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008132
John McCallcc7e5bf2010-05-06 08:58:33 +00008133 // Check to see if one of the (unmodified) operands is of different
8134 // signedness.
8135 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00008136 if (LHS->getType()->hasSignedIntegerRepresentation()) {
8137 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00008138 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00008139 signedOperand = LHS;
8140 unsignedOperand = RHS;
8141 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
8142 signedOperand = RHS;
8143 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00008144 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00008145 CheckTrivialUnsignedComparison(S, E);
8146 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008147 }
8148
John McCallcc7e5bf2010-05-06 08:58:33 +00008149 // Otherwise, calculate the effective range of the signed operand.
8150 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00008151
John McCallcc7e5bf2010-05-06 08:58:33 +00008152 // Go ahead and analyze implicit conversions in the operands. Note
8153 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00008154 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
8155 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00008156
John McCallcc7e5bf2010-05-06 08:58:33 +00008157 // If the signed range is non-negative, -Wsign-compare won't fire,
8158 // but we should still check for comparisons which are always true
8159 // or false.
8160 if (signedRange.NonNegative)
8161 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008162
8163 // For (in)equality comparisons, if the unsigned operand is a
8164 // constant which cannot collide with a overflowed signed operand,
8165 // then reinterpreting the signed operand as unsigned will not
8166 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00008167 if (E->isEqualityOp()) {
8168 unsigned comparisonWidth = S.Context.getIntWidth(T);
8169 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00008170
John McCallcc7e5bf2010-05-06 08:58:33 +00008171 // We should never be unable to prove that the unsigned operand is
8172 // non-negative.
8173 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
8174
8175 if (unsignedRange.Width < comparisonWidth)
8176 return;
8177 }
8178
Douglas Gregorbfb4a212012-05-01 01:53:49 +00008179 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
8180 S.PDiag(diag::warn_mixed_sign_comparison)
8181 << LHS->getType() << RHS->getType()
8182 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00008183}
8184
John McCall1f425642010-11-11 03:21:53 +00008185/// Analyzes an attempt to assign the given value to a bitfield.
8186///
8187/// Returns true if there was something fishy about the attempt.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008188bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
8189 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00008190 assert(Bitfield->isBitField());
8191 if (Bitfield->isInvalidDecl())
8192 return false;
8193
John McCalldeebbcf2010-11-11 05:33:51 +00008194 // White-list bool bitfields.
8195 if (Bitfield->getType()->isBooleanType())
8196 return false;
8197
Douglas Gregor789adec2011-02-04 13:09:01 +00008198 // Ignore value- or type-dependent expressions.
8199 if (Bitfield->getBitWidth()->isValueDependent() ||
8200 Bitfield->getBitWidth()->isTypeDependent() ||
8201 Init->isValueDependent() ||
8202 Init->isTypeDependent())
8203 return false;
8204
John McCall1f425642010-11-11 03:21:53 +00008205 Expr *OriginalInit = Init->IgnoreParenImpCasts();
8206
Richard Smith5fab0c92011-12-28 19:48:30 +00008207 llvm::APSInt Value;
8208 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00008209 return false;
8210
John McCall1f425642010-11-11 03:21:53 +00008211 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00008212 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00008213
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00008214 if (!Value.isSigned() || Value.isNegative())
Richard Trieu7561ed02016-08-05 02:39:30 +00008215 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00008216 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
8217 OriginalWidth = Value.getMinSignedBits();
Richard Trieu7561ed02016-08-05 02:39:30 +00008218
John McCall1f425642010-11-11 03:21:53 +00008219 if (OriginalWidth <= FieldWidth)
8220 return false;
8221
Eli Friedmanc267a322012-01-26 23:11:39 +00008222 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00008223 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00008224 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00008225
Eli Friedmanc267a322012-01-26 23:11:39 +00008226 // Check whether the stored value is equal to the original value.
8227 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00008228 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00008229 return false;
8230
Eli Friedmanc267a322012-01-26 23:11:39 +00008231 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00008232 // therefore don't strictly fit into a signed bitfield of width 1.
8233 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00008234 return false;
8235
John McCall1f425642010-11-11 03:21:53 +00008236 std::string PrettyValue = Value.toString(10);
8237 std::string PrettyTrunc = TruncatedValue.toString(10);
8238
8239 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
8240 << PrettyValue << PrettyTrunc << OriginalInit->getType()
8241 << Init->getSourceRange();
8242
8243 return true;
8244}
8245
John McCalld2a53122010-11-09 23:24:47 +00008246/// Analyze the given simple or compound assignment for warning-worthy
8247/// operations.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008248void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00008249 // Just recurse on the LHS.
8250 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8251
8252 // We want to recurse on the RHS as normal unless we're assigning to
8253 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00008254 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008255 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00008256 E->getOperatorLoc())) {
8257 // Recurse, ignoring any implicit conversions on the RHS.
8258 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
8259 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00008260 }
8261 }
8262
8263 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
8264}
8265
John McCall263a48b2010-01-04 23:31:57 +00008266/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008267void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
8268 SourceLocation CContext, unsigned diag,
8269 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00008270 if (pruneControlFlow) {
8271 S.DiagRuntimeBehavior(E->getExprLoc(), E,
8272 S.PDiag(diag)
8273 << SourceType << T << E->getSourceRange()
8274 << SourceRange(CContext));
8275 return;
8276 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00008277 S.Diag(E->getExprLoc(), diag)
8278 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
8279}
8280
Chandler Carruth7f3654f2011-04-05 06:47:57 +00008281/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008282void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
8283 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00008284 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00008285}
8286
Richard Trieube234c32016-04-21 21:04:55 +00008287
8288/// Diagnose an implicit cast from a floating point value to an integer value.
8289void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
8290
8291 SourceLocation CContext) {
8292 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
8293 const bool PruneWarnings = !S.ActiveTemplateInstantiations.empty();
8294
8295 Expr *InnerE = E->IgnoreParenImpCasts();
8296 // We also want to warn on, e.g., "int i = -1.234"
8297 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
8298 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
8299 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
8300
8301 const bool IsLiteral =
8302 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
8303
8304 llvm::APFloat Value(0.0);
8305 bool IsConstant =
8306 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
8307 if (!IsConstant) {
Richard Trieu891f0f12016-04-22 22:14:32 +00008308 return DiagnoseImpCast(S, E, T, CContext,
8309 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +00008310 }
8311
Chandler Carruth016ef402011-04-10 08:36:24 +00008312 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +00008313
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00008314 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
8315 T->hasUnsignedIntegerRepresentation());
Richard Trieube234c32016-04-21 21:04:55 +00008316 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
8317 &isExact) == llvm::APFloat::opOK &&
Richard Trieu891f0f12016-04-22 22:14:32 +00008318 isExact) {
Richard Trieube234c32016-04-21 21:04:55 +00008319 if (IsLiteral) return;
8320 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
8321 PruneWarnings);
8322 }
8323
8324 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +00008325 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +00008326 // Warn on floating point literal to integer.
8327 DiagID = diag::warn_impcast_literal_float_to_integer;
8328 } else if (IntegerValue == 0) {
8329 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
8330 return DiagnoseImpCast(S, E, T, CContext,
8331 diag::warn_impcast_float_integer, PruneWarnings);
8332 }
8333 // Warn on non-zero to zero conversion.
8334 DiagID = diag::warn_impcast_float_to_integer_zero;
8335 } else {
8336 if (IntegerValue.isUnsigned()) {
8337 if (!IntegerValue.isMaxValue()) {
8338 return DiagnoseImpCast(S, E, T, CContext,
8339 diag::warn_impcast_float_integer, PruneWarnings);
8340 }
8341 } else { // IntegerValue.isSigned()
8342 if (!IntegerValue.isMaxSignedValue() &&
8343 !IntegerValue.isMinSignedValue()) {
8344 return DiagnoseImpCast(S, E, T, CContext,
8345 diag::warn_impcast_float_integer, PruneWarnings);
8346 }
8347 }
8348 // Warn on evaluatable floating point expression to integer conversion.
8349 DiagID = diag::warn_impcast_float_to_integer;
8350 }
Chandler Carruth016ef402011-04-10 08:36:24 +00008351
Eli Friedman07185912013-08-29 23:44:43 +00008352 // FIXME: Force the precision of the source value down so we don't print
8353 // digits which are usually useless (we don't really care here if we
8354 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
8355 // would automatically print the shortest representation, but it's a bit
8356 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00008357 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00008358 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
8359 precision = (precision * 59 + 195) / 196;
8360 Value.toString(PrettySourceValue, precision);
8361
David Blaikie9b88cc02012-05-15 17:18:27 +00008362 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +00008363 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +00008364 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00008365 else
David Blaikie9b88cc02012-05-15 17:18:27 +00008366 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00008367
Richard Trieube234c32016-04-21 21:04:55 +00008368 if (PruneWarnings) {
8369 S.DiagRuntimeBehavior(E->getExprLoc(), E,
8370 S.PDiag(DiagID)
8371 << E->getType() << T.getUnqualifiedType()
8372 << PrettySourceValue << PrettyTargetValue
8373 << E->getSourceRange() << SourceRange(CContext));
8374 } else {
8375 S.Diag(E->getExprLoc(), DiagID)
8376 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
8377 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
8378 }
Chandler Carruth016ef402011-04-10 08:36:24 +00008379}
8380
John McCall18a2c2c2010-11-09 22:22:12 +00008381std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
8382 if (!Range.Width) return "0";
8383
8384 llvm::APSInt ValueInRange = Value;
8385 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00008386 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00008387 return ValueInRange.toString(10);
8388}
8389
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008390bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008391 if (!isa<ImplicitCastExpr>(Ex))
8392 return false;
8393
8394 Expr *InnerE = Ex->IgnoreParenImpCasts();
8395 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
8396 const Type *Source =
8397 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
8398 if (Target->isDependentType())
8399 return false;
8400
8401 const BuiltinType *FloatCandidateBT =
8402 dyn_cast<BuiltinType>(ToBool ? Source : Target);
8403 const Type *BoolCandidateType = ToBool ? Target : Source;
8404
8405 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
8406 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
8407}
8408
8409void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
8410 SourceLocation CC) {
8411 unsigned NumArgs = TheCall->getNumArgs();
8412 for (unsigned i = 0; i < NumArgs; ++i) {
8413 Expr *CurrA = TheCall->getArg(i);
8414 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
8415 continue;
8416
8417 bool IsSwapped = ((i > 0) &&
8418 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
8419 IsSwapped |= ((i < (NumArgs - 1)) &&
8420 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
8421 if (IsSwapped) {
8422 // Warn on this floating-point to bool conversion.
8423 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
8424 CurrA->getType(), CC,
8425 diag::warn_impcast_floating_point_to_bool);
8426 }
8427 }
8428}
8429
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008430void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00008431 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
8432 E->getExprLoc()))
8433 return;
8434
Richard Trieu09d6b802016-01-08 23:35:06 +00008435 // Don't warn on functions which have return type nullptr_t.
8436 if (isa<CallExpr>(E))
8437 return;
8438
Richard Trieu5b993502014-10-15 03:42:06 +00008439 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
8440 const Expr::NullPointerConstantKind NullKind =
8441 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
8442 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
8443 return;
8444
8445 // Return if target type is a safe conversion.
8446 if (T->isAnyPointerType() || T->isBlockPointerType() ||
8447 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
8448 return;
8449
8450 SourceLocation Loc = E->getSourceRange().getBegin();
8451
Richard Trieu0a5e1662016-02-13 00:58:53 +00008452 // Venture through the macro stacks to get to the source of macro arguments.
8453 // The new location is a better location than the complete location that was
8454 // passed in.
8455 while (S.SourceMgr.isMacroArgExpansion(Loc))
8456 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
8457
8458 while (S.SourceMgr.isMacroArgExpansion(CC))
8459 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
8460
Richard Trieu5b993502014-10-15 03:42:06 +00008461 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +00008462 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
8463 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
8464 Loc, S.SourceMgr, S.getLangOpts());
8465 if (MacroName == "NULL")
8466 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
Richard Trieu5b993502014-10-15 03:42:06 +00008467 }
8468
8469 // Only warn if the null and context location are in the same macro expansion.
8470 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
8471 return;
8472
8473 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
8474 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
8475 << FixItHint::CreateReplacement(Loc,
8476 S.getFixItZeroLiteralForType(T, Loc));
8477}
8478
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008479void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8480 ObjCArrayLiteral *ArrayLiteral);
8481void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8482 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +00008483
8484/// Check a single element within a collection literal against the
8485/// target element type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008486void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
8487 Expr *Element, unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00008488 // Skip a bitcast to 'id' or qualified 'id'.
8489 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
8490 if (ICE->getCastKind() == CK_BitCast &&
8491 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
8492 Element = ICE->getSubExpr();
8493 }
8494
8495 QualType ElementType = Element->getType();
8496 ExprResult ElementResult(Element);
8497 if (ElementType->getAs<ObjCObjectPointerType>() &&
8498 S.CheckSingleAssignmentConstraints(TargetElementType,
8499 ElementResult,
8500 false, false)
8501 != Sema::Compatible) {
8502 S.Diag(Element->getLocStart(),
8503 diag::warn_objc_collection_literal_element)
8504 << ElementType << ElementKind << TargetElementType
8505 << Element->getSourceRange();
8506 }
8507
8508 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
8509 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
8510 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
8511 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
8512}
8513
8514/// Check an Objective-C array literal being converted to the given
8515/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008516void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8517 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00008518 if (!S.NSArrayDecl)
8519 return;
8520
8521 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8522 if (!TargetObjCPtr)
8523 return;
8524
8525 if (TargetObjCPtr->isUnspecialized() ||
8526 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8527 != S.NSArrayDecl->getCanonicalDecl())
8528 return;
8529
8530 auto TypeArgs = TargetObjCPtr->getTypeArgs();
8531 if (TypeArgs.size() != 1)
8532 return;
8533
8534 QualType TargetElementType = TypeArgs[0];
8535 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
8536 checkObjCCollectionLiteralElement(S, TargetElementType,
8537 ArrayLiteral->getElement(I),
8538 0);
8539 }
8540}
8541
8542/// Check an Objective-C dictionary literal being converted to the given
8543/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008544void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8545 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00008546 if (!S.NSDictionaryDecl)
8547 return;
8548
8549 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8550 if (!TargetObjCPtr)
8551 return;
8552
8553 if (TargetObjCPtr->isUnspecialized() ||
8554 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8555 != S.NSDictionaryDecl->getCanonicalDecl())
8556 return;
8557
8558 auto TypeArgs = TargetObjCPtr->getTypeArgs();
8559 if (TypeArgs.size() != 2)
8560 return;
8561
8562 QualType TargetKeyType = TypeArgs[0];
8563 QualType TargetObjectType = TypeArgs[1];
8564 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
8565 auto Element = DictionaryLiteral->getKeyValueElement(I);
8566 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
8567 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
8568 }
8569}
8570
Richard Trieufc404c72016-02-05 23:02:38 +00008571// Helper function to filter out cases for constant width constant conversion.
8572// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008573bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
8574 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +00008575 // If initializing from a constant, and the constant starts with '0',
8576 // then it is a binary, octal, or hexadecimal. Allow these constants
8577 // to fill all the bits, even if there is a sign change.
8578 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
8579 const char FirstLiteralCharacter =
8580 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
8581 if (FirstLiteralCharacter == '0')
8582 return false;
8583 }
8584
8585 // If the CC location points to a '{', and the type is char, then assume
8586 // assume it is an array initialization.
8587 if (CC.isValid() && T->isCharType()) {
8588 const char FirstContextCharacter =
8589 S.getSourceManager().getCharacterData(CC)[0];
8590 if (FirstContextCharacter == '{')
8591 return false;
8592 }
8593
8594 return true;
8595}
8596
John McCallcc7e5bf2010-05-06 08:58:33 +00008597void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00008598 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008599 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00008600
John McCallcc7e5bf2010-05-06 08:58:33 +00008601 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
8602 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
8603 if (Source == Target) return;
8604 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00008605
Chandler Carruthc22845a2011-07-26 05:40:03 +00008606 // If the conversion context location is invalid don't complain. We also
8607 // don't want to emit a warning if the issue occurs from the expansion of
8608 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
8609 // delay this check as long as possible. Once we detect we are in that
8610 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008611 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00008612 return;
8613
Richard Trieu021baa32011-09-23 20:10:00 +00008614 // Diagnose implicit casts to bool.
8615 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
8616 if (isa<StringLiteral>(E))
8617 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00008618 // and expressions, for instance, assert(0 && "error here"), are
8619 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00008620 return DiagnoseImpCast(S, E, T, CC,
8621 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00008622 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
8623 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
8624 // This covers the literal expressions that evaluate to Objective-C
8625 // objects.
8626 return DiagnoseImpCast(S, E, T, CC,
8627 diag::warn_impcast_objective_c_literal_to_bool);
8628 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00008629 if (Source->isPointerType() || Source->canDecayToPointerType()) {
8630 // Warn on pointer to bool conversion that is always true.
8631 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
8632 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00008633 }
Richard Trieu021baa32011-09-23 20:10:00 +00008634 }
John McCall263a48b2010-01-04 23:31:57 +00008635
Douglas Gregor5054cb02015-07-07 03:58:22 +00008636 // Check implicit casts from Objective-C collection literals to specialized
8637 // collection types, e.g., NSArray<NSString *> *.
8638 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
8639 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
8640 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
8641 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
8642
John McCall263a48b2010-01-04 23:31:57 +00008643 // Strip vector types.
8644 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008645 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008646 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008647 return;
John McCallacf0ee52010-10-08 02:01:28 +00008648 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008649 }
Chris Lattneree7286f2011-06-14 04:51:15 +00008650
8651 // If the vector cast is cast between two vectors of the same size, it is
8652 // a bitcast, not a conversion.
8653 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
8654 return;
John McCall263a48b2010-01-04 23:31:57 +00008655
8656 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
8657 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
8658 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00008659 if (auto VecTy = dyn_cast<VectorType>(Target))
8660 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00008661
8662 // Strip complex types.
8663 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008664 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008665 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008666 return;
8667
John McCallacf0ee52010-10-08 02:01:28 +00008668 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008669 }
John McCall263a48b2010-01-04 23:31:57 +00008670
8671 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
8672 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
8673 }
8674
8675 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
8676 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
8677
8678 // If the source is floating point...
8679 if (SourceBT && SourceBT->isFloatingPoint()) {
8680 // ...and the target is floating point...
8681 if (TargetBT && TargetBT->isFloatingPoint()) {
8682 // ...then warn if we're dropping FP rank.
8683
8684 // Builtin FP kinds are ordered by increasing FP rank.
8685 if (SourceBT->getKind() > TargetBT->getKind()) {
8686 // Don't warn about float constants that are precisely
8687 // representable in the target type.
8688 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00008689 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00008690 // Value might be a float, a float vector, or a float complex.
8691 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00008692 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
8693 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00008694 return;
8695 }
8696
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008697 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008698 return;
8699
John McCallacf0ee52010-10-08 02:01:28 +00008700 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +00008701 }
8702 // ... or possibly if we're increasing rank, too
8703 else if (TargetBT->getKind() > SourceBT->getKind()) {
8704 if (S.SourceMgr.isInSystemMacro(CC))
8705 return;
8706
8707 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +00008708 }
8709 return;
8710 }
8711
Richard Trieube234c32016-04-21 21:04:55 +00008712 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00008713 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008714 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008715 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00008716
Richard Trieube234c32016-04-21 21:04:55 +00008717 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00008718 }
John McCall263a48b2010-01-04 23:31:57 +00008719
Richard Smith54894fd2015-12-30 01:06:52 +00008720 // Detect the case where a call result is converted from floating-point to
8721 // to bool, and the final argument to the call is converted from bool, to
8722 // discover this typo:
8723 //
8724 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
8725 //
8726 // FIXME: This is an incredibly special case; is there some more general
8727 // way to detect this class of misplaced-parentheses bug?
8728 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008729 // Check last argument of function call to see if it is an
8730 // implicit cast from a type matching the type the result
8731 // is being cast to.
8732 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +00008733 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008734 Expr *LastA = CEx->getArg(NumArgs - 1);
8735 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +00008736 if (isa<ImplicitCastExpr>(LastA) &&
8737 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008738 // Warn on this floating-point to bool conversion
8739 DiagnoseImpCast(S, E, T, CC,
8740 diag::warn_impcast_floating_point_to_bool);
8741 }
8742 }
8743 }
John McCall263a48b2010-01-04 23:31:57 +00008744 return;
8745 }
8746
Richard Trieu5b993502014-10-15 03:42:06 +00008747 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00008748
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00008749 S.DiscardMisalignedMemberAddress(Target, E);
8750
David Blaikie9366d2b2012-06-19 21:19:06 +00008751 if (!Source->isIntegerType() || !Target->isIntegerType())
8752 return;
8753
David Blaikie7555b6a2012-05-15 16:56:36 +00008754 // TODO: remove this early return once the false positives for constant->bool
8755 // in templates, macros, etc, are reduced or removed.
8756 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
8757 return;
8758
John McCallcc7e5bf2010-05-06 08:58:33 +00008759 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00008760 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00008761
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008762 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00008763 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008764 // TODO: this should happen for bitfield stores, too.
8765 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +00008766 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008767 if (S.SourceMgr.isInSystemMacro(CC))
8768 return;
8769
John McCall18a2c2c2010-11-09 22:22:12 +00008770 std::string PrettySourceValue = Value.toString(10);
8771 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008772
Ted Kremenek33ba9952011-10-22 02:37:33 +00008773 S.DiagRuntimeBehavior(E->getExprLoc(), E,
8774 S.PDiag(diag::warn_impcast_integer_precision_constant)
8775 << PrettySourceValue << PrettyTargetValue
8776 << E->getType() << T << E->getSourceRange()
8777 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00008778 return;
8779 }
8780
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008781 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
8782 if (S.SourceMgr.isInSystemMacro(CC))
8783 return;
8784
David Blaikie9455da02012-04-12 22:40:54 +00008785 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00008786 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
8787 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00008788 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00008789 }
8790
Richard Trieudcb55572016-01-29 23:51:16 +00008791 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
8792 SourceRange.NonNegative && Source->isSignedIntegerType()) {
8793 // Warn when doing a signed to signed conversion, warn if the positive
8794 // source value is exactly the width of the target type, which will
8795 // cause a negative value to be stored.
8796
8797 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +00008798 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
8799 !S.SourceMgr.isInSystemMacro(CC)) {
8800 if (isSameWidthConstantConversion(S, E, T, CC)) {
8801 std::string PrettySourceValue = Value.toString(10);
8802 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +00008803
Richard Trieufc404c72016-02-05 23:02:38 +00008804 S.DiagRuntimeBehavior(
8805 E->getExprLoc(), E,
8806 S.PDiag(diag::warn_impcast_integer_precision_constant)
8807 << PrettySourceValue << PrettyTargetValue << E->getType() << T
8808 << E->getSourceRange() << clang::SourceRange(CC));
8809 return;
Richard Trieudcb55572016-01-29 23:51:16 +00008810 }
8811 }
Richard Trieufc404c72016-02-05 23:02:38 +00008812
Richard Trieudcb55572016-01-29 23:51:16 +00008813 // Fall through for non-constants to give a sign conversion warning.
8814 }
8815
John McCallcc7e5bf2010-05-06 08:58:33 +00008816 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
8817 (!TargetRange.NonNegative && SourceRange.NonNegative &&
8818 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008819 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008820 return;
8821
John McCallcc7e5bf2010-05-06 08:58:33 +00008822 unsigned DiagID = diag::warn_impcast_integer_sign;
8823
8824 // Traditionally, gcc has warned about this under -Wsign-compare.
8825 // We also want to warn about it in -Wconversion.
8826 // So if -Wconversion is off, use a completely identical diagnostic
8827 // in the sign-compare group.
8828 // The conditional-checking code will
8829 if (ICContext) {
8830 DiagID = diag::warn_impcast_integer_sign_conditional;
8831 *ICContext = true;
8832 }
8833
John McCallacf0ee52010-10-08 02:01:28 +00008834 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00008835 }
8836
Douglas Gregora78f1932011-02-22 02:45:07 +00008837 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00008838 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
8839 // type, to give us better diagnostics.
8840 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00008841 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00008842 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8843 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
8844 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
8845 SourceType = S.Context.getTypeDeclType(Enum);
8846 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
8847 }
8848 }
8849
Douglas Gregora78f1932011-02-22 02:45:07 +00008850 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
8851 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00008852 if (SourceEnum->getDecl()->hasNameForLinkage() &&
8853 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008854 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008855 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008856 return;
8857
Douglas Gregor364f7db2011-03-12 00:14:31 +00008858 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00008859 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008860 }
John McCall263a48b2010-01-04 23:31:57 +00008861}
8862
David Blaikie18e9ac72012-05-15 21:57:38 +00008863void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
8864 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00008865
8866void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00008867 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008868 E = E->IgnoreParenImpCasts();
8869
8870 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00008871 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00008872
John McCallacf0ee52010-10-08 02:01:28 +00008873 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008874 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00008875 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00008876}
8877
David Blaikie18e9ac72012-05-15 21:57:38 +00008878void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
8879 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00008880 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00008881
8882 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00008883 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
8884 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00008885
8886 // If -Wconversion would have warned about either of the candidates
8887 // for a signedness conversion to the context type...
8888 if (!Suspicious) return;
8889
8890 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008891 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00008892 return;
8893
John McCallcc7e5bf2010-05-06 08:58:33 +00008894 // ...then check whether it would have warned about either of the
8895 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00008896 if (E->getType() == T) return;
8897
8898 Suspicious = false;
8899 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
8900 E->getType(), CC, &Suspicious);
8901 if (!Suspicious)
8902 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00008903 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00008904}
8905
Richard Trieu65724892014-11-15 06:37:39 +00008906/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
8907/// Input argument E is a logical expression.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008908void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +00008909 if (S.getLangOpts().Bool)
8910 return;
8911 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
8912}
8913
John McCallcc7e5bf2010-05-06 08:58:33 +00008914/// AnalyzeImplicitConversions - Find and report any interesting
8915/// implicit conversions in the given expression. There are a couple
8916/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00008917void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00008918 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00008919 Expr *E = OrigE->IgnoreParenImpCasts();
8920
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00008921 if (E->isTypeDependent() || E->isValueDependent())
8922 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00008923
John McCallcc7e5bf2010-05-06 08:58:33 +00008924 // For conditional operators, we analyze the arguments as if they
8925 // were being fed directly into the output.
8926 if (isa<ConditionalOperator>(E)) {
8927 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00008928 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00008929 return;
8930 }
8931
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008932 // Check implicit argument conversions for function calls.
8933 if (CallExpr *Call = dyn_cast<CallExpr>(E))
8934 CheckImplicitArgumentConversions(S, Call, CC);
8935
John McCallcc7e5bf2010-05-06 08:58:33 +00008936 // Go ahead and check any implicit conversions we might have skipped.
8937 // The non-canonical typecheck is just an optimization;
8938 // CheckImplicitConversion will filter out dead implicit conversions.
8939 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00008940 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008941
8942 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +00008943
8944 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
8945 // The bound subexpressions in a PseudoObjectExpr are not reachable
8946 // as transitive children.
8947 // FIXME: Use a more uniform representation for this.
8948 for (auto *SE : POE->semantics())
8949 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
8950 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00008951 }
Richard Smithd7bed4d2015-11-22 02:57:17 +00008952
John McCallcc7e5bf2010-05-06 08:58:33 +00008953 // Skip past explicit casts.
8954 if (isa<ExplicitCastExpr>(E)) {
8955 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00008956 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008957 }
8958
John McCalld2a53122010-11-09 23:24:47 +00008959 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8960 // Do a somewhat different check with comparison operators.
8961 if (BO->isComparisonOp())
8962 return AnalyzeComparison(S, BO);
8963
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008964 // And with simple assignments.
8965 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00008966 return AnalyzeAssignment(S, BO);
8967 }
John McCallcc7e5bf2010-05-06 08:58:33 +00008968
8969 // These break the otherwise-useful invariant below. Fortunately,
8970 // we don't really need to recurse into them, because any internal
8971 // expressions should have been analyzed already when they were
8972 // built into statements.
8973 if (isa<StmtExpr>(E)) return;
8974
8975 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00008976 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00008977
8978 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00008979 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00008980 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00008981 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +00008982 for (Stmt *SubStmt : E->children()) {
8983 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00008984 if (!ChildExpr)
8985 continue;
8986
Richard Trieu955231d2014-01-25 01:10:35 +00008987 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00008988 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00008989 // Ignore checking string literals that are in logical and operators.
8990 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00008991 continue;
8992 AnalyzeImplicitConversions(S, ChildExpr, CC);
8993 }
Richard Trieu791b86e2014-11-19 06:08:18 +00008994
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00008995 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00008996 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
8997 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00008998 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00008999
9000 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
9001 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00009002 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009003 }
Richard Trieu791b86e2014-11-19 06:08:18 +00009004
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009005 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
9006 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00009007 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009008}
9009
9010} // end anonymous namespace
9011
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009012static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
9013 unsigned Start, unsigned End) {
9014 bool IllegalParams = false;
9015 for (unsigned I = Start; I <= End; ++I) {
9016 QualType Ty = TheCall->getArg(I)->getType();
9017 // Taking into account implicit conversions,
9018 // allow any integer within 32 bits range
9019 if (!Ty->isIntegerType() ||
9020 S.Context.getTypeSizeInChars(Ty).getQuantity() > 4) {
9021 S.Diag(TheCall->getArg(I)->getLocStart(),
9022 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
9023 IllegalParams = true;
9024 }
9025 // Potentially emit standard warnings for implicit conversions if enabled
9026 // using -Wconversion.
9027 CheckImplicitConversion(S, TheCall->getArg(I), S.Context.UnsignedIntTy,
9028 TheCall->getArg(I)->getLocStart());
9029 }
9030 return IllegalParams;
9031}
9032
Richard Trieuc1888e02014-06-28 23:25:37 +00009033// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
9034// Returns true when emitting a warning about taking the address of a reference.
9035static bool CheckForReference(Sema &SemaRef, const Expr *E,
Benjamin Kramer7320b992016-06-15 14:20:56 +00009036 const PartialDiagnostic &PD) {
Richard Trieuc1888e02014-06-28 23:25:37 +00009037 E = E->IgnoreParenImpCasts();
9038
9039 const FunctionDecl *FD = nullptr;
9040
9041 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9042 if (!DRE->getDecl()->getType()->isReferenceType())
9043 return false;
9044 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9045 if (!M->getMemberDecl()->getType()->isReferenceType())
9046 return false;
9047 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00009048 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00009049 return false;
9050 FD = Call->getDirectCallee();
9051 } else {
9052 return false;
9053 }
9054
9055 SemaRef.Diag(E->getExprLoc(), PD);
9056
9057 // If possible, point to location of function.
9058 if (FD) {
9059 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
9060 }
9061
9062 return true;
9063}
9064
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009065// Returns true if the SourceLocation is expanded from any macro body.
9066// Returns false if the SourceLocation is invalid, is from not in a macro
9067// expansion, or is from expanded from a top-level macro argument.
9068static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
9069 if (Loc.isInvalid())
9070 return false;
9071
9072 while (Loc.isMacroID()) {
9073 if (SM.isMacroBodyExpansion(Loc))
9074 return true;
9075 Loc = SM.getImmediateMacroCallerLoc(Loc);
9076 }
9077
9078 return false;
9079}
9080
Richard Trieu3bb8b562014-02-26 02:36:06 +00009081/// \brief Diagnose pointers that are always non-null.
9082/// \param E the expression containing the pointer
9083/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
9084/// compared to a null pointer
9085/// \param IsEqual True when the comparison is equal to a null pointer
9086/// \param Range Extra SourceRange to highlight in the diagnostic
9087void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
9088 Expr::NullPointerConstantKind NullKind,
9089 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00009090 if (!E)
9091 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009092
9093 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009094 if (E->getExprLoc().isMacroID()) {
9095 const SourceManager &SM = getSourceManager();
9096 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
9097 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00009098 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009099 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00009100 E = E->IgnoreImpCasts();
9101
9102 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
9103
Richard Trieuf7432752014-06-06 21:39:26 +00009104 if (isa<CXXThisExpr>(E)) {
9105 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
9106 : diag::warn_this_bool_conversion;
9107 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
9108 return;
9109 }
9110
Richard Trieu3bb8b562014-02-26 02:36:06 +00009111 bool IsAddressOf = false;
9112
9113 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9114 if (UO->getOpcode() != UO_AddrOf)
9115 return;
9116 IsAddressOf = true;
9117 E = UO->getSubExpr();
9118 }
9119
Richard Trieuc1888e02014-06-28 23:25:37 +00009120 if (IsAddressOf) {
9121 unsigned DiagID = IsCompare
9122 ? diag::warn_address_of_reference_null_compare
9123 : diag::warn_address_of_reference_bool_conversion;
9124 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
9125 << IsEqual;
9126 if (CheckForReference(*this, E, PD)) {
9127 return;
9128 }
9129 }
9130
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009131 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
9132 bool IsParam = isa<NonNullAttr>(NonnullAttr);
George Burgess IV850269a2015-12-08 22:02:00 +00009133 std::string Str;
9134 llvm::raw_string_ostream S(Str);
9135 E->printPretty(S, nullptr, getPrintingPolicy());
9136 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
9137 : diag::warn_cast_nonnull_to_bool;
9138 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
9139 << E->getSourceRange() << Range << IsEqual;
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009140 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
George Burgess IV850269a2015-12-08 22:02:00 +00009141 };
9142
9143 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
9144 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
9145 if (auto *Callee = Call->getDirectCallee()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009146 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
9147 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00009148 return;
9149 }
9150 }
9151 }
9152
Richard Trieu3bb8b562014-02-26 02:36:06 +00009153 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00009154 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009155 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
9156 D = R->getDecl();
9157 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9158 D = M->getMemberDecl();
9159 }
9160
9161 // Weak Decls can be null.
9162 if (!D || D->isWeak())
9163 return;
George Burgess IV850269a2015-12-08 22:02:00 +00009164
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009165 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +00009166 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
9167 if (getCurFunction() &&
9168 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009169 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
9170 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00009171 return;
9172 }
9173
9174 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
David Majnemera3debed2016-06-24 05:33:44 +00009175 auto ParamIter = llvm::find(FD->parameters(), PV);
George Burgess IV850269a2015-12-08 22:02:00 +00009176 assert(ParamIter != FD->param_end());
9177 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
9178
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009179 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
9180 if (!NonNull->args_size()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009181 ComplainAboutNonnullParamOrCall(NonNull);
George Burgess IV850269a2015-12-08 22:02:00 +00009182 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009183 }
George Burgess IV850269a2015-12-08 22:02:00 +00009184
9185 for (unsigned ArgNo : NonNull->args()) {
9186 if (ArgNo == ParamNo) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009187 ComplainAboutNonnullParamOrCall(NonNull);
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009188 return;
9189 }
George Burgess IV850269a2015-12-08 22:02:00 +00009190 }
9191 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009192 }
9193 }
George Burgess IV850269a2015-12-08 22:02:00 +00009194 }
9195
Richard Trieu3bb8b562014-02-26 02:36:06 +00009196 QualType T = D->getType();
9197 const bool IsArray = T->isArrayType();
9198 const bool IsFunction = T->isFunctionType();
9199
Richard Trieuc1888e02014-06-28 23:25:37 +00009200 // Address of function is used to silence the function warning.
9201 if (IsAddressOf && IsFunction) {
9202 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009203 }
9204
9205 // Found nothing.
9206 if (!IsAddressOf && !IsFunction && !IsArray)
9207 return;
9208
9209 // Pretty print the expression for the diagnostic.
9210 std::string Str;
9211 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00009212 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00009213
9214 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
9215 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +00009216 enum {
9217 AddressOf,
9218 FunctionPointer,
9219 ArrayPointer
9220 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009221 if (IsAddressOf)
9222 DiagType = AddressOf;
9223 else if (IsFunction)
9224 DiagType = FunctionPointer;
9225 else if (IsArray)
9226 DiagType = ArrayPointer;
9227 else
9228 llvm_unreachable("Could not determine diagnostic.");
9229 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
9230 << Range << IsEqual;
9231
9232 if (!IsFunction)
9233 return;
9234
9235 // Suggest '&' to silence the function warning.
9236 Diag(E->getExprLoc(), diag::note_function_warning_silence)
9237 << FixItHint::CreateInsertion(E->getLocStart(), "&");
9238
9239 // Check to see if '()' fixit should be emitted.
9240 QualType ReturnType;
9241 UnresolvedSet<4> NonTemplateOverloads;
9242 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
9243 if (ReturnType.isNull())
9244 return;
9245
9246 if (IsCompare) {
9247 // There are two cases here. If there is null constant, the only suggest
9248 // for a pointer return type. If the null is 0, then suggest if the return
9249 // type is a pointer or an integer type.
9250 if (!ReturnType->isPointerType()) {
9251 if (NullKind == Expr::NPCK_ZeroExpression ||
9252 NullKind == Expr::NPCK_ZeroLiteral) {
9253 if (!ReturnType->isIntegerType())
9254 return;
9255 } else {
9256 return;
9257 }
9258 }
9259 } else { // !IsCompare
9260 // For function to bool, only suggest if the function pointer has bool
9261 // return type.
9262 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
9263 return;
9264 }
9265 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00009266 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00009267}
9268
John McCallcc7e5bf2010-05-06 08:58:33 +00009269/// Diagnoses "dangerous" implicit conversions within the given
9270/// expression (which is a full expression). Implements -Wconversion
9271/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00009272///
9273/// \param CC the "context" location of the implicit conversion, i.e.
9274/// the most location of the syntactic entity requiring the implicit
9275/// conversion
9276void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009277 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00009278 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00009279 return;
9280
9281 // Don't diagnose for value- or type-dependent expressions.
9282 if (E->isTypeDependent() || E->isValueDependent())
9283 return;
9284
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009285 // Check for array bounds violations in cases where the check isn't triggered
9286 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
9287 // ArraySubscriptExpr is on the RHS of a variable initialization.
9288 CheckArrayAccess(E);
9289
John McCallacf0ee52010-10-08 02:01:28 +00009290 // This is not the right CC for (e.g.) a variable initialization.
9291 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009292}
9293
Richard Trieu65724892014-11-15 06:37:39 +00009294/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9295/// Input argument E is a logical expression.
9296void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
9297 ::CheckBoolLikeConversion(*this, E, CC);
9298}
9299
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009300/// Diagnose when expression is an integer constant expression and its evaluation
9301/// results in integer overflow
9302void Sema::CheckForIntOverflow (Expr *E) {
Akira Hatanakadfe2156f2016-02-10 06:06:06 +00009303 // Use a work list to deal with nested struct initializers.
9304 SmallVector<Expr *, 2> Exprs(1, E);
9305
9306 do {
9307 Expr *E = Exprs.pop_back_val();
9308
9309 if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
9310 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
9311 continue;
9312 }
9313
9314 if (auto InitList = dyn_cast<InitListExpr>(E))
9315 Exprs.append(InitList->inits().begin(), InitList->inits().end());
9316 } while (!Exprs.empty());
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009317}
9318
Richard Smithc406cb72013-01-17 01:17:56 +00009319namespace {
9320/// \brief Visitor for expressions which looks for unsequenced operations on the
9321/// same object.
9322class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00009323 typedef EvaluatedExprVisitor<SequenceChecker> Base;
9324
Richard Smithc406cb72013-01-17 01:17:56 +00009325 /// \brief A tree of sequenced regions within an expression. Two regions are
9326 /// unsequenced if one is an ancestor or a descendent of the other. When we
9327 /// finish processing an expression with sequencing, such as a comma
9328 /// expression, we fold its tree nodes into its parent, since they are
9329 /// unsequenced with respect to nodes we will visit later.
9330 class SequenceTree {
9331 struct Value {
9332 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
9333 unsigned Parent : 31;
Aaron Ballmanaffa1c32016-07-06 18:33:01 +00009334 unsigned Merged : 1;
Richard Smithc406cb72013-01-17 01:17:56 +00009335 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009336 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00009337
9338 public:
9339 /// \brief A region within an expression which may be sequenced with respect
9340 /// to some other region.
9341 class Seq {
9342 explicit Seq(unsigned N) : Index(N) {}
9343 unsigned Index;
9344 friend class SequenceTree;
9345 public:
9346 Seq() : Index(0) {}
9347 };
9348
9349 SequenceTree() { Values.push_back(Value(0)); }
9350 Seq root() const { return Seq(0); }
9351
9352 /// \brief Create a new sequence of operations, which is an unsequenced
9353 /// subset of \p Parent. This sequence of operations is sequenced with
9354 /// respect to other children of \p Parent.
9355 Seq allocate(Seq Parent) {
9356 Values.push_back(Value(Parent.Index));
9357 return Seq(Values.size() - 1);
9358 }
9359
9360 /// \brief Merge a sequence of operations into its parent.
9361 void merge(Seq S) {
9362 Values[S.Index].Merged = true;
9363 }
9364
9365 /// \brief Determine whether two operations are unsequenced. This operation
9366 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
9367 /// should have been merged into its parent as appropriate.
9368 bool isUnsequenced(Seq Cur, Seq Old) {
9369 unsigned C = representative(Cur.Index);
9370 unsigned Target = representative(Old.Index);
9371 while (C >= Target) {
9372 if (C == Target)
9373 return true;
9374 C = Values[C].Parent;
9375 }
9376 return false;
9377 }
9378
9379 private:
9380 /// \brief Pick a representative for a sequence.
9381 unsigned representative(unsigned K) {
9382 if (Values[K].Merged)
9383 // Perform path compression as we go.
9384 return Values[K].Parent = representative(Values[K].Parent);
9385 return K;
9386 }
9387 };
9388
9389 /// An object for which we can track unsequenced uses.
9390 typedef NamedDecl *Object;
9391
9392 /// Different flavors of object usage which we track. We only track the
9393 /// least-sequenced usage of each kind.
9394 enum UsageKind {
9395 /// A read of an object. Multiple unsequenced reads are OK.
9396 UK_Use,
9397 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00009398 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00009399 UK_ModAsValue,
9400 /// A modification of an object which is not sequenced before the value
9401 /// computation of the expression, such as n++.
9402 UK_ModAsSideEffect,
9403
9404 UK_Count = UK_ModAsSideEffect + 1
9405 };
9406
9407 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00009408 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00009409 Expr *Use;
9410 SequenceTree::Seq Seq;
9411 };
9412
9413 struct UsageInfo {
9414 UsageInfo() : Diagnosed(false) {}
9415 Usage Uses[UK_Count];
9416 /// Have we issued a diagnostic for this variable already?
9417 bool Diagnosed;
9418 };
9419 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
9420
9421 Sema &SemaRef;
9422 /// Sequenced regions within the expression.
9423 SequenceTree Tree;
9424 /// Declaration modifications and references which we have seen.
9425 UsageInfoMap UsageMap;
9426 /// The region we are currently within.
9427 SequenceTree::Seq Region;
9428 /// Filled in with declarations which were modified as a side-effect
9429 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009430 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00009431 /// Expressions to check later. We defer checking these to reduce
9432 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009433 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00009434
9435 /// RAII object wrapping the visitation of a sequenced subexpression of an
9436 /// expression. At the end of this process, the side-effects of the evaluation
9437 /// become sequenced with respect to the value computation of the result, so
9438 /// we downgrade any UK_ModAsSideEffect within the evaluation to
9439 /// UK_ModAsValue.
9440 struct SequencedSubexpression {
9441 SequencedSubexpression(SequenceChecker &Self)
9442 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
9443 Self.ModAsSideEffect = &ModAsSideEffect;
9444 }
9445 ~SequencedSubexpression() {
David Majnemerf7e36092016-06-23 00:15:04 +00009446 for (auto &M : llvm::reverse(ModAsSideEffect)) {
9447 UsageInfo &U = Self.UsageMap[M.first];
Richard Smithe8efd992014-12-03 01:05:50 +00009448 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
David Majnemerf7e36092016-06-23 00:15:04 +00009449 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
9450 SideEffectUsage = M.second;
Richard Smithc406cb72013-01-17 01:17:56 +00009451 }
9452 Self.ModAsSideEffect = OldModAsSideEffect;
9453 }
9454
9455 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009456 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
9457 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00009458 };
9459
Richard Smith40238f02013-06-20 22:21:56 +00009460 /// RAII object wrapping the visitation of a subexpression which we might
9461 /// choose to evaluate as a constant. If any subexpression is evaluated and
9462 /// found to be non-constant, this allows us to suppress the evaluation of
9463 /// the outer expression.
9464 class EvaluationTracker {
9465 public:
9466 EvaluationTracker(SequenceChecker &Self)
9467 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
9468 Self.EvalTracker = this;
9469 }
9470 ~EvaluationTracker() {
9471 Self.EvalTracker = Prev;
9472 if (Prev)
9473 Prev->EvalOK &= EvalOK;
9474 }
9475
9476 bool evaluate(const Expr *E, bool &Result) {
9477 if (!EvalOK || E->isValueDependent())
9478 return false;
9479 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
9480 return EvalOK;
9481 }
9482
9483 private:
9484 SequenceChecker &Self;
9485 EvaluationTracker *Prev;
9486 bool EvalOK;
9487 } *EvalTracker;
9488
Richard Smithc406cb72013-01-17 01:17:56 +00009489 /// \brief Find the object which is produced by the specified expression,
9490 /// if any.
9491 Object getObject(Expr *E, bool Mod) const {
9492 E = E->IgnoreParenCasts();
9493 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9494 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
9495 return getObject(UO->getSubExpr(), Mod);
9496 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9497 if (BO->getOpcode() == BO_Comma)
9498 return getObject(BO->getRHS(), Mod);
9499 if (Mod && BO->isAssignmentOp())
9500 return getObject(BO->getLHS(), Mod);
9501 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9502 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
9503 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
9504 return ME->getMemberDecl();
9505 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9506 // FIXME: If this is a reference, map through to its value.
9507 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00009508 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00009509 }
9510
9511 /// \brief Note that an object was modified or used by an expression.
9512 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
9513 Usage &U = UI.Uses[UK];
9514 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
9515 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
9516 ModAsSideEffect->push_back(std::make_pair(O, U));
9517 U.Use = Ref;
9518 U.Seq = Region;
9519 }
9520 }
9521 /// \brief Check whether a modification or use conflicts with a prior usage.
9522 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
9523 bool IsModMod) {
9524 if (UI.Diagnosed)
9525 return;
9526
9527 const Usage &U = UI.Uses[OtherKind];
9528 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
9529 return;
9530
9531 Expr *Mod = U.Use;
9532 Expr *ModOrUse = Ref;
9533 if (OtherKind == UK_Use)
9534 std::swap(Mod, ModOrUse);
9535
9536 SemaRef.Diag(Mod->getExprLoc(),
9537 IsModMod ? diag::warn_unsequenced_mod_mod
9538 : diag::warn_unsequenced_mod_use)
9539 << O << SourceRange(ModOrUse->getExprLoc());
9540 UI.Diagnosed = true;
9541 }
9542
9543 void notePreUse(Object O, Expr *Use) {
9544 UsageInfo &U = UsageMap[O];
9545 // Uses conflict with other modifications.
9546 checkUsage(O, U, Use, UK_ModAsValue, false);
9547 }
9548 void notePostUse(Object O, Expr *Use) {
9549 UsageInfo &U = UsageMap[O];
9550 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
9551 addUsage(U, O, Use, UK_Use);
9552 }
9553
9554 void notePreMod(Object O, Expr *Mod) {
9555 UsageInfo &U = UsageMap[O];
9556 // Modifications conflict with other modifications and with uses.
9557 checkUsage(O, U, Mod, UK_ModAsValue, true);
9558 checkUsage(O, U, Mod, UK_Use, false);
9559 }
9560 void notePostMod(Object O, Expr *Use, UsageKind UK) {
9561 UsageInfo &U = UsageMap[O];
9562 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
9563 addUsage(U, O, Use, UK);
9564 }
9565
9566public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009567 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00009568 : Base(S.Context), SemaRef(S), Region(Tree.root()),
9569 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00009570 Visit(E);
9571 }
9572
9573 void VisitStmt(Stmt *S) {
9574 // Skip all statements which aren't expressions for now.
9575 }
9576
9577 void VisitExpr(Expr *E) {
9578 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00009579 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00009580 }
9581
9582 void VisitCastExpr(CastExpr *E) {
9583 Object O = Object();
9584 if (E->getCastKind() == CK_LValueToRValue)
9585 O = getObject(E->getSubExpr(), false);
9586
9587 if (O)
9588 notePreUse(O, E);
9589 VisitExpr(E);
9590 if (O)
9591 notePostUse(O, E);
9592 }
9593
9594 void VisitBinComma(BinaryOperator *BO) {
9595 // C++11 [expr.comma]p1:
9596 // Every value computation and side effect associated with the left
9597 // expression is sequenced before every value computation and side
9598 // effect associated with the right expression.
9599 SequenceTree::Seq LHS = Tree.allocate(Region);
9600 SequenceTree::Seq RHS = Tree.allocate(Region);
9601 SequenceTree::Seq OldRegion = Region;
9602
9603 {
9604 SequencedSubexpression SeqLHS(*this);
9605 Region = LHS;
9606 Visit(BO->getLHS());
9607 }
9608
9609 Region = RHS;
9610 Visit(BO->getRHS());
9611
9612 Region = OldRegion;
9613
9614 // Forget that LHS and RHS are sequenced. They are both unsequenced
9615 // with respect to other stuff.
9616 Tree.merge(LHS);
9617 Tree.merge(RHS);
9618 }
9619
9620 void VisitBinAssign(BinaryOperator *BO) {
9621 // The modification is sequenced after the value computation of the LHS
9622 // and RHS, so check it before inspecting the operands and update the
9623 // map afterwards.
9624 Object O = getObject(BO->getLHS(), true);
9625 if (!O)
9626 return VisitExpr(BO);
9627
9628 notePreMod(O, BO);
9629
9630 // C++11 [expr.ass]p7:
9631 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
9632 // only once.
9633 //
9634 // Therefore, for a compound assignment operator, O is considered used
9635 // everywhere except within the evaluation of E1 itself.
9636 if (isa<CompoundAssignOperator>(BO))
9637 notePreUse(O, BO);
9638
9639 Visit(BO->getLHS());
9640
9641 if (isa<CompoundAssignOperator>(BO))
9642 notePostUse(O, BO);
9643
9644 Visit(BO->getRHS());
9645
Richard Smith83e37bee2013-06-26 23:16:51 +00009646 // C++11 [expr.ass]p1:
9647 // the assignment is sequenced [...] before the value computation of the
9648 // assignment expression.
9649 // C11 6.5.16/3 has no such rule.
9650 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
9651 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00009652 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009653
Richard Smithc406cb72013-01-17 01:17:56 +00009654 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
9655 VisitBinAssign(CAO);
9656 }
9657
9658 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
9659 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
9660 void VisitUnaryPreIncDec(UnaryOperator *UO) {
9661 Object O = getObject(UO->getSubExpr(), true);
9662 if (!O)
9663 return VisitExpr(UO);
9664
9665 notePreMod(O, UO);
9666 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00009667 // C++11 [expr.pre.incr]p1:
9668 // the expression ++x is equivalent to x+=1
9669 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
9670 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00009671 }
9672
9673 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
9674 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
9675 void VisitUnaryPostIncDec(UnaryOperator *UO) {
9676 Object O = getObject(UO->getSubExpr(), true);
9677 if (!O)
9678 return VisitExpr(UO);
9679
9680 notePreMod(O, UO);
9681 Visit(UO->getSubExpr());
9682 notePostMod(O, UO, UK_ModAsSideEffect);
9683 }
9684
9685 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
9686 void VisitBinLOr(BinaryOperator *BO) {
9687 // The side-effects of the LHS of an '&&' are sequenced before the
9688 // value computation of the RHS, and hence before the value computation
9689 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
9690 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00009691 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00009692 {
9693 SequencedSubexpression Sequenced(*this);
9694 Visit(BO->getLHS());
9695 }
9696
9697 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00009698 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00009699 if (!Result)
9700 Visit(BO->getRHS());
9701 } else {
9702 // Check for unsequenced operations in the RHS, treating it as an
9703 // entirely separate evaluation.
9704 //
9705 // FIXME: If there are operations in the RHS which are unsequenced
9706 // with respect to operations outside the RHS, and those operations
9707 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00009708 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00009709 }
Richard Smithc406cb72013-01-17 01:17:56 +00009710 }
9711 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00009712 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00009713 {
9714 SequencedSubexpression Sequenced(*this);
9715 Visit(BO->getLHS());
9716 }
9717
9718 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00009719 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00009720 if (Result)
9721 Visit(BO->getRHS());
9722 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00009723 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00009724 }
Richard Smithc406cb72013-01-17 01:17:56 +00009725 }
9726
9727 // Only visit the condition, unless we can be sure which subexpression will
9728 // be chosen.
9729 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00009730 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00009731 {
9732 SequencedSubexpression Sequenced(*this);
9733 Visit(CO->getCond());
9734 }
Richard Smithc406cb72013-01-17 01:17:56 +00009735
9736 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00009737 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00009738 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00009739 else {
Richard Smithd33f5202013-01-17 23:18:09 +00009740 WorkList.push_back(CO->getTrueExpr());
9741 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00009742 }
Richard Smithc406cb72013-01-17 01:17:56 +00009743 }
9744
Richard Smithe3dbfe02013-06-30 10:40:20 +00009745 void VisitCallExpr(CallExpr *CE) {
9746 // C++11 [intro.execution]p15:
9747 // When calling a function [...], every value computation and side effect
9748 // associated with any argument expression, or with the postfix expression
9749 // designating the called function, is sequenced before execution of every
9750 // expression or statement in the body of the function [and thus before
9751 // the value computation of its result].
9752 SequencedSubexpression Sequenced(*this);
9753 Base::VisitCallExpr(CE);
9754
9755 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
9756 }
9757
Richard Smithc406cb72013-01-17 01:17:56 +00009758 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00009759 // This is a call, so all subexpressions are sequenced before the result.
9760 SequencedSubexpression Sequenced(*this);
9761
Richard Smithc406cb72013-01-17 01:17:56 +00009762 if (!CCE->isListInitialization())
9763 return VisitExpr(CCE);
9764
9765 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009766 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00009767 SequenceTree::Seq Parent = Region;
9768 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
9769 E = CCE->arg_end();
9770 I != E; ++I) {
9771 Region = Tree.allocate(Parent);
9772 Elts.push_back(Region);
9773 Visit(*I);
9774 }
9775
9776 // Forget that the initializers are sequenced.
9777 Region = Parent;
9778 for (unsigned I = 0; I < Elts.size(); ++I)
9779 Tree.merge(Elts[I]);
9780 }
9781
9782 void VisitInitListExpr(InitListExpr *ILE) {
9783 if (!SemaRef.getLangOpts().CPlusPlus11)
9784 return VisitExpr(ILE);
9785
9786 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009787 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00009788 SequenceTree::Seq Parent = Region;
9789 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
9790 Expr *E = ILE->getInit(I);
9791 if (!E) continue;
9792 Region = Tree.allocate(Parent);
9793 Elts.push_back(Region);
9794 Visit(E);
9795 }
9796
9797 // Forget that the initializers are sequenced.
9798 Region = Parent;
9799 for (unsigned I = 0; I < Elts.size(); ++I)
9800 Tree.merge(Elts[I]);
9801 }
9802};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009803} // end anonymous namespace
Richard Smithc406cb72013-01-17 01:17:56 +00009804
9805void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009806 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00009807 WorkList.push_back(E);
9808 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00009809 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00009810 SequenceChecker(*this, Item, WorkList);
9811 }
Richard Smithc406cb72013-01-17 01:17:56 +00009812}
9813
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009814void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
9815 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00009816 CheckImplicitConversions(E, CheckLoc);
Richard Trieu71d74d42016-08-05 21:02:34 +00009817 if (!E->isInstantiationDependent())
9818 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009819 if (!IsConstexpr && !E->isValueDependent())
9820 CheckForIntOverflow(E);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00009821 DiagnoseMisalignedMembers();
Richard Smithc406cb72013-01-17 01:17:56 +00009822}
9823
John McCall1f425642010-11-11 03:21:53 +00009824void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
9825 FieldDecl *BitField,
9826 Expr *Init) {
9827 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
9828}
9829
David Majnemer61a5bbf2015-04-07 22:08:51 +00009830static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
9831 SourceLocation Loc) {
9832 if (!PType->isVariablyModifiedType())
9833 return;
9834 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
9835 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
9836 return;
9837 }
David Majnemerdf8f73f2015-04-09 19:53:25 +00009838 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
9839 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
9840 return;
9841 }
David Majnemer61a5bbf2015-04-07 22:08:51 +00009842 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
9843 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
9844 return;
9845 }
9846
9847 const ArrayType *AT = S.Context.getAsArrayType(PType);
9848 if (!AT)
9849 return;
9850
9851 if (AT->getSizeModifier() != ArrayType::Star) {
9852 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
9853 return;
9854 }
9855
9856 S.Diag(Loc, diag::err_array_star_in_function_definition);
9857}
9858
Mike Stump0c2ec772010-01-21 03:59:47 +00009859/// CheckParmsForFunctionDef - Check that the parameters of the given
9860/// function are appropriate for the definition of a function. This
9861/// takes care of any checks that cannot be performed on the
9862/// declaration itself, e.g., that the types of each of the function
9863/// parameters are complete.
David Majnemer59f77922016-06-24 04:05:48 +00009864bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
Douglas Gregorb524d902010-11-01 18:37:59 +00009865 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00009866 bool HasInvalidParm = false;
David Majnemer59f77922016-06-24 04:05:48 +00009867 for (ParmVarDecl *Param : Parameters) {
Mike Stump0c2ec772010-01-21 03:59:47 +00009868 // C99 6.7.5.3p4: the parameters in a parameter type list in a
9869 // function declarator that is part of a function definition of
9870 // that function shall not have incomplete type.
9871 //
9872 // This is also C++ [dcl.fct]p6.
9873 if (!Param->isInvalidDecl() &&
9874 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00009875 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00009876 Param->setInvalidDecl();
9877 HasInvalidParm = true;
9878 }
9879
9880 // C99 6.9.1p5: If the declarator includes a parameter type list, the
9881 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00009882 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00009883 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00009884 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00009885 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00009886 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00009887
9888 // C99 6.7.5.3p12:
9889 // If the function declarator is not part of a definition of that
9890 // function, parameters may have incomplete type and may use the [*]
9891 // notation in their sequences of declarator specifiers to specify
9892 // variable length array types.
9893 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +00009894 // FIXME: This diagnostic should point the '[*]' if source-location
9895 // information is added for it.
9896 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00009897
9898 // MSVC destroys objects passed by value in the callee. Therefore a
9899 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00009900 // object's destructor. However, we don't perform any direct access check
9901 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00009902 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
9903 .getCXXABI()
9904 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00009905 if (!Param->isInvalidDecl()) {
9906 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
9907 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
9908 if (!ClassDecl->isInvalidDecl() &&
9909 !ClassDecl->hasIrrelevantDestructor() &&
9910 !ClassDecl->isDependentContext()) {
9911 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
9912 MarkFunctionReferenced(Param->getLocation(), Destructor);
9913 DiagnoseUseOfDecl(Destructor, Param->getLocation());
9914 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00009915 }
9916 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00009917 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009918
9919 // Parameters with the pass_object_size attribute only need to be marked
9920 // constant at function definitions. Because we lack information about
9921 // whether we're on a declaration or definition when we're instantiating the
9922 // attribute, we need to check for constness here.
9923 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
9924 if (!Param->getType().isConstQualified())
9925 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
9926 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +00009927 }
9928
9929 return HasInvalidParm;
9930}
John McCall2b5c1b22010-08-12 21:44:57 +00009931
9932/// CheckCastAlign - Implements -Wcast-align, which warns when a
9933/// pointer cast increases the alignment requirements.
9934void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
9935 // This is actually a lot of work to potentially be doing on every
9936 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009937 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00009938 return;
9939
9940 // Ignore dependent types.
9941 if (T->isDependentType() || Op->getType()->isDependentType())
9942 return;
9943
9944 // Require that the destination be a pointer type.
9945 const PointerType *DestPtr = T->getAs<PointerType>();
9946 if (!DestPtr) return;
9947
9948 // If the destination has alignment 1, we're done.
9949 QualType DestPointee = DestPtr->getPointeeType();
9950 if (DestPointee->isIncompleteType()) return;
9951 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
9952 if (DestAlign.isOne()) return;
9953
9954 // Require that the source be a pointer type.
9955 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
9956 if (!SrcPtr) return;
9957 QualType SrcPointee = SrcPtr->getPointeeType();
9958
9959 // Whitelist casts from cv void*. We already implicitly
9960 // whitelisted casts to cv void*, since they have alignment 1.
9961 // Also whitelist casts involving incomplete types, which implicitly
9962 // includes 'void'.
9963 if (SrcPointee->isIncompleteType()) return;
9964
9965 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
9966 if (SrcAlign >= DestAlign) return;
9967
9968 Diag(TRange.getBegin(), diag::warn_cast_align)
9969 << Op->getType() << T
9970 << static_cast<unsigned>(SrcAlign.getQuantity())
9971 << static_cast<unsigned>(DestAlign.getQuantity())
9972 << TRange << Op->getSourceRange();
9973}
9974
Chandler Carruth28389f02011-08-05 09:10:50 +00009975/// \brief Check whether this array fits the idiom of a size-one tail padded
9976/// array member of a struct.
9977///
9978/// We avoid emitting out-of-bounds access warnings for such arrays as they are
9979/// commonly used to emulate flexible arrays in C89 code.
Benjamin Kramer7320b992016-06-15 14:20:56 +00009980static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
Chandler Carruth28389f02011-08-05 09:10:50 +00009981 const NamedDecl *ND) {
9982 if (Size != 1 || !ND) return false;
9983
9984 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
9985 if (!FD) return false;
9986
9987 // Don't consider sizes resulting from macro expansions or template argument
9988 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00009989
9990 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00009991 while (TInfo) {
9992 TypeLoc TL = TInfo->getTypeLoc();
9993 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00009994 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
9995 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00009996 TInfo = TDL->getTypeSourceInfo();
9997 continue;
9998 }
David Blaikie6adc78e2013-02-18 22:06:02 +00009999 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
10000 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +000010001 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
10002 return false;
10003 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010004 break;
Sean Callanan06a48a62012-05-04 18:22:53 +000010005 }
Chandler Carruth28389f02011-08-05 09:10:50 +000010006
10007 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +000010008 if (!RD) return false;
10009 if (RD->isUnion()) return false;
10010 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10011 if (!CRD->isStandardLayout()) return false;
10012 }
Chandler Carruth28389f02011-08-05 09:10:50 +000010013
Benjamin Kramer8c543672011-08-06 03:04:42 +000010014 // See if this is the last field decl in the record.
10015 const Decl *D = FD;
10016 while ((D = D->getNextDeclInContext()))
10017 if (isa<FieldDecl>(D))
10018 return false;
10019 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +000010020}
10021
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010022void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010023 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +000010024 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010025 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010026 if (IndexExpr->isValueDependent())
10027 return;
10028
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010029 const Type *EffectiveType =
10030 BaseExpr->getType()->getPointeeOrArrayElementType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010031 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010032 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010033 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010034 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +000010035 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +000010036
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010037 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +000010038 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +000010039 return;
Richard Smith13f67182011-12-16 19:31:14 +000010040 if (IndexNegated)
10041 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +000010042
Craig Topperc3ec1492014-05-26 06:22:03 +000010043 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +000010044 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10045 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +000010046 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +000010047 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +000010048
Ted Kremeneke4b316c2011-02-23 23:06:04 +000010049 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010050 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +000010051 if (!size.isStrictlyPositive())
10052 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010053
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010054 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
Nico Weber7c299802011-09-17 22:59:41 +000010055 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010056 // Make sure we're comparing apples to apples when comparing index to size
10057 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
10058 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +000010059 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +000010060 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010061 if (ptrarith_typesize != array_typesize) {
10062 // There's a cast to a different size type involved
10063 uint64_t ratio = array_typesize / ptrarith_typesize;
10064 // TODO: Be smarter about handling cases where array_typesize is not a
10065 // multiple of ptrarith_typesize
10066 if (ptrarith_typesize * ratio == array_typesize)
10067 size *= llvm::APInt(size.getBitWidth(), ratio);
10068 }
10069 }
10070
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010071 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010072 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010073 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010074 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010075
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010076 // For array subscripting the index must be less than size, but for pointer
10077 // arithmetic also allow the index (offset) to be equal to size since
10078 // computing the next address after the end of the array is legal and
10079 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010080 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +000010081 return;
10082
10083 // Also don't warn for arrays of size 1 which are members of some
10084 // structure. These are often used to approximate flexible arrays in C89
10085 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010086 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +000010087 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010088
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010089 // Suppress the warning if the subscript expression (as identified by the
10090 // ']' location) and the index expression are both from macro expansions
10091 // within a system header.
10092 if (ASE) {
10093 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
10094 ASE->getRBracketLoc());
10095 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
10096 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
10097 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +000010098 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010099 return;
10100 }
10101 }
10102
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010103 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010104 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010105 DiagID = diag::warn_array_index_exceeds_bounds;
10106
10107 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10108 PDiag(DiagID) << index.toString(10, true)
10109 << size.toString(10, true)
10110 << (unsigned)size.getLimitedValue(~0U)
10111 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010112 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010113 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010114 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010115 DiagID = diag::warn_ptr_arith_precedes_bounds;
10116 if (index.isNegative()) index = -index;
10117 }
10118
10119 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10120 PDiag(DiagID) << index.toString(10, true)
10121 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +000010122 }
Chandler Carruth1af88f12011-02-17 21:10:52 +000010123
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000010124 if (!ND) {
10125 // Try harder to find a NamedDecl to point at in the note.
10126 while (const ArraySubscriptExpr *ASE =
10127 dyn_cast<ArraySubscriptExpr>(BaseExpr))
10128 BaseExpr = ASE->getBase()->IgnoreParenCasts();
10129 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10130 ND = dyn_cast<NamedDecl>(DRE->getDecl());
10131 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
10132 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
10133 }
10134
Chandler Carruth1af88f12011-02-17 21:10:52 +000010135 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010136 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
10137 PDiag(diag::note_array_index_out_of_bounds)
10138 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +000010139}
10140
Ted Kremenekdf26df72011-03-01 18:41:00 +000010141void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010142 int AllowOnePastEnd = 0;
10143 while (expr) {
10144 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +000010145 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010146 case Stmt::ArraySubscriptExprClass: {
10147 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010148 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010149 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +000010150 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010151 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +000010152 case Stmt::OMPArraySectionExprClass: {
10153 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
10154 if (ASE->getLowerBound())
10155 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
10156 /*ASE=*/nullptr, AllowOnePastEnd > 0);
10157 return;
10158 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010159 case Stmt::UnaryOperatorClass: {
10160 // Only unwrap the * and & unary operators
10161 const UnaryOperator *UO = cast<UnaryOperator>(expr);
10162 expr = UO->getSubExpr();
10163 switch (UO->getOpcode()) {
10164 case UO_AddrOf:
10165 AllowOnePastEnd++;
10166 break;
10167 case UO_Deref:
10168 AllowOnePastEnd--;
10169 break;
10170 default:
10171 return;
10172 }
10173 break;
10174 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000010175 case Stmt::ConditionalOperatorClass: {
10176 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
10177 if (const Expr *lhs = cond->getLHS())
10178 CheckArrayAccess(lhs);
10179 if (const Expr *rhs = cond->getRHS())
10180 CheckArrayAccess(rhs);
10181 return;
10182 }
10183 default:
10184 return;
10185 }
Peter Collingbourne91147592011-04-15 00:35:48 +000010186 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000010187}
John McCall31168b02011-06-15 23:02:42 +000010188
10189//===--- CHECK: Objective-C retain cycles ----------------------------------//
10190
10191namespace {
10192 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +000010193 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +000010194 VarDecl *Variable;
10195 SourceRange Range;
10196 SourceLocation Loc;
10197 bool Indirect;
10198
10199 void setLocsFrom(Expr *e) {
10200 Loc = e->getExprLoc();
10201 Range = e->getSourceRange();
10202 }
10203 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010204} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +000010205
10206/// Consider whether capturing the given variable can possibly lead to
10207/// a retain cycle.
10208static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000010209 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +000010210 // lifetime. In MRR, it's captured strongly if the variable is
10211 // __block and has an appropriate type.
10212 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10213 return false;
10214
10215 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000010216 if (ref)
10217 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +000010218 return true;
10219}
10220
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010221static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +000010222 while (true) {
10223 e = e->IgnoreParens();
10224 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
10225 switch (cast->getCastKind()) {
10226 case CK_BitCast:
10227 case CK_LValueBitCast:
10228 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +000010229 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +000010230 e = cast->getSubExpr();
10231 continue;
10232
John McCall31168b02011-06-15 23:02:42 +000010233 default:
10234 return false;
10235 }
10236 }
10237
10238 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
10239 ObjCIvarDecl *ivar = ref->getDecl();
10240 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10241 return false;
10242
10243 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010244 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +000010245 return false;
10246
10247 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
10248 owner.Indirect = true;
10249 return true;
10250 }
10251
10252 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
10253 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
10254 if (!var) return false;
10255 return considerVariable(var, ref, owner);
10256 }
10257
John McCall31168b02011-06-15 23:02:42 +000010258 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
10259 if (member->isArrow()) return false;
10260
10261 // Don't count this as an indirect ownership.
10262 e = member->getBase();
10263 continue;
10264 }
10265
John McCallfe96e0b2011-11-06 09:01:30 +000010266 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
10267 // Only pay attention to pseudo-objects on property references.
10268 ObjCPropertyRefExpr *pre
10269 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
10270 ->IgnoreParens());
10271 if (!pre) return false;
10272 if (pre->isImplicitProperty()) return false;
10273 ObjCPropertyDecl *property = pre->getExplicitProperty();
10274 if (!property->isRetaining() &&
10275 !(property->getPropertyIvarDecl() &&
10276 property->getPropertyIvarDecl()->getType()
10277 .getObjCLifetime() == Qualifiers::OCL_Strong))
10278 return false;
10279
10280 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010281 if (pre->isSuperReceiver()) {
10282 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
10283 if (!owner.Variable)
10284 return false;
10285 owner.Loc = pre->getLocation();
10286 owner.Range = pre->getSourceRange();
10287 return true;
10288 }
John McCallfe96e0b2011-11-06 09:01:30 +000010289 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
10290 ->getSourceExpr());
10291 continue;
10292 }
10293
John McCall31168b02011-06-15 23:02:42 +000010294 // Array ivars?
10295
10296 return false;
10297 }
10298}
10299
10300namespace {
10301 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
10302 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
10303 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010304 Context(Context), Variable(variable), Capturer(nullptr),
10305 VarWillBeReased(false) {}
10306 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +000010307 VarDecl *Variable;
10308 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010309 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +000010310
10311 void VisitDeclRefExpr(DeclRefExpr *ref) {
10312 if (ref->getDecl() == Variable && !Capturer)
10313 Capturer = ref;
10314 }
10315
John McCall31168b02011-06-15 23:02:42 +000010316 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
10317 if (Capturer) return;
10318 Visit(ref->getBase());
10319 if (Capturer && ref->isFreeIvar())
10320 Capturer = ref;
10321 }
10322
10323 void VisitBlockExpr(BlockExpr *block) {
10324 // Look inside nested blocks
10325 if (block->getBlockDecl()->capturesVariable(Variable))
10326 Visit(block->getBlockDecl()->getBody());
10327 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +000010328
10329 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
10330 if (Capturer) return;
10331 if (OVE->getSourceExpr())
10332 Visit(OVE->getSourceExpr());
10333 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010334 void VisitBinaryOperator(BinaryOperator *BinOp) {
10335 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
10336 return;
10337 Expr *LHS = BinOp->getLHS();
10338 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
10339 if (DRE->getDecl() != Variable)
10340 return;
10341 if (Expr *RHS = BinOp->getRHS()) {
10342 RHS = RHS->IgnoreParenCasts();
10343 llvm::APSInt Value;
10344 VarWillBeReased =
10345 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
10346 }
10347 }
10348 }
John McCall31168b02011-06-15 23:02:42 +000010349 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010350} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +000010351
10352/// Check whether the given argument is a block which captures a
10353/// variable.
10354static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
10355 assert(owner.Variable && owner.Loc.isValid());
10356
10357 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +000010358
10359 // Look through [^{...} copy] and Block_copy(^{...}).
10360 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
10361 Selector Cmd = ME->getSelector();
10362 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
10363 e = ME->getInstanceReceiver();
10364 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +000010365 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +000010366 e = e->IgnoreParenCasts();
10367 }
10368 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
10369 if (CE->getNumArgs() == 1) {
10370 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +000010371 if (Fn) {
10372 const IdentifierInfo *FnI = Fn->getIdentifier();
10373 if (FnI && FnI->isStr("_Block_copy")) {
10374 e = CE->getArg(0)->IgnoreParenCasts();
10375 }
10376 }
Jordan Rose67e887c2012-09-17 17:54:30 +000010377 }
10378 }
10379
John McCall31168b02011-06-15 23:02:42 +000010380 BlockExpr *block = dyn_cast<BlockExpr>(e);
10381 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +000010382 return nullptr;
John McCall31168b02011-06-15 23:02:42 +000010383
10384 FindCaptureVisitor visitor(S.Context, owner.Variable);
10385 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010386 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +000010387}
10388
10389static void diagnoseRetainCycle(Sema &S, Expr *capturer,
10390 RetainCycleOwner &owner) {
10391 assert(capturer);
10392 assert(owner.Variable && owner.Loc.isValid());
10393
10394 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
10395 << owner.Variable << capturer->getSourceRange();
10396 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
10397 << owner.Indirect << owner.Range;
10398}
10399
10400/// Check for a keyword selector that starts with the word 'add' or
10401/// 'set'.
10402static bool isSetterLikeSelector(Selector sel) {
10403 if (sel.isUnarySelector()) return false;
10404
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010405 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +000010406 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +000010407 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +000010408 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +000010409 else if (str.startswith("add")) {
10410 // Specially whitelist 'addOperationWithBlock:'.
10411 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
10412 return false;
10413 str = str.substr(3);
10414 }
John McCall31168b02011-06-15 23:02:42 +000010415 else
10416 return false;
10417
10418 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +000010419 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +000010420}
10421
Benjamin Kramer3a743452015-03-09 15:03:32 +000010422static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
10423 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010424 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
10425 Message->getReceiverInterface(),
10426 NSAPI::ClassId_NSMutableArray);
10427 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010428 return None;
10429 }
10430
10431 Selector Sel = Message->getSelector();
10432
10433 Optional<NSAPI::NSArrayMethodKind> MKOpt =
10434 S.NSAPIObj->getNSArrayMethodKind(Sel);
10435 if (!MKOpt) {
10436 return None;
10437 }
10438
10439 NSAPI::NSArrayMethodKind MK = *MKOpt;
10440
10441 switch (MK) {
10442 case NSAPI::NSMutableArr_addObject:
10443 case NSAPI::NSMutableArr_insertObjectAtIndex:
10444 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
10445 return 0;
10446 case NSAPI::NSMutableArr_replaceObjectAtIndex:
10447 return 1;
10448
10449 default:
10450 return None;
10451 }
10452
10453 return None;
10454}
10455
10456static
10457Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
10458 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010459 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
10460 Message->getReceiverInterface(),
10461 NSAPI::ClassId_NSMutableDictionary);
10462 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010463 return None;
10464 }
10465
10466 Selector Sel = Message->getSelector();
10467
10468 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
10469 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
10470 if (!MKOpt) {
10471 return None;
10472 }
10473
10474 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
10475
10476 switch (MK) {
10477 case NSAPI::NSMutableDict_setObjectForKey:
10478 case NSAPI::NSMutableDict_setValueForKey:
10479 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
10480 return 0;
10481
10482 default:
10483 return None;
10484 }
10485
10486 return None;
10487}
10488
10489static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010490 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
10491 Message->getReceiverInterface(),
10492 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +000010493
Alex Denisov5dfac812015-08-06 04:51:14 +000010494 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
10495 Message->getReceiverInterface(),
10496 NSAPI::ClassId_NSMutableOrderedSet);
10497 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010498 return None;
10499 }
10500
10501 Selector Sel = Message->getSelector();
10502
10503 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
10504 if (!MKOpt) {
10505 return None;
10506 }
10507
10508 NSAPI::NSSetMethodKind MK = *MKOpt;
10509
10510 switch (MK) {
10511 case NSAPI::NSMutableSet_addObject:
10512 case NSAPI::NSOrderedSet_setObjectAtIndex:
10513 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
10514 case NSAPI::NSOrderedSet_insertObjectAtIndex:
10515 return 0;
10516 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
10517 return 1;
10518 }
10519
10520 return None;
10521}
10522
10523void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
10524 if (!Message->isInstanceMessage()) {
10525 return;
10526 }
10527
10528 Optional<int> ArgOpt;
10529
10530 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
10531 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
10532 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
10533 return;
10534 }
10535
10536 int ArgIndex = *ArgOpt;
10537
Alex Denisove1d882c2015-03-04 17:55:52 +000010538 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
10539 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
10540 Arg = OE->getSourceExpr()->IgnoreImpCasts();
10541 }
10542
Alex Denisov5dfac812015-08-06 04:51:14 +000010543 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010544 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010545 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010546 Diag(Message->getSourceRange().getBegin(),
10547 diag::warn_objc_circular_container)
Alex Denisov5dfac812015-08-06 04:51:14 +000010548 << ArgRE->getDecl()->getName() << StringRef("super");
Alex Denisove1d882c2015-03-04 17:55:52 +000010549 }
10550 }
Alex Denisov5dfac812015-08-06 04:51:14 +000010551 } else {
10552 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
10553
10554 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
10555 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
10556 }
10557
10558 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
10559 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
10560 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
10561 ValueDecl *Decl = ReceiverRE->getDecl();
10562 Diag(Message->getSourceRange().getBegin(),
10563 diag::warn_objc_circular_container)
10564 << Decl->getName() << Decl->getName();
10565 if (!ArgRE->isObjCSelfExpr()) {
10566 Diag(Decl->getLocation(),
10567 diag::note_objc_circular_container_declared_here)
10568 << Decl->getName();
10569 }
10570 }
10571 }
10572 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
10573 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
10574 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
10575 ObjCIvarDecl *Decl = IvarRE->getDecl();
10576 Diag(Message->getSourceRange().getBegin(),
10577 diag::warn_objc_circular_container)
10578 << Decl->getName() << Decl->getName();
10579 Diag(Decl->getLocation(),
10580 diag::note_objc_circular_container_declared_here)
10581 << Decl->getName();
10582 }
Alex Denisove1d882c2015-03-04 17:55:52 +000010583 }
10584 }
10585 }
Alex Denisove1d882c2015-03-04 17:55:52 +000010586}
10587
John McCall31168b02011-06-15 23:02:42 +000010588/// Check a message send to see if it's likely to cause a retain cycle.
10589void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
10590 // Only check instance methods whose selector looks like a setter.
10591 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
10592 return;
10593
10594 // Try to find a variable that the receiver is strongly owned by.
10595 RetainCycleOwner owner;
10596 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010597 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +000010598 return;
10599 } else {
10600 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
10601 owner.Variable = getCurMethodDecl()->getSelfDecl();
10602 owner.Loc = msg->getSuperLoc();
10603 owner.Range = msg->getSuperLoc();
10604 }
10605
10606 // Check whether the receiver is captured by any of the arguments.
10607 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
10608 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
10609 return diagnoseRetainCycle(*this, capturer, owner);
10610}
10611
10612/// Check a property assign to see if it's likely to cause a retain cycle.
10613void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
10614 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010615 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +000010616 return;
10617
10618 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
10619 diagnoseRetainCycle(*this, capturer, owner);
10620}
10621
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000010622void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
10623 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +000010624 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000010625 return;
10626
10627 // Because we don't have an expression for the variable, we have to set the
10628 // location explicitly here.
10629 Owner.Loc = Var->getLocation();
10630 Owner.Range = Var->getSourceRange();
10631
10632 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
10633 diagnoseRetainCycle(*this, Capturer, Owner);
10634}
10635
Ted Kremenek9304da92012-12-21 08:04:28 +000010636static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
10637 Expr *RHS, bool isProperty) {
10638 // Check if RHS is an Objective-C object literal, which also can get
10639 // immediately zapped in a weak reference. Note that we explicitly
10640 // allow ObjCStringLiterals, since those are designed to never really die.
10641 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000010642
Ted Kremenek64873352012-12-21 22:46:35 +000010643 // This enum needs to match with the 'select' in
10644 // warn_objc_arc_literal_assign (off-by-1).
10645 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
10646 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
10647 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000010648
10649 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +000010650 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +000010651 << (isProperty ? 0 : 1)
10652 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000010653
10654 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +000010655}
10656
Ted Kremenekc1f014a2012-12-21 19:45:30 +000010657static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
10658 Qualifiers::ObjCLifetime LT,
10659 Expr *RHS, bool isProperty) {
10660 // Strip off any implicit cast added to get to the one ARC-specific.
10661 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
10662 if (cast->getCastKind() == CK_ARCConsumeObject) {
10663 S.Diag(Loc, diag::warn_arc_retained_assign)
10664 << (LT == Qualifiers::OCL_ExplicitNone)
10665 << (isProperty ? 0 : 1)
10666 << RHS->getSourceRange();
10667 return true;
10668 }
10669 RHS = cast->getSubExpr();
10670 }
10671
10672 if (LT == Qualifiers::OCL_Weak &&
10673 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
10674 return true;
10675
10676 return false;
10677}
10678
Ted Kremenekb36234d2012-12-21 08:04:20 +000010679bool Sema::checkUnsafeAssigns(SourceLocation Loc,
10680 QualType LHS, Expr *RHS) {
10681 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
10682
10683 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
10684 return false;
10685
10686 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
10687 return true;
10688
10689 return false;
10690}
10691
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010692void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
10693 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010694 QualType LHSType;
10695 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +000010696 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010697 ObjCPropertyRefExpr *PRE
10698 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
10699 if (PRE && !PRE->isImplicitProperty()) {
10700 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
10701 if (PD)
10702 LHSType = PD->getType();
10703 }
10704
10705 if (LHSType.isNull())
10706 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +000010707
10708 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
10709
10710 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010711 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +000010712 getCurFunction()->markSafeWeakUse(LHS);
10713 }
10714
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010715 if (checkUnsafeAssigns(Loc, LHSType, RHS))
10716 return;
Jordan Rose657b5f42012-09-28 22:21:35 +000010717
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010718 // FIXME. Check for other life times.
10719 if (LT != Qualifiers::OCL_None)
10720 return;
10721
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010722 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010723 if (PRE->isImplicitProperty())
10724 return;
10725 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
10726 if (!PD)
10727 return;
10728
Bill Wendling44426052012-12-20 19:22:21 +000010729 unsigned Attributes = PD->getPropertyAttributes();
10730 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010731 // when 'assign' attribute was not explicitly specified
10732 // by user, ignore it and rely on property type itself
10733 // for lifetime info.
10734 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
10735 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
10736 LHSType->isObjCRetainableType())
10737 return;
10738
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010739 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +000010740 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010741 Diag(Loc, diag::warn_arc_retained_property_assign)
10742 << RHS->getSourceRange();
10743 return;
10744 }
10745 RHS = cast->getSubExpr();
10746 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000010747 }
Bill Wendling44426052012-12-20 19:22:21 +000010748 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +000010749 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
10750 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +000010751 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000010752 }
10753}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010754
10755//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
10756
10757namespace {
10758bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
10759 SourceLocation StmtLoc,
10760 const NullStmt *Body) {
10761 // Do not warn if the body is a macro that expands to nothing, e.g:
10762 //
10763 // #define CALL(x)
10764 // if (condition)
10765 // CALL(0);
10766 //
10767 if (Body->hasLeadingEmptyMacro())
10768 return false;
10769
10770 // Get line numbers of statement and body.
10771 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +000010772 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010773 &StmtLineInvalid);
10774 if (StmtLineInvalid)
10775 return false;
10776
10777 bool BodyLineInvalid;
10778 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
10779 &BodyLineInvalid);
10780 if (BodyLineInvalid)
10781 return false;
10782
10783 // Warn if null statement and body are on the same line.
10784 if (StmtLine != BodyLine)
10785 return false;
10786
10787 return true;
10788}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010789} // end anonymous namespace
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010790
10791void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
10792 const Stmt *Body,
10793 unsigned DiagID) {
10794 // Since this is a syntactic check, don't emit diagnostic for template
10795 // instantiations, this just adds noise.
10796 if (CurrentInstantiationScope)
10797 return;
10798
10799 // The body should be a null statement.
10800 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
10801 if (!NBody)
10802 return;
10803
10804 // Do the usual checks.
10805 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
10806 return;
10807
10808 Diag(NBody->getSemiLoc(), DiagID);
10809 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
10810}
10811
10812void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
10813 const Stmt *PossibleBody) {
10814 assert(!CurrentInstantiationScope); // Ensured by caller
10815
10816 SourceLocation StmtLoc;
10817 const Stmt *Body;
10818 unsigned DiagID;
10819 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
10820 StmtLoc = FS->getRParenLoc();
10821 Body = FS->getBody();
10822 DiagID = diag::warn_empty_for_body;
10823 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
10824 StmtLoc = WS->getCond()->getSourceRange().getEnd();
10825 Body = WS->getBody();
10826 DiagID = diag::warn_empty_while_body;
10827 } else
10828 return; // Neither `for' nor `while'.
10829
10830 // The body should be a null statement.
10831 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
10832 if (!NBody)
10833 return;
10834
10835 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010836 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010837 return;
10838
10839 // Do the usual checks.
10840 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
10841 return;
10842
10843 // `for(...);' and `while(...);' are popular idioms, so in order to keep
10844 // noise level low, emit diagnostics only if for/while is followed by a
10845 // CompoundStmt, e.g.:
10846 // for (int i = 0; i < n; i++);
10847 // {
10848 // a(i);
10849 // }
10850 // or if for/while is followed by a statement with more indentation
10851 // than for/while itself:
10852 // for (int i = 0; i < n; i++);
10853 // a(i);
10854 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
10855 if (!ProbableTypo) {
10856 bool BodyColInvalid;
10857 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
10858 PossibleBody->getLocStart(),
10859 &BodyColInvalid);
10860 if (BodyColInvalid)
10861 return;
10862
10863 bool StmtColInvalid;
10864 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
10865 S->getLocStart(),
10866 &StmtColInvalid);
10867 if (StmtColInvalid)
10868 return;
10869
10870 if (BodyCol > StmtCol)
10871 ProbableTypo = true;
10872 }
10873
10874 if (ProbableTypo) {
10875 Diag(NBody->getSemiLoc(), DiagID);
10876 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
10877 }
10878}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010879
Richard Trieu36d0b2b2015-01-13 02:32:02 +000010880//===--- CHECK: Warn on self move with std::move. -------------------------===//
10881
10882/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
10883void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
10884 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +000010885 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
10886 return;
10887
10888 if (!ActiveTemplateInstantiations.empty())
10889 return;
10890
10891 // Strip parens and casts away.
10892 LHSExpr = LHSExpr->IgnoreParenImpCasts();
10893 RHSExpr = RHSExpr->IgnoreParenImpCasts();
10894
10895 // Check for a call expression
10896 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
10897 if (!CE || CE->getNumArgs() != 1)
10898 return;
10899
10900 // Check for a call to std::move
10901 const FunctionDecl *FD = CE->getDirectCallee();
10902 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
10903 !FD->getIdentifier()->isStr("move"))
10904 return;
10905
10906 // Get argument from std::move
10907 RHSExpr = CE->getArg(0);
10908
10909 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
10910 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
10911
10912 // Two DeclRefExpr's, check that the decls are the same.
10913 if (LHSDeclRef && RHSDeclRef) {
10914 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
10915 return;
10916 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
10917 RHSDeclRef->getDecl()->getCanonicalDecl())
10918 return;
10919
10920 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10921 << LHSExpr->getSourceRange()
10922 << RHSExpr->getSourceRange();
10923 return;
10924 }
10925
10926 // Member variables require a different approach to check for self moves.
10927 // MemberExpr's are the same if every nested MemberExpr refers to the same
10928 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
10929 // the base Expr's are CXXThisExpr's.
10930 const Expr *LHSBase = LHSExpr;
10931 const Expr *RHSBase = RHSExpr;
10932 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
10933 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
10934 if (!LHSME || !RHSME)
10935 return;
10936
10937 while (LHSME && RHSME) {
10938 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
10939 RHSME->getMemberDecl()->getCanonicalDecl())
10940 return;
10941
10942 LHSBase = LHSME->getBase();
10943 RHSBase = RHSME->getBase();
10944 LHSME = dyn_cast<MemberExpr>(LHSBase);
10945 RHSME = dyn_cast<MemberExpr>(RHSBase);
10946 }
10947
10948 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
10949 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
10950 if (LHSDeclRef && RHSDeclRef) {
10951 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
10952 return;
10953 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
10954 RHSDeclRef->getDecl()->getCanonicalDecl())
10955 return;
10956
10957 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10958 << LHSExpr->getSourceRange()
10959 << RHSExpr->getSourceRange();
10960 return;
10961 }
10962
10963 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
10964 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10965 << LHSExpr->getSourceRange()
10966 << RHSExpr->getSourceRange();
10967}
10968
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010969//===--- Layout compatibility ----------------------------------------------//
10970
10971namespace {
10972
10973bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
10974
10975/// \brief Check if two enumeration types are layout-compatible.
10976bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
10977 // C++11 [dcl.enum] p8:
10978 // Two enumeration types are layout-compatible if they have the same
10979 // underlying type.
10980 return ED1->isComplete() && ED2->isComplete() &&
10981 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
10982}
10983
10984/// \brief Check if two fields are layout-compatible.
10985bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
10986 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
10987 return false;
10988
10989 if (Field1->isBitField() != Field2->isBitField())
10990 return false;
10991
10992 if (Field1->isBitField()) {
10993 // Make sure that the bit-fields are the same length.
10994 unsigned Bits1 = Field1->getBitWidthValue(C);
10995 unsigned Bits2 = Field2->getBitWidthValue(C);
10996
10997 if (Bits1 != Bits2)
10998 return false;
10999 }
11000
11001 return true;
11002}
11003
11004/// \brief Check if two standard-layout structs are layout-compatible.
11005/// (C++11 [class.mem] p17)
11006bool isLayoutCompatibleStruct(ASTContext &C,
11007 RecordDecl *RD1,
11008 RecordDecl *RD2) {
11009 // If both records are C++ classes, check that base classes match.
11010 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
11011 // If one of records is a CXXRecordDecl we are in C++ mode,
11012 // thus the other one is a CXXRecordDecl, too.
11013 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
11014 // Check number of base classes.
11015 if (D1CXX->getNumBases() != D2CXX->getNumBases())
11016 return false;
11017
11018 // Check the base classes.
11019 for (CXXRecordDecl::base_class_const_iterator
11020 Base1 = D1CXX->bases_begin(),
11021 BaseEnd1 = D1CXX->bases_end(),
11022 Base2 = D2CXX->bases_begin();
11023 Base1 != BaseEnd1;
11024 ++Base1, ++Base2) {
11025 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
11026 return false;
11027 }
11028 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
11029 // If only RD2 is a C++ class, it should have zero base classes.
11030 if (D2CXX->getNumBases() > 0)
11031 return false;
11032 }
11033
11034 // Check the fields.
11035 RecordDecl::field_iterator Field2 = RD2->field_begin(),
11036 Field2End = RD2->field_end(),
11037 Field1 = RD1->field_begin(),
11038 Field1End = RD1->field_end();
11039 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
11040 if (!isLayoutCompatible(C, *Field1, *Field2))
11041 return false;
11042 }
11043 if (Field1 != Field1End || Field2 != Field2End)
11044 return false;
11045
11046 return true;
11047}
11048
11049/// \brief Check if two standard-layout unions are layout-compatible.
11050/// (C++11 [class.mem] p18)
11051bool isLayoutCompatibleUnion(ASTContext &C,
11052 RecordDecl *RD1,
11053 RecordDecl *RD2) {
11054 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011055 for (auto *Field2 : RD2->fields())
11056 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011057
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011058 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011059 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
11060 I = UnmatchedFields.begin(),
11061 E = UnmatchedFields.end();
11062
11063 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011064 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011065 bool Result = UnmatchedFields.erase(*I);
11066 (void) Result;
11067 assert(Result);
11068 break;
11069 }
11070 }
11071 if (I == E)
11072 return false;
11073 }
11074
11075 return UnmatchedFields.empty();
11076}
11077
11078bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
11079 if (RD1->isUnion() != RD2->isUnion())
11080 return false;
11081
11082 if (RD1->isUnion())
11083 return isLayoutCompatibleUnion(C, RD1, RD2);
11084 else
11085 return isLayoutCompatibleStruct(C, RD1, RD2);
11086}
11087
11088/// \brief Check if two types are layout-compatible in C++11 sense.
11089bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
11090 if (T1.isNull() || T2.isNull())
11091 return false;
11092
11093 // C++11 [basic.types] p11:
11094 // If two types T1 and T2 are the same type, then T1 and T2 are
11095 // layout-compatible types.
11096 if (C.hasSameType(T1, T2))
11097 return true;
11098
11099 T1 = T1.getCanonicalType().getUnqualifiedType();
11100 T2 = T2.getCanonicalType().getUnqualifiedType();
11101
11102 const Type::TypeClass TC1 = T1->getTypeClass();
11103 const Type::TypeClass TC2 = T2->getTypeClass();
11104
11105 if (TC1 != TC2)
11106 return false;
11107
11108 if (TC1 == Type::Enum) {
11109 return isLayoutCompatible(C,
11110 cast<EnumType>(T1)->getDecl(),
11111 cast<EnumType>(T2)->getDecl());
11112 } else if (TC1 == Type::Record) {
11113 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
11114 return false;
11115
11116 return isLayoutCompatible(C,
11117 cast<RecordType>(T1)->getDecl(),
11118 cast<RecordType>(T2)->getDecl());
11119 }
11120
11121 return false;
11122}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011123} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011124
11125//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
11126
11127namespace {
11128/// \brief Given a type tag expression find the type tag itself.
11129///
11130/// \param TypeExpr Type tag expression, as it appears in user's code.
11131///
11132/// \param VD Declaration of an identifier that appears in a type tag.
11133///
11134/// \param MagicValue Type tag magic value.
11135bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
11136 const ValueDecl **VD, uint64_t *MagicValue) {
11137 while(true) {
11138 if (!TypeExpr)
11139 return false;
11140
11141 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
11142
11143 switch (TypeExpr->getStmtClass()) {
11144 case Stmt::UnaryOperatorClass: {
11145 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
11146 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
11147 TypeExpr = UO->getSubExpr();
11148 continue;
11149 }
11150 return false;
11151 }
11152
11153 case Stmt::DeclRefExprClass: {
11154 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
11155 *VD = DRE->getDecl();
11156 return true;
11157 }
11158
11159 case Stmt::IntegerLiteralClass: {
11160 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
11161 llvm::APInt MagicValueAPInt = IL->getValue();
11162 if (MagicValueAPInt.getActiveBits() <= 64) {
11163 *MagicValue = MagicValueAPInt.getZExtValue();
11164 return true;
11165 } else
11166 return false;
11167 }
11168
11169 case Stmt::BinaryConditionalOperatorClass:
11170 case Stmt::ConditionalOperatorClass: {
11171 const AbstractConditionalOperator *ACO =
11172 cast<AbstractConditionalOperator>(TypeExpr);
11173 bool Result;
11174 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
11175 if (Result)
11176 TypeExpr = ACO->getTrueExpr();
11177 else
11178 TypeExpr = ACO->getFalseExpr();
11179 continue;
11180 }
11181 return false;
11182 }
11183
11184 case Stmt::BinaryOperatorClass: {
11185 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
11186 if (BO->getOpcode() == BO_Comma) {
11187 TypeExpr = BO->getRHS();
11188 continue;
11189 }
11190 return false;
11191 }
11192
11193 default:
11194 return false;
11195 }
11196 }
11197}
11198
11199/// \brief Retrieve the C type corresponding to type tag TypeExpr.
11200///
11201/// \param TypeExpr Expression that specifies a type tag.
11202///
11203/// \param MagicValues Registered magic values.
11204///
11205/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
11206/// kind.
11207///
11208/// \param TypeInfo Information about the corresponding C type.
11209///
11210/// \returns true if the corresponding C type was found.
11211bool GetMatchingCType(
11212 const IdentifierInfo *ArgumentKind,
11213 const Expr *TypeExpr, const ASTContext &Ctx,
11214 const llvm::DenseMap<Sema::TypeTagMagicValue,
11215 Sema::TypeTagData> *MagicValues,
11216 bool &FoundWrongKind,
11217 Sema::TypeTagData &TypeInfo) {
11218 FoundWrongKind = false;
11219
11220 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000011221 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011222
11223 uint64_t MagicValue;
11224
11225 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
11226 return false;
11227
11228 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000011229 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011230 if (I->getArgumentKind() != ArgumentKind) {
11231 FoundWrongKind = true;
11232 return false;
11233 }
11234 TypeInfo.Type = I->getMatchingCType();
11235 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
11236 TypeInfo.MustBeNull = I->getMustBeNull();
11237 return true;
11238 }
11239 return false;
11240 }
11241
11242 if (!MagicValues)
11243 return false;
11244
11245 llvm::DenseMap<Sema::TypeTagMagicValue,
11246 Sema::TypeTagData>::const_iterator I =
11247 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
11248 if (I == MagicValues->end())
11249 return false;
11250
11251 TypeInfo = I->second;
11252 return true;
11253}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011254} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011255
11256void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
11257 uint64_t MagicValue, QualType Type,
11258 bool LayoutCompatible,
11259 bool MustBeNull) {
11260 if (!TypeTagForDatatypeMagicValues)
11261 TypeTagForDatatypeMagicValues.reset(
11262 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
11263
11264 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
11265 (*TypeTagForDatatypeMagicValues)[Magic] =
11266 TypeTagData(Type, LayoutCompatible, MustBeNull);
11267}
11268
11269namespace {
11270bool IsSameCharType(QualType T1, QualType T2) {
11271 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
11272 if (!BT1)
11273 return false;
11274
11275 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
11276 if (!BT2)
11277 return false;
11278
11279 BuiltinType::Kind T1Kind = BT1->getKind();
11280 BuiltinType::Kind T2Kind = BT2->getKind();
11281
11282 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
11283 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
11284 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
11285 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
11286}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011287} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011288
11289void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
11290 const Expr * const *ExprArgs) {
11291 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
11292 bool IsPointerAttr = Attr->getIsPointer();
11293
11294 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
11295 bool FoundWrongKind;
11296 TypeTagData TypeInfo;
11297 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
11298 TypeTagForDatatypeMagicValues.get(),
11299 FoundWrongKind, TypeInfo)) {
11300 if (FoundWrongKind)
11301 Diag(TypeTagExpr->getExprLoc(),
11302 diag::warn_type_tag_for_datatype_wrong_kind)
11303 << TypeTagExpr->getSourceRange();
11304 return;
11305 }
11306
11307 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
11308 if (IsPointerAttr) {
11309 // Skip implicit cast of pointer to `void *' (as a function argument).
11310 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000011311 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000011312 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011313 ArgumentExpr = ICE->getSubExpr();
11314 }
11315 QualType ArgumentType = ArgumentExpr->getType();
11316
11317 // Passing a `void*' pointer shouldn't trigger a warning.
11318 if (IsPointerAttr && ArgumentType->isVoidPointerType())
11319 return;
11320
11321 if (TypeInfo.MustBeNull) {
11322 // Type tag with matching void type requires a null pointer.
11323 if (!ArgumentExpr->isNullPointerConstant(Context,
11324 Expr::NPC_ValueDependentIsNotNull)) {
11325 Diag(ArgumentExpr->getExprLoc(),
11326 diag::warn_type_safety_null_pointer_required)
11327 << ArgumentKind->getName()
11328 << ArgumentExpr->getSourceRange()
11329 << TypeTagExpr->getSourceRange();
11330 }
11331 return;
11332 }
11333
11334 QualType RequiredType = TypeInfo.Type;
11335 if (IsPointerAttr)
11336 RequiredType = Context.getPointerType(RequiredType);
11337
11338 bool mismatch = false;
11339 if (!TypeInfo.LayoutCompatible) {
11340 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
11341
11342 // C++11 [basic.fundamental] p1:
11343 // Plain char, signed char, and unsigned char are three distinct types.
11344 //
11345 // But we treat plain `char' as equivalent to `signed char' or `unsigned
11346 // char' depending on the current char signedness mode.
11347 if (mismatch)
11348 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
11349 RequiredType->getPointeeType())) ||
11350 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
11351 mismatch = false;
11352 } else
11353 if (IsPointerAttr)
11354 mismatch = !isLayoutCompatible(Context,
11355 ArgumentType->getPointeeType(),
11356 RequiredType->getPointeeType());
11357 else
11358 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
11359
11360 if (mismatch)
11361 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000011362 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011363 << TypeInfo.LayoutCompatible << RequiredType
11364 << ArgumentExpr->getSourceRange()
11365 << TypeTagExpr->getSourceRange();
11366}
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011367
11368void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
11369 CharUnits Alignment) {
11370 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
11371}
11372
11373void Sema::DiagnoseMisalignedMembers() {
11374 for (MisalignedMember &m : MisalignedMembers) {
Alex Lorenz014181e2016-10-05 09:27:48 +000011375 const NamedDecl *ND = m.RD;
11376 if (ND->getName().empty()) {
11377 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
11378 ND = TD;
11379 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011380 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
Alex Lorenz014181e2016-10-05 09:27:48 +000011381 << m.MD << ND << m.E->getSourceRange();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011382 }
11383 MisalignedMembers.clear();
11384}
11385
11386void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
11387 if (!T->isPointerType())
11388 return;
11389 if (isa<UnaryOperator>(E) &&
11390 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
11391 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
11392 if (isa<MemberExpr>(Op)) {
11393 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
11394 MisalignedMember(Op));
11395 if (MA != MisalignedMembers.end() &&
11396 Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment)
11397 MisalignedMembers.erase(MA);
11398 }
11399 }
11400}
11401
11402void Sema::RefersToMemberWithReducedAlignment(
11403 Expr *E,
11404 std::function<void(Expr *, RecordDecl *, ValueDecl *, CharUnits)> Action) {
11405 const auto *ME = dyn_cast<MemberExpr>(E);
11406 while (ME && isa<FieldDecl>(ME->getMemberDecl())) {
11407 QualType BaseType = ME->getBase()->getType();
11408 if (ME->isArrow())
11409 BaseType = BaseType->getPointeeType();
11410 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
11411
11412 ValueDecl *MD = ME->getMemberDecl();
11413 bool ByteAligned = Context.getTypeAlignInChars(MD->getType()).isOne();
11414 if (ByteAligned) // Attribute packed does not have any effect.
11415 break;
11416
11417 if (!ByteAligned &&
11418 (RD->hasAttr<PackedAttr>() || (MD->hasAttr<PackedAttr>()))) {
11419 CharUnits Alignment = std::min(Context.getTypeAlignInChars(MD->getType()),
11420 Context.getTypeAlignInChars(BaseType));
11421 // Notify that this expression designates a member with reduced alignment
11422 Action(E, RD, MD, Alignment);
11423 break;
11424 }
11425 ME = dyn_cast<MemberExpr>(ME->getBase());
11426 }
11427}
11428
11429void Sema::CheckAddressOfPackedMember(Expr *rhs) {
11430 using namespace std::placeholders;
11431 RefersToMemberWithReducedAlignment(
11432 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
11433 _2, _3, _4));
11434}
11435